lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
mit
ab902e453682a20bf2837c900ca769e71fc08730
0
jbrr/ski-free-test,jbrr/ski-free,jbrr/ski-free-test,jbrr/ski-free
var Skier = require('./skier'); var reportCollisions = require('./collision'); var obstacleGenerator = require('./obstacle-generator'); var yetiEnding = require('./yeti-generator'); var Yeti = require('./yeti'); var canvas = document.getElementById('skifree'); var ctx = canvas.getContext('2d'); var stopped = false; var spriteMapImg = new Image(); spriteMapImg.src = 'https://s3.amazonaws.com/jbrr-turing/assets/spritemap.png'; function keyPressed(event, skier) { if (event.keyCode === 37) { skier.moveLeft(); } else if (event.keyCode === 39) { skier.moveRight(); } } var stopCheck = function(skier, yeti) { if (Math.round(yeti.x) === Math.round(skier.x) && Math.round(yeti.y) === Math.round(skier.y)) { skier.lives = 0; } if (skier.lives === 0) { ctx.clearRect(0, 0, canvas.width, canvas.height); stopped = true; } }; var start = function(skier, yeti, obstacles, spriteMapImg) { if (stopped === false) { requestAnimationFrame(function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); skier.draw(spriteMapImg); obstacleGenerator(obstacles, skier, canvas, ctx); reportCollisions(obstacles, skier); yetiEnding(skier, yeti); stopCheck(skier, yeti); requestAnimationFrame(gameLoop); }); } }; function init() { document.addEventListener("keydown", function(event) { keyPressed(event, skier); }, false); var yeti = new Yeti({canvas: canvas, context: ctx }); var skier = new Skier({ canvas: canvas, context: ctx }); var obstacles = []; start(skier, yeti, obstacles); } init();
app/lib/index.js
var Skier = require('./skier'); var reportCollisions = require('./collision'); var obstacleGenerator = require('./obstacle-generator'); var yetiEnding = require('./yeti-generator'); var Yeti = require('./yeti'); var canvas = document.getElementById('skifree'); var ctx = canvas.getContext('2d'); var stopped = false; var spriteMapImg = new Image(); spriteMapImg.src = 'https://s3.amazonaws.com/jbrr-turing/assets/spritemap.png'; function keyPressed(event, skier) { if (event.keyCode === 37) { skier.moveLeft(); } else if (event.keyCode === 39) { skier.moveRight(); } } var stopCheck = function(skier, yeti) { if ((yeti.x === skier.x && yeti.y === skier.y) || skier.lives === 0) { context.clearRect(0, 0, canvas.width, canvas.height); stopped = true; } }; var start = function(skier, yeti, obstacles, spriteMapImg) { if (stopped === false) { requestAnimationFrame(function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); skier.draw(spriteMapImg); obstacleGenerator(obstacles, skier, canvas, ctx); reportCollisions(obstacles, skier); yetiEnding(skier, yeti); stopCheck(skier, yeti); console.log(stopped); requestAnimationFrame(gameLoop); }); } }; function init() { document.addEventListener("keydown", function(event) { keyPressed(event, skier); }, false); var yeti = new Yeti({canvas: canvas, context: ctx }); var skier = new Skier({ canvas: canvas, context: ctx }); var obstacles = []; start(skier, yeti, obstacles); } init();
Add ability to stop and clear the game if lives are equal to zero or the yeti attacks the skier.
app/lib/index.js
Add ability to stop and clear the game if lives are equal to zero or the yeti attacks the skier.
<ide><path>pp/lib/index.js <ide> } <ide> <ide> var stopCheck = function(skier, yeti) { <del> if ((yeti.x === skier.x && yeti.y === skier.y) || skier.lives === 0) { <del> context.clearRect(0, 0, canvas.width, canvas.height); <add> if (Math.round(yeti.x) === Math.round(skier.x) && Math.round(yeti.y) === Math.round(skier.y)) { <add> skier.lives = 0; <add> } <add> if (skier.lives === 0) { <add> ctx.clearRect(0, 0, canvas.width, canvas.height); <ide> stopped = true; <ide> } <ide> }; <ide> reportCollisions(obstacles, skier); <ide> yetiEnding(skier, yeti); <ide> stopCheck(skier, yeti); <del> console.log(stopped); <ide> requestAnimationFrame(gameLoop); <ide> }); <ide> }
Java
mit
d3f5a78334a17c991c6a34a01e9ac0474ee9c5a4
0
omor1/CSE360-Project
import java.sql.*; public class MySQLConnect { Connection conn = null; public static Connection ConnectDb() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://Localhost/student","root","root"); System.out.println("Connection work!"); return conn; } }
JavaMD2/src/MySQLConnect.java
import java.sql.*; import javax.swing.*; public class MySQLConnect { Connection conn = null; public static Connection ConnectDb(){ try{ Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://Localhost/student","root","root"); System.out.println("Connection work!"); return conn; }catch(Exception e){ JOptionPane.showMessageDialog(null,e); return null; } } }
JavaMD2/src/MySQLConnect.java: throws ClassNotFoundException, SQLException JavaMD2/src/MySQLConnect.java: formatting
JavaMD2/src/MySQLConnect.java
JavaMD2/src/MySQLConnect.java: throws ClassNotFoundException, SQLException JavaMD2/src/MySQLConnect.java: formatting
<ide><path>avaMD2/src/MySQLConnect.java <ide> import java.sql.*; <del>import javax.swing.*; <add> <ide> public class MySQLConnect { <ide> Connection conn = null; <del> public static Connection ConnectDb(){ <del> try{ <add> public static Connection ConnectDb() throws ClassNotFoundException, SQLException { <ide> Class.forName("com.mysql.jdbc.Driver"); <ide> Connection conn = DriverManager.getConnection("jdbc:mysql://Localhost/student","root","root"); <ide> System.out.println("Connection work!"); <ide> return conn; <del> }catch(Exception e){ <del> JOptionPane.showMessageDialog(null,e); <del> return null; <del> } <ide> } <ide> }
Java
apache-2.0
3a97efbd2393b76957ff3ecdfad7a5c30ed043f7
0
opetrovski/development,opetrovski/development,opetrovski/development,opetrovski/development,opetrovski/development
/******************************************************************************* * * Copyright FUJITSU LIMITED 2016 * * Creation Date: 16.05.2013 * *******************************************************************************/ package org.oscm.ui.filter; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import org.junit.Before; import org.junit.Test; import org.oscm.internal.intf.ConfigurationService; import org.oscm.internal.intf.TenantService; import org.oscm.internal.types.enumtypes.AuthenticationMode; import org.oscm.internal.types.enumtypes.ConfigurationKey; import org.oscm.internal.types.exception.NotExistentTenantException; import org.oscm.internal.types.exception.ObjectNotFoundException; import org.oscm.internal.vo.VOConfigurationSetting; import org.oscm.internal.vo.VOTenant; import org.oscm.tenant.bean.TenantServiceBean; import org.oscm.types.constants.Configuration; /** * @author stavreva * */ public class AuthenticationSettingsTest { private static final String ISSUER = "OSCM"; private static final String IDP = "http://idp.de:9080/openam/SSORedirect/metaAlias/idp"; private static final String IDP_UPPERCASE = IDP.toUpperCase(); private static final String IDP_CONTEXT_ROOT = "http://idp.de:9080/openam"; private static final String IDP_HTTP_METHOD = "POST"; private static final String IDP_KEYSTORE_PASS = "changeit"; private static final String BASE_URL = "http://www.example.de"; private AuthenticationSettings authSettings; private ConfigurationService cfgMock; private TenantService tenantService; private VOTenant mockTenant; @Before public void setup() throws Exception { tenantService = spy(new TenantServiceBean() { }); mockTenant = mock(VOTenant.class); doReturn(ISSUER).when(mockTenant).getIssuer(); doReturn(IDP).when(mockTenant).getIDPURL(); doReturn(IDP_HTTP_METHOD).when(mockTenant).getIdpHttpMethod(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getSigningKeystorePass(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getSigningKeystore(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getSigningKeyAlias(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getLogoutURL(); doReturn(mockTenant).when(tenantService).getTenantByTenantId(any(String.class)); doReturn(mockTenant).when(tenantService).findByTkey(any(String.class)); cfgMock = mock(ConfigurationService.class); } private void givenMock(AuthenticationMode authMode, String idpUrl) { doReturn( new VOConfigurationSetting(ConfigurationKey.AUTH_MODE, Configuration.GLOBAL_CONTEXT, authMode.name())).when( cfgMock).getVOConfigurationSetting(ConfigurationKey.AUTH_MODE, Configuration.GLOBAL_CONTEXT); doReturn( new VOConfigurationSetting(ConfigurationKey.SSO_IDP_URL, Configuration.GLOBAL_CONTEXT, idpUrl)).when(cfgMock) .getVOConfigurationSetting(ConfigurationKey.SSO_IDP_URL, Configuration.GLOBAL_CONTEXT); doReturn( new VOConfigurationSetting(ConfigurationKey.BASE_URL, Configuration.GLOBAL_CONTEXT, idpUrl)).when(cfgMock) .getVOConfigurationSetting(ConfigurationKey.BASE_URL, Configuration.GLOBAL_CONTEXT); authSettings = new AuthenticationSettings(tenantService, cfgMock); } @Test public void constructor() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then verify(cfgMock, times(1)).getVOConfigurationSetting( ConfigurationKey.AUTH_MODE, Configuration.GLOBAL_CONTEXT); } @Test public void isServiceProvider() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertTrue(authSettings.isServiceProvider()); } @Test public void isInternal() throws Exception { // given givenMock(AuthenticationMode.INTERNAL, IDP); // then assertTrue(authSettings.isInternal()); } @Test public void getIssuer() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(ISSUER, authSettings.getIssuer("tenantID")); } @Test public void getIdentityProviderURL() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP, authSettings.getIdentityProviderURL("tenantID")); } @Test public void getIdentityProviderURLContextRoot() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_CONTEXT_ROOT, authSettings.getIdentityProviderURLContextRoot("tenantID")); } @Test public void getIdentityProviderURLContextRoot_Uppercase() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP_UPPERCASE); // then assertEquals(IDP_CONTEXT_ROOT, authSettings.getIdentityProviderURLContextRoot("tenantID")); } @Test public void getConfigurationSetting_null() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); doReturn(null).when(cfgMock).getVOConfigurationSetting( ConfigurationKey.LOG_LEVEL, Configuration.GLOBAL_CONTEXT); // then assertNull(authSettings.getConfigurationSetting(cfgMock, ConfigurationKey.LOG_LEVEL)); } @Test public void getConfigurationSetting() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals("SAML_SP", authSettings.getConfigurationSetting(cfgMock, ConfigurationKey.AUTH_MODE)); } @Test public void getContextRoot_null() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertNull(authSettings.getContextRoot(null)); } @Test public void getContextRoot_empty() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertNull(authSettings.getContextRoot("")); } @Test public void getContextRoot_lessTokens() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertNull(authSettings.getContextRoot("http://www.idp.de/")); } @Test public void getContextRoot() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_CONTEXT_ROOT, authSettings.getContextRoot(IDP)); } @Test public void getIdentityProviderHttpMethod() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_HTTP_METHOD, authSettings.getIdentityProviderHttpMethod("tenantID")); } @Test public void getSigningKeystorePass() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeystorePass("tenantID")); } @Test public void getSigningKeystore() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeystore("tenantID")); } @Test public void getSigningKeyAlias() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeyAlias("tenantID")); } @Test public void getLogoutURL() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getLogoutURL("tenantID")); } @Test public void getTenantBlank() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); authSettings = spy(authSettings); doReturn(IDP_KEYSTORE_PASS).when(authSettings). getConfigurationSetting(cfgMock, ConfigurationKey.SSO_SIGNING_KEYSTORE_PASS); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeystorePass(null)); } @Test(expected = NotExistentTenantException.class) public void findByTKey() throws ObjectNotFoundException, NotExistentTenantException { // given givenMock(AuthenticationMode.SAML_SP, IDP); doThrow(new ObjectNotFoundException()).when(tenantService).findByTkey(anyString()); // then authSettings.getSigningKeystorePass("asdf"); } }
oscm-portal-unittests/javasrc/org/oscm/ui/filter/AuthenticationSettingsTest.java
/******************************************************************************* * * Copyright FUJITSU LIMITED 2016 * * Creation Date: 16.05.2013 * *******************************************************************************/ package org.oscm.ui.filter; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import org.junit.Before; import org.junit.Test; import org.oscm.internal.intf.ConfigurationService; import org.oscm.internal.intf.TenantService; import org.oscm.internal.types.enumtypes.AuthenticationMode; import org.oscm.internal.types.enumtypes.ConfigurationKey; import org.oscm.internal.types.exception.NotExistentTenantException; import org.oscm.internal.types.exception.ObjectNotFoundException; import org.oscm.internal.vo.VOConfigurationSetting; import org.oscm.internal.vo.VOTenant; import org.oscm.types.constants.Configuration; /** * @author stavreva * */ public class AuthenticationSettingsTest { private static final String ISSUER = "OSCM"; private static final String IDP = "http://idp.de:9080/openam/SSORedirect/metaAlias/idp"; private static final String IDP_UPPERCASE = IDP.toUpperCase(); private static final String IDP_CONTEXT_ROOT = "http://idp.de:9080/openam"; private static final String IDP_HTTP_METHOD = "POST"; private static final String IDP_KEYSTORE_PASS = "changeit"; private static final String BASE_URL = "http://www.example.de"; private AuthenticationSettings authSettings; private ConfigurationService cfgMock; private TenantService tenantService; private VOTenant mockTenant; @Before public void setup() throws Exception { tenantService = mock(TenantService.class); mockTenant = mock(VOTenant.class); doReturn(ISSUER).when(mockTenant).getIssuer(); doReturn(IDP).when(mockTenant).getIDPURL(); doReturn(IDP_HTTP_METHOD).when(mockTenant).getIdpHttpMethod(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getSigningKeystorePass(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getSigningKeystore(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getSigningKeyAlias(); doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getLogoutURL(); doReturn(mockTenant).when(tenantService).getTenantByTenantId(any(String.class)); cfgMock = mock(ConfigurationService.class); } private void givenMock(AuthenticationMode authMode, String idpUrl) { doReturn( new VOConfigurationSetting(ConfigurationKey.AUTH_MODE, Configuration.GLOBAL_CONTEXT, authMode.name())).when( cfgMock).getVOConfigurationSetting(ConfigurationKey.AUTH_MODE, Configuration.GLOBAL_CONTEXT); doReturn( new VOConfigurationSetting(ConfigurationKey.SSO_IDP_URL, Configuration.GLOBAL_CONTEXT, idpUrl)).when(cfgMock) .getVOConfigurationSetting(ConfigurationKey.SSO_IDP_URL, Configuration.GLOBAL_CONTEXT); doReturn( new VOConfigurationSetting(ConfigurationKey.BASE_URL, Configuration.GLOBAL_CONTEXT, idpUrl)).when(cfgMock) .getVOConfigurationSetting(ConfigurationKey.BASE_URL, Configuration.GLOBAL_CONTEXT); authSettings = new AuthenticationSettings(tenantService, cfgMock); } @Test public void constructor() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then verify(cfgMock, times(1)).getVOConfigurationSetting( ConfigurationKey.AUTH_MODE, Configuration.GLOBAL_CONTEXT); } @Test public void isServiceProvider() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertTrue(authSettings.isServiceProvider()); } @Test public void isInternal() throws Exception { // given givenMock(AuthenticationMode.INTERNAL, IDP); // then assertTrue(authSettings.isInternal()); } @Test public void getIssuer() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(ISSUER, authSettings.getIssuer("tenantID")); } @Test public void getIdentityProviderURL() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP, authSettings.getIdentityProviderURL("tenantID")); } @Test public void getIdentityProviderURLContextRoot() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_CONTEXT_ROOT, authSettings.getIdentityProviderURLContextRoot("tenantID")); } @Test public void getIdentityProviderURLContextRoot_Uppercase() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP_UPPERCASE); // then assertEquals(IDP_CONTEXT_ROOT, authSettings.getIdentityProviderURLContextRoot("tenantID")); } @Test public void getConfigurationSetting_null() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); doReturn(null).when(cfgMock).getVOConfigurationSetting( ConfigurationKey.LOG_LEVEL, Configuration.GLOBAL_CONTEXT); // then assertNull(authSettings.getConfigurationSetting(cfgMock, ConfigurationKey.LOG_LEVEL)); } @Test public void getConfigurationSetting() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals("SAML_SP", authSettings.getConfigurationSetting(cfgMock, ConfigurationKey.AUTH_MODE)); } @Test public void getContextRoot_null() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertNull(authSettings.getContextRoot(null)); } @Test public void getContextRoot_empty() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertNull(authSettings.getContextRoot("")); } @Test public void getContextRoot_lessTokens() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertNull(authSettings.getContextRoot("http://www.idp.de/")); } @Test public void getContextRoot() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_CONTEXT_ROOT, authSettings.getContextRoot(IDP)); } @Test public void getIdentityProviderHttpMethod() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_HTTP_METHOD, authSettings.getIdentityProviderHttpMethod("tenantID")); } @Test public void getSigningKeystorePass() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeystorePass("tenantID")); } @Test public void getSigningKeystore() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeystore("tenantID")); } @Test public void getSigningKeyAlias() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeyAlias("tenantID")); } @Test public void getLogoutURL() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getLogoutURL("tenantID")); } @Test public void getTenantBlank() throws Exception { // given givenMock(AuthenticationMode.SAML_SP, IDP); authSettings = spy(authSettings); doReturn(IDP_KEYSTORE_PASS).when(authSettings). getConfigurationSetting(cfgMock, ConfigurationKey.SSO_SIGNING_KEYSTORE_PASS); // then assertEquals(IDP_KEYSTORE_PASS, authSettings.getSigningKeystorePass(null)); } @Test(expected = NotExistentTenantException.class) public void findByTKey() throws ObjectNotFoundException, NotExistentTenantException { // given givenMock(AuthenticationMode.SAML_SP, IDP); doThrow(new ObjectNotFoundException()).when(tenantService).getTenantByTenantId(anyString()); // then authSettings.getSigningKeystorePass("asdf"); } }
fixed tests
oscm-portal-unittests/javasrc/org/oscm/ui/filter/AuthenticationSettingsTest.java
fixed tests
<ide><path>scm-portal-unittests/javasrc/org/oscm/ui/filter/AuthenticationSettingsTest.java <ide> import org.oscm.internal.types.exception.ObjectNotFoundException; <ide> import org.oscm.internal.vo.VOConfigurationSetting; <ide> import org.oscm.internal.vo.VOTenant; <add>import org.oscm.tenant.bean.TenantServiceBean; <ide> import org.oscm.types.constants.Configuration; <ide> <ide> /** <ide> <ide> @Before <ide> public void setup() throws Exception { <del> tenantService = mock(TenantService.class); <add> tenantService = spy(new TenantServiceBean() { <add> }); <ide> mockTenant = mock(VOTenant.class); <ide> doReturn(ISSUER).when(mockTenant).getIssuer(); <ide> doReturn(IDP).when(mockTenant).getIDPURL(); <ide> doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getSigningKeyAlias(); <ide> doReturn(IDP_KEYSTORE_PASS).when(mockTenant).getLogoutURL(); <ide> doReturn(mockTenant).when(tenantService).getTenantByTenantId(any(String.class)); <add> doReturn(mockTenant).when(tenantService).findByTkey(any(String.class)); <ide> cfgMock = mock(ConfigurationService.class); <ide> } <ide> <ide> public void findByTKey() throws ObjectNotFoundException, NotExistentTenantException { <ide> // given <ide> givenMock(AuthenticationMode.SAML_SP, IDP); <del> doThrow(new ObjectNotFoundException()).when(tenantService).getTenantByTenantId(anyString()); <add> doThrow(new ObjectNotFoundException()).when(tenantService).findByTkey(anyString()); <ide> <ide> // then <ide> authSettings.getSigningKeystorePass("asdf");
Java
apache-2.0
c268bfe5d64ee3ca159555f76de96709983334d6
0
007slm/nutz,livvyguo/nutz,elkan1788/nutz,happyday517/nutz,yaotj/nutz,ansjsun/nutz,sdgdsffdsfff/nutz,ansjsun/nutz,happyday517/nutz,sunshinefather/nutz,InsideZhou/nutz,sdgdsffdsfff/nutz,ansjsun/nutz,joansmith/nutz,007slm/nutz,dxxfire/nutz,InsideZhou/nutz,fengshao0907/nutz,QinAIns/nutz,fengshao0907/nutz,nutzam/nutz,sunshinefather/nutz,s24963386/nutz,livvyguo/nutz,elkan1788/nutz,yaotj/nutz,nutzam/nutz,sunshinefather/nutz,joansmith/nutz,dxxfire/nutz,livvyguo/nutz,elkan1788/nutz,007slm/nutz,nutzam/nutz,nutzam/nutz,ansjsun/nutz,fengshao0907/nutz,dxxfire/nutz,lzxz1234/nutz,ywjno/nutz,altihou/nutz,ywjno/nutz,altihou/nutz,sunshinefather/nutz,s24963386/nutz,altihou/nutz,nutzam/nutz,ywjno/nutz,fengshao0907/nutz,dxxfire/nutz,s24963386/nutz,happyday517/nutz,lzxz1234/nutz,elkan1788/nutz,yaotj/nutz,sdgdsffdsfff/nutz,joansmith/nutz,sdgdsffdsfff/nutz,ansjsun/nutz,altihou/nutz,ywjno/nutz,lzxz1234/nutz,InsideZhou/nutz,QinAIns/nutz,InsideZhou/nutz,happyday517/nutz,joansmith/nutz,QinAIns/nutz,livvyguo/nutz,ywjno/nutz,lzxz1234/nutz
package org.nutz.lang; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Map.Entry; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.nutz.castor.Castors; import org.nutz.castor.FailToCastObjectException; import org.nutz.json.Json; import org.nutz.lang.stream.StringInputStream; import org.nutz.lang.stream.StringOutputStream; import org.nutz.lang.stream.StringReader; import org.nutz.lang.stream.StringWriter; /** * 这些帮助函数让 Java 的某些常用功能变得更简单 * * @author zozoh([email protected]) * @author wendal([email protected]) * @author bonyfish([email protected]) */ public abstract class Lang { public static ComboException comboThrow(Throwable... es) { ComboException ce = new ComboException(); for (Throwable e : es) ce.add(e); return ce; } /** * @return 一个未实现的运行时异常 */ public static RuntimeException noImplement() { return new RuntimeException("Not implement yet!"); } /** * 根据格式化字符串,生成运行时异常 * * @param format * 格式 * @param args * 参数 * @return 运行时异常 */ public static RuntimeException makeThrow(String format, Object... args) { return new RuntimeException(String.format(format, args)); } /** * 根据格式化字符串,生成一个指定的异常。 * * @param classOfT * 异常类型, 需要有一个字符串为参数的构造函数 * @param format * 格式 * @param args * 参数 * @return 异常对象 */ public static <T extends Throwable> T makeThrow(Class<T> classOfT, String format, Object... args) { return Mirror.me(classOfT).born(String.format(format, args)); } /** * 将抛出对象包裹成运行时异常,并增加自己的描述 * * @param e * 抛出对象 * @param fmt * 格式 * @param args * 参数 * @return 运行时异常 */ public static RuntimeException wrapThrow(Throwable e, String fmt, Object... args) { return new RuntimeException(String.format(fmt, args), e); } /** * 用运行时异常包裹抛出对象,如果抛出对象本身就是运行时异常,则直接返回。 * <p> * 如果是 InvocationTargetException,那么将其剥离,只包裹其 TargetException * * @param e * 抛出对象 * @return 运行时异常 */ public static RuntimeException wrapThrow(Throwable e) { if (e instanceof RuntimeException) return (RuntimeException) e; if (e instanceof InvocationTargetException) return wrapThrow(((InvocationTargetException) e).getTargetException()); return new RuntimeException(e); } /** * 用一个指定可抛出类型来包裹一个抛出对象。这个指定的可抛出类型需要有一个构造函数 接受 Throwable 类型的对象 * * @param e * 抛出对象 * @param wrapper * 包裹类型 * @return 包裹后对象 */ @SuppressWarnings("unchecked") public static <T extends Throwable> T wrapThrow(Throwable e, Class<T> wrapper) { if (wrapper.isAssignableFrom(e.getClass())) return (T) e; return Mirror.me(wrapper).born(e); } public static Throwable unwrapThrow(Throwable e) { if (e == null) return null; if (e instanceof InvocationTargetException) { InvocationTargetException itE = (InvocationTargetException) e; if (itE.getTargetException() != null) return unwrapThrow(itE.getTargetException()); } if (e.getCause() != null) return unwrapThrow(e.getCause()); return e; } /** * 判断两个对象是否相等。 这个函数用处是: * <ul> * <li>可以容忍 null * <li>可以容忍不同类型的 Number * <li>对数组,集合, Map 会深层比较 * </ul> * 当然,如果你重写的 equals 方法会优先 * * @param a1 * 比较对象1 * @param a2 * 比较对象2 * @return 是否相等 */ @SuppressWarnings("unchecked") public static boolean equals(Object a1, Object a2) { if (a1 == a2) return true; if (a1 == null || a2 == null) return false; if (a1.equals(a2)) return true; if (a1 instanceof Number) return a2 instanceof Number && a1.toString().equals(a2.toString()); if (a1 instanceof Map && a2 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) a1; Map<?, ?> m2 = (Map<?, ?>) a2; if (m1.size() != m2.size()) return false; for (Entry<?, ?> e : m1.entrySet()) { Object key = e.getKey(); if (!m2.containsKey(key) || !equals(m1.get(key), m2.get(key))) return false; } return true; } else if (a1.getClass().isArray()) { if (a2.getClass().isArray()) { int len = Array.getLength(a1); if (len != Array.getLength(a2)) return false; for (int i = 0; i < len; i++) { if (!equals(Array.get(a1, i), Array.get(a2, i))) return false; } return true; } else if (a2 instanceof List) { return equals(a1, Lang.collection2array((List<Object>) a2, Object.class)); } return false; } else if (a1 instanceof List) { if (a2 instanceof List) { List<?> l1 = (List<?>) a1; List<?> l2 = (List<?>) a2; if (l1.size() != l2.size()) return false; int i = 0; for (Iterator<?> it = l1.iterator(); it.hasNext();) { if (!equals(it.next(), l2.get(i++))) return false; } return true; } else if (a2.getClass().isArray()) { return equals(Lang.collection2array((List<Object>) a1, Object.class), a2); } return false; } else if (a1 instanceof Collection && a2 instanceof Collection) { Collection<?> c1 = (Collection<?>) a1; Collection<?> c2 = (Collection<?>) a2; if (c1.size() != c2.size()) return false; return c1.containsAll(c2) && c2.containsAll(c1); } return false; } /** * 判断一个数组内是否包括某一个对象。 它的比较将通过 equals(Object,Object) 方法 * * @param array * 数组 * @param ele * 对象 * @return true 包含 false 不包含 */ public static <T> boolean contains(T[] array, T ele) { if (null == array) return false; for (T e : array) { if (equals(e, ele)) return true; } return false; } /** * 从一个文本输入流读取所有内容,并将该流关闭 * * @param reader * 文本输入流 * @return 输入流所有内容 */ public static String readAll(Reader reader) { if (!(reader instanceof BufferedReader)) reader = new BufferedReader(reader); try { StringBuilder sb = new StringBuilder(); char[] data = new char[64]; int len; while (true) { if ((len = reader.read(data)) == -1) break; sb.append(data, 0, len); } return sb.toString(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(reader); } } /** * 将一段字符串写入一个文本输出流,并将该流关闭 * * @param writer * 文本输出流 * @param str * 字符串 */ public static void writeAll(Writer writer, String str) { try { writer.write(str); writer.flush(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(writer); } } /** * 根据一段文本模拟出一个输入流对象 <br/> * * @param cs * 文本 * @return 输出流对象 */ public static InputStream ins(CharSequence cs) { return new StringInputStream(cs); } /** * 根据一段文本模拟出一个文本输入流对象 * * @param cs * 文本 * @return 文本输出流对象 */ public static Reader inr(CharSequence cs) { return new StringReader(cs); } /** * 根据一个 StringBuilder 模拟一个文本输出流对象 * * @param sb * StringBuilder 对象 * @return 文本输出流对象 */ public static Writer opw(StringBuilder sb) { return new StringWriter(sb); } /** * 根据一个 StringBuilder 模拟一个输出流对象 * * @param sb * StringBuilder 对象 * @return 输出流对象 */ public static StringOutputStream ops(StringBuilder sb) { return new StringOutputStream(sb); } /** * 较方便的创建一个数组,比如: * * <pre> * Pet[] pets = Lang.array(pet1, pet2, pet3); * </pre> * * @param eles * 可变参数 * @return 数组对象 */ public static <T> T[] array(T... eles) { return eles; } /** * 较方便的创建一个列表,比如: * * <pre> * List《Pet》 pets = Lang.list(pet1, pet2, pet3); * </pre> * * @param eles * 可变参数 * @return 列表对象 */ public static <T> List<T> list(T... eles) { List<T> list = new ArrayList<T>(eles.length); for (T ele : eles) list.add(ele); return list; } /** * 将多个数组,合并成一个数组。如果这些数组为空,则返回 null * * @param arys * 数组对象 * @return 合并后的数组对象 */ @SuppressWarnings("unchecked") public static <T> T[] merge(T[]... arys) { Queue<T> list = new LinkedList<T>(); for (T[] ary : arys) if (null != ary) for (T e : ary) if (null != e) list.add(e); if (list.isEmpty()) return null; Class<T> type = (Class<T>) list.peek().getClass(); return list.toArray((T[]) Array.newInstance(type, list.size())); } /** * 将一个对象添加成为一个数组的第一个元素,从而生成一个新的数组 * * @param e * 对象 * @param eles * 数组 * @return 新数组 */ @SuppressWarnings("unchecked") public static <T> T[] arrayFirst(T e, T[] eles) { try { if (null == eles || eles.length == 0) { T[] arr = (T[]) Array.newInstance(e.getClass(), 1); arr[0] = e; return arr; } T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1); arr[0] = e; for (int i = 0; i < eles.length; i++) { arr[i + 1] = eles[i]; } return arr; } catch (NegativeArraySizeException e1) { throw Lang.wrapThrow(e1); } } /** * 将一个对象添加成为一个数组的最后一个元素,从而生成一个新的数组 * * @param e * 对象 * @param eles * 数组 * @return 新数组 */ @SuppressWarnings("unchecked") public static <T> T[] arrayLast(T[] eles, T e) { try { if (null == eles || eles.length == 0) { T[] arr = (T[]) Array.newInstance(e.getClass(), 1); arr[0] = e; return arr; } T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1); for (int i = 0; i < eles.length; i++) { arr[i] = eles[i]; } arr[eles.length] = e; return arr; } catch (NegativeArraySizeException e1) { throw Lang.wrapThrow(e1); } } /** * 将一个数组转换成字符串 * <p> * 所有的元素都被格式化字符串包裹。 这个格式话字符串只能有一个占位符, %s, %d 等,均可,请视你的数组内容而定 * * @param fmt * 格式 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concatBy(String fmt, T[] objs) { StringBuilder sb = new StringBuilder(); for (T obj : objs) sb.append(String.format(fmt, obj)); return sb; } /** * 将一个数组转换成字符串 * <p> * 所有的元素都被格式化字符串包裹。 这个格式话字符串只能有一个占位符, %s, %d 等,均可,请视你的数组内容而定 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param ptn * 格式 * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concatBy(String ptn, Object c, T[] objs) { StringBuilder sb = new StringBuilder(); for (T obj : objs) sb.append(String.format(ptn, obj)).append(c); if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1); return sb; } /** * 将一个数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(Object c, T[] objs) { StringBuilder sb = new StringBuilder(); if (null == objs || 0 == objs.length) return sb; sb.append(objs[0]); for (int i = 1; i < objs.length; i++) sb.append(c).append(objs[i]); return sb; } /** * 将一个长整型数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param vals * 数组 * @return 拼合后的字符串 */ public static StringBuilder concat(Object c, long[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(c).append(vals[i]); return sb; } /** * 将一个整型数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param vals * 数组 * @return 拼合后的字符串 */ public static StringBuilder concat(Object c, int[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(c).append(vals[i]); return sb; } /** * 将一个数组的部分元素转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param offset * 开始元素的下标 * @param len * 元素数量 * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(int offset, int len, Object c, T[] objs) { StringBuilder sb = new StringBuilder(); if (null == objs || len < 0 || 0 == objs.length) return sb; if (offset < objs.length) { sb.append(objs[offset]); for (int i = 1; i < len && i + offset < objs.length; i++) { sb.append(c).append(objs[i + offset]); } } return sb; } /** * 将一个数组所有元素拼合成一个字符串 * * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(T[] objs) { StringBuilder sb = new StringBuilder(); for (T e : objs) sb.append(e.toString()); return sb; } /** * 将一个数组部分元素拼合成一个字符串 * * @param offset * 开始元素的下标 * @param len * 元素数量 * @param array * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(int offset, int len, T[] array) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append(array[i + offset].toString()); } return sb; } /** * 将一个集合转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param coll * 集合 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(Object c, Collection<T> coll) { StringBuilder sb = new StringBuilder(); if (null == coll || coll.isEmpty()) return sb; Iterator<T> it = coll.iterator(); sb.append(it.next()); while (it.hasNext()) sb.append(c).append(it.next()); return sb; } /** * 将一个或者多个数组填入一个集合。 * * @param <C> * 集合类型 * @param <T> * 数组元素类型 * @param coll * 集合 * @param objss * 数组 (数目可变) * @return 集合对象 */ public static <C extends Collection<T>, T> C fill(C coll, T[]... objss) { for (T[] objs : objss) for (T obj : objs) coll.add(obj); return coll; } /** * 将一个集合变成 Map。 * * @param mapClass * Map 的类型 * @param coll * 集合对象 * @param keyFieldName * 采用集合中元素的哪个一个字段为键。 * @return Map 对象 */ public static <T extends Map<Object, Object>> Map<?, ?> collection2map( Class<T> mapClass, Collection<?> coll, String keyFieldName) { if (null == coll) return null; Map<Object, Object> map = createMap(mapClass); if (coll.size() > 0) { Iterator<?> it = coll.iterator(); Object obj = it.next(); Mirror<?> mirror = Mirror.me(obj.getClass()); Object key = mirror.getValue(obj, keyFieldName); map.put(key, obj); for (; it.hasNext();) { obj = it.next(); key = mirror.getValue(obj, keyFieldName); map.put(key, obj); } } return map; } /** * 将集合变成 ArrayList * * @param col * 集合对象 * @return 列表对象 */ @SuppressWarnings("unchecked") public static <E> List<E> collection2list(Collection<E> col) { if (null == col) return null; if (col.size() == 0) return new ArrayList<E>(0); Class<E> eleType = (Class<E>) col.iterator().next().getClass(); return collection2list(col, eleType); } /** * 将集合编程变成指定类型的列表 * * @param col * 集合对象 * @param eleType * 列表类型 * @return 列表对象 */ public static <E> List<E> collection2list(Collection<?> col, Class<E> eleType) { if (null == col) return null; List<E> list = new ArrayList<E>(col.size()); for (Object obj : col) list.add(Castors.me().castTo(obj, eleType)); return list; } /** * 将集合变成数组,数组的类型为集合的第一个元素的类型。如果集合为空,则返回 null * * @param coll * 集合对象 * @return 数组 */ @SuppressWarnings("unchecked") public static <E> E[] collection2array(Collection<E> coll) { if (null == coll) return null; if (coll.size() == 0) return (E[]) new Object[0]; Class<E> eleType = (Class<E>) Lang.first(coll).getClass(); return collection2array(coll, eleType); } /** * 将集合变成指定类型的数组 * * @param col * 集合对象 * @param eleType * 数组元素类型 * @return 数组 */ @SuppressWarnings("unchecked") public static <E> E[] collection2array(Collection<?> col, Class<E> eleType) { if (null == col) return null; Object re = Array.newInstance(eleType, col.size()); int i = 0; for (Iterator<?> it = col.iterator(); it.hasNext();) { Object obj = it.next(); if (null == obj) Array.set(re, i++, null); else Array.set(re, i++, Castors.me().castTo(obj, eleType)); } return (E[]) re; } /** * 将一个数组变成 Map * * @param mapClass * Map 的类型 * @param array * 数组 * @param keyFieldName * 采用集合中元素的哪个一个字段为键。 * @return Map 对象 */ public static <T extends Map<Object, Object>> Map<?, ?> array2map( Class<T> mapClass, Object array, String keyFieldName) { if (null == array) return null; Map<Object, Object> map = createMap(mapClass); int len = Array.getLength(array); if (len > 0) { Object obj = Array.get(array, 0); Mirror<?> mirror = Mirror.me(obj.getClass()); for (int i = 0; i < len; i++) { obj = Array.get(array, i); Object key = mirror.getValue(obj, keyFieldName); map.put(key, obj); } } return map; } private static <T extends Map<Object, Object>> Map<Object, Object> createMap(Class<T> mapClass) { Map<Object, Object> map; try { map = mapClass.newInstance(); } catch (Exception e) { map = new HashMap<Object, Object>(); } if (!mapClass.isAssignableFrom(map.getClass())) { throw Lang.makeThrow("Fail to create map [%s]", mapClass.getName()); } return map; } /** * 将数组转换成一个列表。 * * @param array * 原始数组 * @return 新列表 * * @see org.nutz.castor.Castors */ public static <T> List<T> array2list(T[] array) { if (null == array) return null; List<T> re = new ArrayList<T>(array.length); for (T obj : array) re.add(obj); return re; } /** * 将数组转换成一个列表。将会采用 Castor 来深层转换数组元素 * * @param array * 原始数组 * @param eleType * 新列表的元素类型 * @return 新列表 * * @see org.nutz.castor.Castors */ public static <T, E> List<E> array2list(Object array, Class<E> eleType) { if (null == array) return null; int len = Array.getLength(array); List<E> re = new ArrayList<E>(len); for (int i = 0; i < len; i++) { Object obj = Array.get(array, i); re.add(Castors.me().castTo(obj, eleType)); } return re; } /** * 将数组转换成另外一种类型的数组。将会采用 Castor 来深层转换数组元素 * * @param array * 原始数组 * @param eleType * 新数组的元素类型 * @return 新数组 * @throws FailToCastObjectException * * @see org.nutz.castor.Castors */ public static Object array2array(Object array, Class<?> eleType) throws FailToCastObjectException { if (null == array) return null; int len = Array.getLength(array); Object re = Array.newInstance(eleType, len); for (int i = 0; i < len; i++) { Array.set(re, i, Castors.me().castTo(Array.get(array, i), eleType)); } return re; } /** * 将数组转换成Object[] 数组。将会采用 Castor 来深层转换数组元素 * * @param args * 原始数组 * @param pts * 新数组的元素类型 * @return 新数组 * @throws FailToCastObjectException * * @see org.nutz.castor.Castors */ public static <T> Object[] array2ObjectArray(T[] args, Class<?>[] pts) throws FailToCastObjectException { if (null == args) return null; Object[] newArgs = new Object[args.length]; for (int i = 0; i < args.length; i++) { newArgs[i] = Castors.me().castTo(args[i], pts[i]); } return newArgs; } /** * 根据一个 Map,和给定的对象类型,创建一个新的 JAVA 对象 * * @param src * Map 对象 * @param toType * JAVA 对象类型 * @return JAVA 对象 * @throws FailToCastObjectException */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T map2Object(Map<?, ?> src, Class<T> toType) throws FailToCastObjectException { if (null == toType) throw new FailToCastObjectException("target type is Null"); // 类型相同 if (toType == Map.class) return (T) src; // 也是一种 Map if (Map.class.isAssignableFrom(toType)) { Map map; try { map = (Map) toType.newInstance(); map.putAll(src); return (T) map; } catch (Exception e) { throw new FailToCastObjectException("target type fail to born!", e); } } // 数组 if (toType.isArray()) return (T) Lang.collection2array(src.values(), toType.getComponentType()); // List if (List.class == toType) { return (T) Lang.collection2list(src.values()); } // POJO Mirror<T> mirror = Mirror.me(toType); T obj = mirror.born(); for (Field field : mirror.getFields()) { if (src.containsKey(field.getName())) { Object v = src.get(field.getName()); if (null == v) continue; Class<?> ft = field.getType(); Object vv = null; // 集合 if (v instanceof Collection) { Collection c = (Collection) v; // 集合到数组 if (ft.isArray()) { vv = Lang.collection2array(c, ft.getComponentType()); } // 集合到集合 else { // 创建 Collection newCol; Class eleType = Mirror.getGenericTypes(field, 0); if (ft == List.class) { newCol = new ArrayList(c.size()); } else if (ft == Set.class) { newCol = new LinkedHashSet(); } else { try { newCol = (Collection) ft.newInstance(); } catch (Exception e) { throw Lang.wrapThrow(e); } } // 赋值 for (Object ele : c) { newCol.add(Castors.me().castTo(ele, eleType)); } vv = newCol; } } // Map else if (v instanceof Map) { // 创建 final Map map; if (ft == Map.class) { map = new HashMap(); } else { try { map = (Map) ft.newInstance(); } catch (Exception e) { throw new FailToCastObjectException("target type fail to born!", e); } } // 赋值 final Class<?> valType = Mirror.getGenericTypes(field, 1); each(v, new Each<Entry>() { public void invoke(int i, Entry en, int length) { map.put(en.getKey(), Castors.me().castTo(en.getValue(), valType)); } }); vv = map; } else { vv = Castors.me().castTo(v, ft); } mirror.setValue(obj, field, vv); } } return obj; } /** * 根据一段字符串,生成一个 Map 对象。 * * @param str * 参照 JSON 标准的字符串,但是可以没有前后的大括号 * @return Map 对象 */ @SuppressWarnings("unchecked") public static Map<String, Object> map(String str) { if (null == str) return null; if ((str.length() > 0 && str.charAt(0) == '{') && str.endsWith("}")) return (Map<String, Object>) Json.fromJson(str); return (Map<String, Object>) Json.fromJson("{" + str + "}"); } /** * 根据一段字符串,生成一个List 对象。 * * @param str * 参照 JSON 标准的字符串,但是可以没有前后的中括号 * @return List 对象 */ @SuppressWarnings("unchecked") public static List<Object> list4(String str) { if (null == str) return null; if ((str.length() > 0 && str.charAt(0) == '[') && str.endsWith("]")) return (List<Object>) Json.fromJson(str); return (List<Object>) Json.fromJson("[" + str + "]"); } /** * 获得一个对象的长度。它可以接受: * <ul> * <li>null : 0 * <li>数组 * <li>集合 * <li>Map * <li>一般 Java 对象。 返回 1 * </ul> * 如果你想让你的 Java 对象返回不是 1 , 请在对象中声明 length() 函数 * * @param obj * @return 对象长度 */ public static int length(Object obj) { if (null == obj) return 0; if (obj.getClass().isArray()) { return Array.getLength(obj); } else if (obj instanceof Collection<?>) { return ((Collection<?>) obj).size(); } else if (obj instanceof Map<?, ?>) { return ((Map<?, ?>) obj).size(); } try { return (Integer) Mirror.me(obj.getClass()).invoke(obj, "length"); } catch (Exception e) {} return 1; } /** * 取得第一个对象,无论是 数组,集合还是 Map。如果是一个一般 JAVA 对象,则返回自身 * * @param obj * 任意对象 * @return 第一个代表对象 */ public static Object first(Object obj) { final Object[] re = new Object[1]; each(obj, new Each<Object>() { public void invoke(int i, Object obj, int length) throws ExitLoop { re[0] = obj; Lang.Break(); } }); return re[0]; } /** * 获取集合中的第一个元素,如果集合为空,返回 null * * @param coll * 集合 * @return 第一个元素 */ public static <T> T first(Collection<T> coll) { if (null == coll || coll.isEmpty()) return null; return coll.iterator().next(); } /** * 获得表中的第一个名值对 * * @param map * 表 * @return 第一个名值对 */ public static <K, V> Entry<K, V> first(Map<K, V> map) { if (null == map || map.isEmpty()) return null; return map.entrySet().iterator().next(); } /** * 打断 each 循环 */ public static void Break() throws ExitLoop { throw new ExitLoop(); } /** * 用回调的方式,遍历一个对象,可以支持遍历 * <ul> * <li>数组 * <li>集合 * <li>Map * <li>单一元素 * </ul> * * @param obj * 对象 * @param callback * 回调 */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> void each(Object obj, Each<T> callback) { if (null == obj || null == callback) return; try { Class<T> eType = Mirror.getTypeParam(callback.getClass(), 0); if (obj.getClass().isArray()) { int len = Array.getLength(obj); for (int i = 0; i < len; i++) try { callback.invoke(i, (T) Array.get(obj, i), len); } catch (ExitLoop e) { break; } } else if (obj instanceof Collection) { int len = ((Collection) obj).size(); int i = 0; for (Iterator<T> it = ((Collection) obj).iterator(); it.hasNext();) try { callback.invoke(i++, it.next(), len); } catch (ExitLoop e) { break; } } else if (obj instanceof Map) { Map map = (Map) obj; int len = map.size(); int i = 0; if (null != eType && eType != Object.class && eType.isAssignableFrom(Entry.class)) { for (Object v : map.entrySet()) try { callback.invoke(i++, (T) v, len); } catch (ExitLoop e) { break; } } else { for (Object v : map.entrySet()) try { callback.invoke(i++, (T) ((Entry) v).getValue(), len); } catch (ExitLoop e) { break; } } } else try { callback.invoke(0, (T) obj, 1); } catch (ExitLoop e) {} } catch (LoopException e) { throw Lang.wrapThrow(e.getCause()); } } /** * 将一个抛出对象的异常堆栈,显示成一个字符串 * * @param e * 抛出对象 * @return 异常堆栈文本 */ public static String getStackTrace(Throwable e) { StringBuilder sb = new StringBuilder(); StringOutputStream sbo = new StringOutputStream(sb); PrintStream ps = new PrintStream(sbo); e.printStackTrace(ps); ps.flush(); return sbo.getStringBuilder().toString(); } /** * 将字符串解析成 boolean 值,支持更多的字符串 * <ul> * <li>1 | 0 * <li>yes | no * <li>on | off * <li>true | false * </ul> * * @param s * @return 布尔值 */ public static boolean parseBoolean(String s) { if (null == s || s.length() == 0) return false; if (s.length() > 5) return true; if ("0".equals(s)) return false; s = s.toLowerCase(); return !"false".equals(s) && !"off".equals(s) && !"no".equals(s); } /** * 帮你快速获得一个 DocumentBuilder,方便 XML 解析。 * * @return 一个 DocumentBuilder 对象 * @throws ParserConfigurationException */ public static DocumentBuilder xmls() throws ParserConfigurationException { return DocumentBuilderFactory.newInstance().newDocumentBuilder(); } /** * 对Thread.sleep(long)的简单封装,不抛出任何异常 * * @param millisecond * 休眠时间 */ public void quiteSleep(long millisecond) { try { if (millisecond > 0) Thread.sleep(millisecond); } catch (Throwable e) {} } @SuppressWarnings("unchecked") private static <T extends Map<String, Object>> void obj2map(Object obj, T map, Map<Object, Object> memo) { if (null == obj || memo.containsKey(obj)) return; memo.put(obj, ""); Mirror<?> mirror = Mirror.me(obj.getClass()); Field[] flds = mirror.getFields(); for (Field fld : flds) { Object v = mirror.getValue(obj, fld); if (null == v) { map.put(fld.getName(), null); } Mirror<?> mr = Mirror.me(fld.getType()); if (mr.isNumber() || mr.isBoolean() || mr.isChar() || mr.isStringLike() || mr.isDateTimeLike()) { map.put(fld.getName(), v); } else if (memo.containsKey(v)) { map.put(fld.getName(), null); } else { T sub; try { sub = (T) map.getClass().newInstance(); } catch (Exception e) { throw Lang.wrapThrow(e); } obj2map(v, sub, memo); map.put(fld.getName(), sub); } } } /** * 将对象转换成 Map * * @param obj * POJO 对象 * @return Map 对象 */ @SuppressWarnings("unchecked") public static Map<String, Object> obj2map(Object obj) { return obj2map(obj, HashMap.class); } /** * 将对象转换成 Map * * @param <T> * @param obj * POJO 对象 * @param mapType * Map 的类型 * @return Map 对象 */ public static <T extends Map<String, Object>> T obj2map(Object obj, Class<T> mapType) { try { T map = mapType.newInstance(); Lang.obj2map(obj, map, new HashMap<Object, Object>()); return map; } catch (Exception e) { throw Lang.wrapThrow(e); } } /** * 返回一个集合对象的枚举对象。实际上就是对 Iterator 接口的一个封装 * * @param col * 集合对象 * @return 枚举对象 */ public static <T> Enumeration<T> enumeration(Collection<T> col) { final Iterator<T> it = col.iterator(); return new Enumeration<T>() { public boolean hasMoreElements() { return it.hasNext(); } public T nextElement() { return it.next(); } }; } /** * 将字符数组强制转换成字节数组。如果字符为双字节编码,则会丢失信息 * * @param cs * 字符数组 * @return 字节数组 */ public static byte[] toBytes(char[] cs) { byte[] bs = new byte[cs.length]; for (int i = 0; i < cs.length; i++) bs[i] = (byte) cs[i]; return bs; } /** * 将整数数组强制转换成字节数组。整数的高位将会被丢失 * * @param is * 整数数组 * @return 字节数组 */ public static byte[] toBytes(int[] is) { byte[] bs = new byte[is.length]; for (int i = 0; i < is.length; i++) bs[i] = (byte) is[i]; return bs; } /** * 判断当前系统是否为Windows * * @return true 如果当前系统为Windows系统 */ public static boolean isWin() { try { String os = System.getenv("OS"); return os != null && os.indexOf("Windows") > -1; } catch (Throwable e) { return false; } } /** * 使用当前线程的ClassLoader加载给定的类 * * @param className * 类的全称 * @return 给定的类 * @throws ClassNotFoundException * 如果无法用当前线程的ClassLoader加载 */ public static Class<?> loadClass(String className) throws ClassNotFoundException { try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { return Class.forName(className); } } }
src/org/nutz/lang/Lang.java
package org.nutz.lang; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Map.Entry; import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.nutz.castor.Castors; import org.nutz.castor.FailToCastObjectException; import org.nutz.json.Json; import org.nutz.lang.stream.StringInputStream; import org.nutz.lang.stream.StringOutputStream; import org.nutz.lang.stream.StringReader; import org.nutz.lang.stream.StringWriter; /** * 这些帮助函数让 Java 的某些常用功能变得更简单 * * @author zozoh([email protected]) * @author wendal([email protected]) * @author bonyfish([email protected]) */ public abstract class Lang { public static ComboException comboThrow(Throwable... es) { ComboException ce = new ComboException(); for (Throwable e : es) ce.add(e); return ce; } /** * @return 一个未实现的运行时异常 */ public static RuntimeException noImplement() { return new RuntimeException("Not implement yet!"); } /** * 根据格式化字符串,生成运行时异常 * * @param format * 格式 * @param args * 参数 * @return 运行时异常 */ public static RuntimeException makeThrow(String format, Object... args) { return new RuntimeException(String.format(format, args)); } /** * 根据格式化字符串,生成一个指定的异常。 * * @param classOfT * 异常类型, 需要有一个字符串为参数的构造函数 * @param format * 格式 * @param args * 参数 * @return 异常对象 */ public static <T extends Throwable> T makeThrow(Class<T> classOfT, String format, Object... args) { return Mirror.me(classOfT).born(String.format(format, args)); } /** * 将抛出对象包裹成运行时异常,并增加自己的描述 * * @param e * 抛出对象 * @param fmt * 格式 * @param args * 参数 * @return 运行时异常 */ public static RuntimeException wrapThrow(Throwable e, String fmt, Object... args) { return new RuntimeException(String.format(fmt, args), e); } /** * 用运行时异常包裹抛出对象,如果抛出对象本身就是运行时异常,则直接返回。 * <p> * 如果是 InvocationTargetException,那么将其剥离,只包裹其 TargetException * * @param e * 抛出对象 * @return 运行时异常 */ public static RuntimeException wrapThrow(Throwable e) { if (e instanceof RuntimeException) return (RuntimeException) e; if (e instanceof InvocationTargetException) return wrapThrow(((InvocationTargetException) e).getTargetException()); return new RuntimeException(e); } /** * 用一个指定可抛出类型来包裹一个抛出对象。这个指定的可抛出类型需要有一个构造函数 接受 Throwable 类型的对象 * * @param e * 抛出对象 * @param wrapper * 包裹类型 * @return 包裹后对象 */ @SuppressWarnings("unchecked") public static <T extends Throwable> T wrapThrow(Throwable e, Class<T> wrapper) { if (wrapper.isAssignableFrom(e.getClass())) return (T) e; return Mirror.me(wrapper).born(e); } public static Throwable unwrapThrow(Throwable e) { if (e == null) return null; if (e instanceof InvocationTargetException) { InvocationTargetException itE = (InvocationTargetException) e; if (itE.getTargetException() != null) return unwrapThrow(itE.getTargetException()); } if (e.getCause() != null) return unwrapThrow(e.getCause()); return e; } /** * 判断两个对象是否相等。 这个函数用处是: * <ul> * <li>可以容忍 null * <li>可以容忍不同类型的 Number * <li>对数组,集合, Map 会深层比较 * </ul> * 当然,如果你重写的 equals 方法会优先 * * @param a1 * 比较对象1 * @param a2 * 比较对象2 * @return 是否相等 */ @SuppressWarnings("unchecked") public static boolean equals(Object a1, Object a2) { if (a1 == a2) return true; if (a1 == null || a2 == null) return false; if (a1.equals(a2)) return true; if (a1 instanceof Number) return a2 instanceof Number && a1.toString().equals(a2.toString()); if (a1 instanceof Map && a2 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) a1; Map<?, ?> m2 = (Map<?, ?>) a2; if (m1.size() != m2.size()) return false; for (Entry<?, ?> e : m1.entrySet()) { Object key = e.getKey(); if (!m2.containsKey(key) || !equals(m1.get(key), m2.get(key))) return false; } return true; } else if (a1.getClass().isArray()) { if (a2.getClass().isArray()) { int len = Array.getLength(a1); if (len != Array.getLength(a2)) return false; for (int i = 0; i < len; i++) { if (!equals(Array.get(a1, i), Array.get(a2, i))) return false; } return true; } else if (a2 instanceof List) { return equals(a1, Lang.collection2array((List<Object>) a2, Object.class)); } return false; } else if (a1 instanceof List) { if (a2 instanceof List) { List<?> l1 = (List<?>) a1; List<?> l2 = (List<?>) a2; if (l1.size() != l2.size()) return false; int i = 0; for (Iterator<?> it = l1.iterator(); it.hasNext();) { if (!equals(it.next(), l2.get(i++))) return false; } return true; } else if (a2.getClass().isArray()) { return equals(Lang.collection2array((List<Object>) a1, Object.class), a2); } return false; } else if (a1 instanceof Collection && a2 instanceof Collection) { Collection<?> c1 = (Collection<?>) a1; Collection<?> c2 = (Collection<?>) a2; if (c1.size() != c2.size()) return false; return c1.containsAll(c2) && c2.containsAll(c1); } return false; } /** * 判断一个数组内是否包括某一个对象。 它的比较将通过 equals(Object,Object) 方法 * * @param array * 数组 * @param ele * 对象 * @return true 包含 false 不包含 */ public static <T> boolean contains(T[] array, T ele) { if (null == array) return false; for (T e : array) { if (equals(e, ele)) return true; } return false; } /** * 从一个文本输入流读取所有内容,并将该流关闭 * * @param reader * 文本输入流 * @return 输入流所有内容 */ public static String readAll(Reader reader) { if (!(reader instanceof BufferedReader)) reader = new BufferedReader(reader); try { StringBuilder sb = new StringBuilder(); char[] data = new char[64]; int len; while (true) { if ((len = reader.read(data)) == -1) break; sb.append(data, 0, len); } return sb.toString(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(reader); } } /** * 将一段字符串写入一个文本输出流,并将该流关闭 * * @param writer * 文本输出流 * @param str * 字符串 */ public static void writeAll(Writer writer, String str) { try { writer.write(str); writer.flush(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { Streams.safeClose(writer); } } /** * 根据一段文本模拟出一个输入流对象 <br/> * * @param cs * 文本 * @return 输出流对象 */ public static InputStream ins(CharSequence cs) { return new StringInputStream(cs); } /** * 根据一段文本模拟出一个文本输入流对象 * * @param cs * 文本 * @return 文本输出流对象 */ public static Reader inr(CharSequence cs) { return new StringReader(cs); } /** * 根据一个 StringBuilder 模拟一个文本输出流对象 * * @param sb * StringBuilder 对象 * @return 文本输出流对象 */ public static Writer opw(StringBuilder sb) { return new StringWriter(sb); } /** * 根据一个 StringBuilder 模拟一个输出流对象 * * @param sb * StringBuilder 对象 * @return 输出流对象 */ public static StringOutputStream ops(StringBuilder sb) { return new StringOutputStream(sb); } /** * 较方便的创建一个数组,比如: * * <pre> * Pet[] pets = Lang.array(pet1, pet2, pet3); * </pre> * * @param eles * 可变参数 * @return 数组对象 */ public static <T> T[] array(T... eles) { return eles; } /** * 较方便的创建一个列表,比如: * * <pre> * List《Pet》 pets = Lang.list(pet1, pet2, pet3); * </pre> * * @param eles * 可变参数 * @return 列表对象 */ public static <T> List<T> list(T... eles) { List<T> list = new ArrayList<T>(eles.length); for (T ele : eles) list.add(ele); return list; } /** * 将多个数组,合并成一个数组。如果这些数组为空,则返回 null * * @param arys * 数组对象 * @return 合并后的数组对象 */ @SuppressWarnings("unchecked") public static <T> T[] merge(T[]... arys) { Queue<T> list = new LinkedList<T>(); for (T[] ary : arys) if (null != ary) for (T e : ary) if (null != e) list.add(e); if (list.isEmpty()) return null; Class<T> type = (Class<T>) list.peek().getClass(); return list.toArray((T[]) Array.newInstance(type, list.size())); } /** * 将一个对象添加成为一个数组的第一个元素,从而生成一个新的数组 * * @param e * 对象 * @param eles * 数组 * @return 新数组 */ @SuppressWarnings("unchecked") public static <T> T[] arrayFirst(T e, T[] eles) { try { if (null == eles || eles.length == 0) { T[] arr = (T[]) Array.newInstance(e.getClass(), 1); arr[0] = e; return arr; } T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1); arr[0] = e; for (int i = 0; i < eles.length; i++) { arr[i + 1] = eles[i]; } return arr; } catch (NegativeArraySizeException e1) { throw Lang.wrapThrow(e1); } } /** * 将一个对象添加成为一个数组的最后一个元素,从而生成一个新的数组 * * @param e * 对象 * @param eles * 数组 * @return 新数组 */ @SuppressWarnings("unchecked") public static <T> T[] arrayLast(T[] eles, T e) { try { if (null == eles || eles.length == 0) { T[] arr = (T[]) Array.newInstance(e.getClass(), 1); arr[0] = e; return arr; } T[] arr = (T[]) Array.newInstance(eles.getClass().getComponentType(), eles.length + 1); for (int i = 0; i < eles.length; i++) { arr[i] = eles[i]; } arr[eles.length] = e; return arr; } catch (NegativeArraySizeException e1) { throw Lang.wrapThrow(e1); } } /** * 将一个数组转换成字符串 * <p> * 所有的元素都被格式化字符串包裹。 这个格式话字符串只能有一个占位符, %s, %d 等,均可,请视你的数组内容而定 * * @param fmt * 格式 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concatBy(String fmt, T[] objs) { StringBuilder sb = new StringBuilder(); for (T obj : objs) sb.append(String.format(fmt, obj)); return sb; } /** * 将一个数组转换成字符串 * <p> * 所有的元素都被格式化字符串包裹。 这个格式话字符串只能有一个占位符, %s, %d 等,均可,请视你的数组内容而定 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param ptn * 格式 * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concatBy(String ptn, Object c, T[] objs) { StringBuilder sb = new StringBuilder(); for (T obj : objs) sb.append(String.format(ptn, obj)).append(c); if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1); return sb; } /** * 将一个数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(Object c, T[] objs) { StringBuilder sb = new StringBuilder(); if (null == objs || 0 == objs.length) return sb; sb.append(objs[0]); for (int i = 1; i < objs.length; i++) sb.append(c).append(objs[i]); return sb; } /** * 将一个长整型数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param vals * 数组 * @return 拼合后的字符串 */ public static StringBuilder concat(Object c, long[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(c).append(vals[i]); return sb; } /** * 将一个整型数组转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param vals * 数组 * @return 拼合后的字符串 */ public static StringBuilder concat(Object c, int[] vals) { StringBuilder sb = new StringBuilder(); if (null == vals || 0 == vals.length) return sb; sb.append(vals[0]); for (int i = 1; i < vals.length; i++) sb.append(c).append(vals[i]); return sb; } /** * 将一个数组的部分元素转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param offset * 开始元素的下标 * @param len * 元素数量 * @param c * 分隔符 * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(int offset, int len, Object c, T[] objs) { StringBuilder sb = new StringBuilder(); if (null == objs || len < 0 || 0 == objs.length) return sb; if (offset < objs.length) { sb.append(objs[offset]); for (int i = 1; i < len && i + offset < objs.length; i++) { sb.append(c).append(objs[i + offset]); } } return sb; } /** * 将一个数组所有元素拼合成一个字符串 * * @param objs * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(T[] objs) { StringBuilder sb = new StringBuilder(); for (T e : objs) sb.append(e.toString()); return sb; } /** * 将一个数组部分元素拼合成一个字符串 * * @param offset * 开始元素的下标 * @param len * 元素数量 * @param array * 数组 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(int offset, int len, T[] array) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { sb.append(array[i + offset].toString()); } return sb; } /** * 将一个集合转换成字符串 * <p> * 每个元素之间,都会用一个给定的字符分隔 * * @param c * 分隔符 * @param coll * 集合 * @return 拼合后的字符串 */ public static <T> StringBuilder concat(Object c, Collection<T> coll) { StringBuilder sb = new StringBuilder(); if (null == coll || coll.isEmpty()) return sb; Iterator<T> it = coll.iterator(); sb.append(it.next()); while (it.hasNext()) sb.append(c).append(it.next()); return sb; } /** * 将一个或者多个数组填入一个集合。 * * @param <C> * 集合类型 * @param <T> * 数组元素类型 * @param coll * 集合 * @param objss * 数组 (数目可变) * @return 集合对象 */ public static <C extends Collection<T>, T> C fill(C coll, T[]... objss) { for (T[] objs : objss) for (T obj : objs) coll.add(obj); return coll; } /** * 将一个集合变成 Map。 * * @param mapClass * Map 的类型 * @param coll * 集合对象 * @param keyFieldName * 采用集合中元素的哪个一个字段为键。 * @return Map 对象 */ public static <T extends Map<Object, Object>> Map<?, ?> collection2map( Class<T> mapClass, Collection<?> coll, String keyFieldName) { if (null == coll) return null; Map<Object, Object> map = createMap(mapClass); if (coll.size() > 0) { Iterator<?> it = coll.iterator(); Object obj = it.next(); Mirror<?> mirror = Mirror.me(obj.getClass()); Object key = mirror.getValue(obj, keyFieldName); map.put(key, obj); for (; it.hasNext();) { obj = it.next(); key = mirror.getValue(obj, keyFieldName); map.put(key, obj); } } return map; } /** * 将集合变成 ArrayList * * @param col * 集合对象 * @return 列表对象 */ @SuppressWarnings("unchecked") public static <E> List<E> collection2list(Collection<E> col) { if (null == col) return null; if (col.size() == 0) return new ArrayList<E>(0); Class<E> eleType = (Class<E>) col.iterator().next().getClass(); return collection2list(col, eleType); } /** * 将集合编程变成指定类型的列表 * * @param col * 集合对象 * @param classOfList * 列表类型 * @return 列表对象 */ public static <E> List<E> collection2list(Collection<?> col, Class<E> eleType) { if (null == col) return null; List<E> list = new ArrayList<E>(col.size()); for (Object obj : col) list.add(Castors.me().castTo(obj, eleType)); return list; } /** * 将集合变成数组,数组的类型为集合的第一个元素的类型。如果集合为空,则返回 null * * @param coll * 集合对象 * @return 数组 */ @SuppressWarnings("unchecked") public static <E> E[] collection2array(Collection<E> coll) { if (null == coll) return null; if (coll.size() == 0) return (E[]) new Object[0]; Class<E> eleType = (Class<E>) Lang.first(coll).getClass(); return collection2array(coll, eleType); } /** * 将集合变成指定类型的数组 * * @param col * 集合对象 * @param eleType * 数组元素类型 * @return 数组 */ @SuppressWarnings("unchecked") public static <E> E[] collection2array(Collection<?> col, Class<E> eleType) { if (null == col) return null; Object re = Array.newInstance(eleType, col.size()); int i = 0; for (Iterator<?> it = col.iterator(); it.hasNext();) { Object obj = it.next(); if (null == obj) Array.set(re, i++, null); else Array.set(re, i++, Castors.me().castTo(obj, eleType)); } return (E[]) re; } /** * 将一个数组变成 Map * * @param mapClass * Map 的类型 * @param array * 数组 * @param keyFieldName * 采用集合中元素的哪个一个字段为键。 * @return Map 对象 */ public static <T extends Map<Object, Object>> Map<?, ?> array2map( Class<T> mapClass, Object array, String keyFieldName) { if (null == array) return null; Map<Object, Object> map = createMap(mapClass); int len = Array.getLength(array); if (len > 0) { Object obj = Array.get(array, 0); Mirror<?> mirror = Mirror.me(obj.getClass()); for (int i = 0; i < len; i++) { obj = Array.get(array, i); Object key = mirror.getValue(obj, keyFieldName); map.put(key, obj); } } return map; } private static <T extends Map<Object, Object>> Map<Object, Object> createMap(Class<T> mapClass) { Map<Object, Object> map; try { map = mapClass.newInstance(); } catch (Exception e) { map = new HashMap<Object, Object>(); } if (!mapClass.isAssignableFrom(map.getClass())) { throw Lang.makeThrow("Fail to create map [%s]", mapClass.getName()); } return map; } /** * 将数组转换成一个列表。 * * @param array * 原始数组 * @return 新列表 * * @see org.nutz.castor.Castors */ public static <T> List<T> array2list(T[] array) { if (null == array) return null; List<T> re = new ArrayList<T>(array.length); for (T obj : array) re.add(obj); return re; } /** * 将数组转换成一个列表。将会采用 Castor 来深层转换数组元素 * * @param array * 原始数组 * @param eleType * 新列表的元素类型 * @return 新列表 * * @see org.nutz.castor.Castors */ public static <T, E> List<E> array2list(Object array, Class<E> eleType) { if (null == array) return null; int len = Array.getLength(array); List<E> re = new ArrayList<E>(len); for (int i = 0; i < len; i++) { Object obj = Array.get(array, i); re.add(Castors.me().castTo(obj, eleType)); } return re; } /** * 将数组转换成另外一种类型的数组。将会采用 Castor 来深层转换数组元素 * * @param array * 原始数组 * @param eleType * 新数组的元素类型 * @return 新数组 * @throws FailToCastObjectException * * @see org.nutz.castor.Castors */ public static Object array2array(Object array, Class<?> eleType) throws FailToCastObjectException { if (null == array) return null; int len = Array.getLength(array); Object re = Array.newInstance(eleType, len); for (int i = 0; i < len; i++) { Array.set(re, i, Castors.me().castTo(Array.get(array, i), eleType)); } return re; } /** * 将数组转换成Object[] 数组。将会采用 Castor 来深层转换数组元素 * * @param args * 原始数组 * @param pts * 新数组的元素类型 * @return 新数组 * @throws FailToCastObjectException * * @see org.nutz.castor.Castors */ public static <T> Object[] array2ObjectArray(T[] args, Class<?>[] pts) throws FailToCastObjectException { if (null == args) return null; Object[] newArgs = new Object[args.length]; for (int i = 0; i < args.length; i++) { newArgs[i] = Castors.me().castTo(args[i], pts[i]); } return newArgs; } /** * 根据一个 Map,和给定的对象类型,创建一个新的 JAVA 对象 * * @param src * Map 对象 * @param toType * JAVA 对象类型 * @return JAVA 对象 * @throws FailToCastObjectException */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T map2Object(Map<?, ?> src, Class<T> toType) throws FailToCastObjectException { if (null == toType) throw new FailToCastObjectException("target type is Null"); // 类型相同 if (toType == Map.class) return (T) src; // 也是一种 Map if (Map.class.isAssignableFrom(toType)) { Map map; try { map = (Map) toType.newInstance(); map.putAll(src); return (T) map; } catch (Exception e) { throw new FailToCastObjectException("target type fail to born!", e); } } // 数组 if (toType.isArray()) return (T) Lang.collection2array(src.values(), toType.getComponentType()); // List if (List.class == toType) { return (T) Lang.collection2list(src.values()); } // POJO Mirror<T> mirror = Mirror.me(toType); T obj = mirror.born(); for (Field field : mirror.getFields()) { if (src.containsKey(field.getName())) { Object v = src.get(field.getName()); if (null == v) continue; Class<?> ft = field.getType(); Object vv = null; // 集合 if (v instanceof Collection) { Collection c = (Collection) v; // 集合到数组 if (ft.isArray()) { vv = Lang.collection2array(c, ft.getComponentType()); } // 集合到集合 else { // 创建 Collection newCol; Class eleType = Mirror.getGenericTypes(field, 0); if (ft == List.class) { newCol = new ArrayList(c.size()); } else if (ft == Set.class) { newCol = new LinkedHashSet(); } else { try { newCol = (Collection) ft.newInstance(); } catch (Exception e) { throw Lang.wrapThrow(e); } } // 赋值 for (Object ele : c) { newCol.add(Castors.me().castTo(ele, eleType)); } vv = newCol; } } // Map else if (v instanceof Map) { // 创建 final Map map; if (ft == Map.class) { map = new HashMap(); } else { try { map = (Map) ft.newInstance(); } catch (Exception e) { throw new FailToCastObjectException("target type fail to born!", e); } } // 赋值 final Class<?> valType = Mirror.getGenericTypes(field, 1); each(v, new Each<Entry>() { public void invoke(int i, Entry en, int length) { map.put(en.getKey(), Castors.me().castTo(en.getValue(), valType)); } }); vv = map; } else { vv = Castors.me().castTo(v, ft); } mirror.setValue(obj, field, vv); } } return obj; } /** * 根据一段字符串,生成一个 Map 对象。 * * @param str * 参照 JSON 标准的字符串,但是可以没有前后的大括号 * @return Map 对象 */ @SuppressWarnings("unchecked") public static Map<String, Object> map(String str) { if (null == str) return null; if ((str.length() > 0 && str.charAt(0) == '{') && str.endsWith("}")) return (Map<String, Object>) Json.fromJson(str); return (Map<String, Object>) Json.fromJson("{" + str + "}"); } /** * 根据一段字符串,生成一个List 对象。 * * @param str * 参照 JSON 标准的字符串,但是可以没有前后的中括号 * @return List 对象 */ @SuppressWarnings("unchecked") public static List<Object> list4(String str) { if (null == str) return null; if ((str.length() > 0 && str.charAt(0) == '[') && str.endsWith("]")) return (List<Object>) Json.fromJson(str); return (List<Object>) Json.fromJson("[" + str + "]"); } /** * 获得一个对象的长度。它可以接受: * <ul> * <li>null : 0 * <li>数组 * <li>集合 * <li>Map * <li>一般 Java 对象。 返回 1 * </ul> * 如果你想让你的 Java 对象返回不是 1 , 请在对象中声明 length() 函数 * * @param obj * @return 对象长度 */ public static int length(Object obj) { if (null == obj) return 0; if (obj.getClass().isArray()) { return Array.getLength(obj); } else if (obj instanceof Collection<?>) { return ((Collection<?>) obj).size(); } else if (obj instanceof Map<?, ?>) { return ((Map<?, ?>) obj).size(); } try { return (Integer) Mirror.me(obj.getClass()).invoke(obj, "length"); } catch (Exception e) {} return 1; } /** * 取得第一个对象,无论是 数组,集合还是 Map。如果是一个一般 JAVA 对象,则返回自身 * * @param obj * 任意对象 * @return 第一个代表对象 */ public static Object first(Object obj) { final Object[] re = new Object[1]; each(obj, new Each<Object>() { public void invoke(int i, Object obj, int length) throws ExitLoop { re[0] = obj; Lang.Break(); } }); return re[0]; } /** * 获取集合中的第一个元素,如果集合为空,返回 null * * @param coll * 集合 * @return 第一个元素 */ public static <T> T first(Collection<T> coll) { if (null == coll || coll.isEmpty()) return null; return coll.iterator().next(); } /** * 获得表中的第一个名值对 * * @param map * 表 * @return 第一个名值对 */ public static <K, V> Entry<K, V> first(Map<K, V> map) { if (null == map || map.isEmpty()) return null; return map.entrySet().iterator().next(); } /** * 打断 each 循环 */ public static void Break() throws ExitLoop { throw new ExitLoop(); } /** * 用回调的方式,遍历一个对象,可以支持遍历 * <ul> * <li>数组 * <li>集合 * <li>Map * <li>单一元素 * </ul> * * @param obj * 对象 * @param callback * 回调 */ @SuppressWarnings({"unchecked", "rawtypes"}) public static <T> void each(Object obj, Each<T> callback) { if (null == obj || null == callback) return; try { Class<T> eType = Mirror.getTypeParam(callback.getClass(), 0); if (obj.getClass().isArray()) { int len = Array.getLength(obj); for (int i = 0; i < len; i++) try { callback.invoke(i, (T) Array.get(obj, i), len); } catch (ExitLoop e) { break; } } else if (obj instanceof Collection) { int len = ((Collection) obj).size(); int i = 0; for (Iterator<T> it = ((Collection) obj).iterator(); it.hasNext();) try { callback.invoke(i++, it.next(), len); } catch (ExitLoop e) { break; } } else if (obj instanceof Map) { Map map = (Map) obj; int len = map.size(); int i = 0; if (null != eType && eType != Object.class && eType.isAssignableFrom(Entry.class)) { for (Object v : map.entrySet()) try { callback.invoke(i++, (T) v, len); } catch (ExitLoop e) { break; } } else { for (Object v : map.entrySet()) try { callback.invoke(i++, (T) ((Entry) v).getValue(), len); } catch (ExitLoop e) { break; } } } else try { callback.invoke(0, (T) obj, 1); } catch (ExitLoop e) {} } catch (LoopException e) { throw Lang.wrapThrow(e.getCause()); } } /** * 将一个抛出对象的异常堆栈,显示成一个字符串 * * @param e * 抛出对象 * @return 异常堆栈文本 */ public static String getStackTrace(Throwable e) { StringBuilder sb = new StringBuilder(); StringOutputStream sbo = new StringOutputStream(sb); PrintStream ps = new PrintStream(sbo); e.printStackTrace(ps); ps.flush(); return sbo.getStringBuilder().toString(); } /** * 将字符串解析成 boolean 值,支持更多的字符串 * <ul> * <li>1 | 0 * <li>yes | no * <li>on | off * <li>true | false * </ul> * * @param s * @return 布尔值 */ public static boolean parseBoolean(String s) { if (null == s || s.length() == 0) return false; if (s.length() > 5) return true; if ("0".equals(s)) return false; s = s.toLowerCase(); return !"false".equals(s) && !"off".equals(s) && !"no".equals(s); } /** * 帮你快速获得一个 DocumentBuilder,方便 XML 解析。 * * @return 一个 DocumentBuilder 对象 * @throws ParserConfigurationException */ public static DocumentBuilder xmls() throws ParserConfigurationException { return DocumentBuilderFactory.newInstance().newDocumentBuilder(); } /** * 对Thread.sleep(long)的简单封装,不抛出任何异常 * * @param millisecond * 休眠时间 */ public void quiteSleep(long millisecond) { try { if (millisecond > 0) Thread.sleep(millisecond); } catch (Throwable e) {} } @SuppressWarnings("unchecked") private static <T extends Map<String, Object>> void obj2map(Object obj, T map, Map<Object, Object> memo) { if (null == obj || memo.containsKey(obj)) return; memo.put(obj, ""); Mirror<?> mirror = Mirror.me(obj.getClass()); Field[] flds = mirror.getFields(); for (Field fld : flds) { Object v = mirror.getValue(obj, fld); if (null == v) { map.put(fld.getName(), null); } Mirror<?> mr = Mirror.me(fld.getType()); if (mr.isNumber() || mr.isBoolean() || mr.isChar() || mr.isStringLike() || mr.isDateTimeLike()) { map.put(fld.getName(), v); } else if (memo.containsKey(v)) { map.put(fld.getName(), null); } else { T sub; try { sub = (T) map.getClass().newInstance(); } catch (Exception e) { throw Lang.wrapThrow(e); } obj2map(v, sub, memo); map.put(fld.getName(), sub); } } } /** * 将对象转换成 Map * * @param obj * POJO 对象 * @return Map 对象 */ @SuppressWarnings("unchecked") public static Map<String, Object> obj2map(Object obj) { return obj2map(obj, HashMap.class); } /** * 将对象转换成 Map * * @param <T> * @param obj * POJO 对象 * @param mapType * Map 的类型 * @return Map 对象 */ public static <T extends Map<String, Object>> T obj2map(Object obj, Class<T> mapType) { try { T map = mapType.newInstance(); Lang.obj2map(obj, map, new HashMap<Object, Object>()); return map; } catch (Exception e) { throw Lang.wrapThrow(e); } } /** * 返回一个集合对象的枚举对象。实际上就是对 Iterator 接口的一个封装 * * @param col * 集合对象 * @return 枚举对象 */ public static <T> Enumeration<T> enumeration(Collection<T> col) { final Iterator<T> it = col.iterator(); return new Enumeration<T>() { public boolean hasMoreElements() { return it.hasNext(); } public T nextElement() { return it.next(); } }; } /** * 将字符数组强制转换成字节数组。如果字符为双字节编码,则会丢失信息 * * @param cs * 字符数组 * @return 字节数组 */ public static byte[] toBytes(char[] cs) { byte[] bs = new byte[cs.length]; for (int i = 0; i < cs.length; i++) bs[i] = (byte) cs[i]; return bs; } /** * 将整数数组强制转换成字节数组。整数的高位将会被丢失 * * @param is * 整数数组 * @return 字节数组 */ public static byte[] toBytes(int[] is) { byte[] bs = new byte[is.length]; for (int i = 0; i < is.length; i++) bs[i] = (byte) is[i]; return bs; } /** * 判断当前系统是否为Windows * * @return true 如果当前系统为Windows系统 */ public static boolean isWin() { try { String os = System.getenv("OS"); return os != null && os.indexOf("Windows") > -1; } catch (Throwable e) { return false; } } /** * 使用当前线程的ClassLoader加载给定的类 * * @param className * 类的全称 * @return 给定的类 * @throws ClassNotFoundException * 如果无法用当前线程的ClassLoader加载 */ public static Class<?> loadClass(String className) throws ClassNotFoundException { try { return Thread.currentThread().getContextClassLoader().loadClass(className); } catch (ClassNotFoundException e) { return Class.forName(className); } } }
修正JDoc错误 git-svn-id: b73081968da82ba525d2f11eaba64c47babea5dc@1662 423f10f2-e3a4-11dd-a6ea-a32d6b26a33d
src/org/nutz/lang/Lang.java
修正JDoc错误
<ide><path>rc/org/nutz/lang/Lang.java <ide> * <ide> * @param col <ide> * 集合对象 <del> * @param classOfList <add> * @param eleType <ide> * 列表类型 <ide> * @return 列表对象 <ide> */
Java
agpl-3.0
75b5dc6fe33eaa9220b2701368717b8342129509
0
creative-quant/voltdb,ingted/voltdb,deerwalk/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,migue/voltdb,deerwalk/voltdb,wolffcm/voltdb,creative-quant/voltdb,ingted/voltdb,VoltDB/voltdb,creative-quant/voltdb,flybird119/voltdb,zuowang/voltdb,zuowang/voltdb,paulmartel/voltdb,ingted/voltdb,zuowang/voltdb,VoltDB/voltdb,ingted/voltdb,creative-quant/voltdb,kumarrus/voltdb,kobronson/cs-voltdb,wolffcm/voltdb,paulmartel/voltdb,kumarrus/voltdb,migue/voltdb,migue/voltdb,ingted/voltdb,migue/voltdb,kumarrus/voltdb,wolffcm/voltdb,paulmartel/voltdb,kumarrus/voltdb,zuowang/voltdb,flybird119/voltdb,deerwalk/voltdb,paulmartel/voltdb,wolffcm/voltdb,flybird119/voltdb,kumarrus/voltdb,VoltDB/voltdb,kumarrus/voltdb,simonzhangsm/voltdb,migue/voltdb,migue/voltdb,kobronson/cs-voltdb,deerwalk/voltdb,VoltDB/voltdb,kobronson/cs-voltdb,VoltDB/voltdb,VoltDB/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,wolffcm/voltdb,wolffcm/voltdb,migue/voltdb,flybird119/voltdb,wolffcm/voltdb,zuowang/voltdb,VoltDB/voltdb,zuowang/voltdb,kobronson/cs-voltdb,creative-quant/voltdb,migue/voltdb,paulmartel/voltdb,kumarrus/voltdb,wolffcm/voltdb,ingted/voltdb,flybird119/voltdb,kobronson/cs-voltdb,paulmartel/voltdb,zuowang/voltdb,ingted/voltdb,paulmartel/voltdb,simonzhangsm/voltdb,kumarrus/voltdb,deerwalk/voltdb,ingted/voltdb,flybird119/voltdb,flybird119/voltdb,deerwalk/voltdb,kobronson/cs-voltdb,creative-quant/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,kobronson/cs-voltdb,simonzhangsm/voltdb,creative-quant/voltdb,zuowang/voltdb,simonzhangsm/voltdb,kobronson/cs-voltdb,paulmartel/voltdb,creative-quant/voltdb,flybird119/voltdb
/* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB L.L.C. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.dtxn; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import org.voltdb.ClientResponseImpl; import org.voltdb.VoltDB; import org.voltdb.VoltTable; import org.voltdb.fault.FaultHandler; import org.voltdb.fault.NodeFailureFault; import org.voltdb.fault.VoltFault; import org.voltdb.fault.VoltFault.FaultType; import org.voltdb.messaging.HeartbeatResponseMessage; import org.voltdb.messaging.InitiateResponseMessage; import org.voltdb.messaging.VoltMessage; import org.voltdb.network.Connection; import org.voltdb.utils.EstTime; /** * DtxnInitiatorQueue matches incoming result set responses to outstanding * transactions, performing duplicate suppression and consistency checking * for single-partition transactions when replication is enabled. * * It currently shares/uses m_initiator's intrinsic lock to maintain * thread-safety across callers into SimpleDtxnInitiator and threads which * provide InitiateResponses via offer(). This is a bit ugly but is identical * with the synchronization mechanism that existed before the extraction of * this class, so it should JustWork(tm). */ public class DtxnInitiatorQueue implements Queue<VoltMessage> { private class InitiatorNodeFailureFaultHandler implements FaultHandler { @Override public void faultOccured(VoltFault fault) { if (fault instanceof NodeFailureFault) { NodeFailureFault node_fault = (NodeFailureFault) fault; ArrayList<Integer> dead_sites = VoltDB.instance().getCatalogContext().siteTracker. getAllSitesForHost(node_fault.getHostId()); for (Integer site_id : dead_sites) { removeSite(site_id); m_safetyState.removeState(site_id); } } } } /** Map of transaction ids to transaction information */ private final int m_siteId; private final PendingTxnList m_pendingTxns = new PendingTxnList(); private TransactionInitiator m_initiator; private final HashMap<Long, InitiateResponseMessage> m_txnIdResponses; // need a separate copy of the VoltTables so that we can have // thread-safe meta-data private final HashMap<Long, VoltTable[]> m_txnIdResults; private final ExecutorTxnIdSafetyState m_safetyState; /** * Storage for initiator statistics */ final InitiatorStats m_stats; /** * Construct a new DtxnInitiatorQueue * @param siteId The mailbox siteId for this initiator */ public DtxnInitiatorQueue(int siteId, ExecutorTxnIdSafetyState safetyState) { assert(safetyState != null); m_siteId = siteId; m_safetyState = safetyState; m_stats = new InitiatorStats("Initiator " + siteId + " stats", siteId); m_txnIdResults = new HashMap<Long, VoltTable[]>(); m_txnIdResponses = new HashMap<Long, InitiateResponseMessage>(); VoltDB.instance().getFaultDistributor(). // For Node failure, the initiators need to be ordered after the catalog // but before everything else (to prevent any new work for bad sites) registerFaultHandler(FaultType.NODE_FAILURE, new InitiatorNodeFailureFaultHandler(), NodeFailureFault.NODE_FAILURE_INITIATOR); } public void setInitiator(TransactionInitiator initiator) { m_initiator = initiator; } public void addPendingTxn(InFlightTxnState txn) { synchronized (m_initiator) { m_pendingTxns.addTxn(txn.txnId, txn.coordinatorId, txn); } } public void removeSite(int siteId) { synchronized (m_initiator) { Map<Long, InFlightTxnState> txn_ids_affected = m_pendingTxns.removeSite(siteId); for (Long txn_id : txn_ids_affected.keySet()) { if (m_pendingTxns.getTxnIdSize(txn_id) == 0) { InFlightTxnState state = txn_ids_affected.get(txn_id); if (!m_txnIdResponses.containsKey(txn_id)) { // No response was ever received for this TXN. // Currently, crashing is okay because there are // no valid node failures that can lead us to the // state where there are no more pending // InFlightTxnStates AND no responses for a TXN ID. // Multipartition initiators and coordinators are // currently co-located, so a node failure kills both // and this code doesn't run. Single partition // transactions with replications are guaranteed a // response or an outstanding InFlightTxnState. // Single partition transactions with no replication // means that a node failure kills the cluster. VoltDB.crashVoltDB(); } InitiateResponseMessage r = m_txnIdResponses.get(txn_id); m_pendingTxns.removeTxnId(r.getTxnId()); m_initiator.reduceBackpressure(state.messageSize); m_txnIdResponses.remove(r.getTxnId()); if (!state.isReadOnly) { enqueueResponse(r, state); } } } } } @Override public boolean add(VoltMessage arg0) { throw new UnsupportedOperationException(); } @Override public boolean contains(Object arg0) { throw new UnsupportedOperationException(); } @Override public boolean offer(VoltMessage message) { synchronized(m_initiator) { // update the state of seen txnids for each executor if (message instanceof HeartbeatResponseMessage) { HeartbeatResponseMessage hrm = (HeartbeatResponseMessage) message; m_safetyState.updateLastSeenTxnIdFromExecutorBySiteId(hrm.getExecSiteId(), hrm.getLastReceivedTxnId(), hrm.isBlocked()); return true; } // only valid messages are this and heartbeatresponse assert(message instanceof InitiateResponseMessage); final InitiateResponseMessage r = (InitiateResponseMessage) message; // update the state of seen txnids for each executor m_safetyState.updateLastSeenTxnIdFromExecutorBySiteId(r.getCoordinatorSiteId(), r.getLastReceivedTxnId(), false); InFlightTxnState state; int sites_left = -1; state = m_pendingTxns.getTxn(r.getTxnId(), r.getCoordinatorSiteId()); sites_left = m_pendingTxns.getTxnIdSize(r.getTxnId()); assert(state.coordinatorId == r.getCoordinatorSiteId()); assert(m_siteId == r.getInitiatorSiteId()); boolean first_response = false; VoltTable[] first_results = null; if (!m_txnIdResults.containsKey(r.getTxnId())) { ClientResponseImpl curr_response = r.getClientResponseData(); VoltTable[] curr_results = curr_response.getResults(); VoltTable[] saved_results = new VoltTable[curr_results.length]; // Create shallow copies of all the VoltTables to avoid // race conditions with the ByteBuffer metadata for (int i = 0; i < curr_results.length; ++i) { saved_results[i] = new VoltTable(curr_results[i].getTableDataReference(), true); } m_txnIdResults.put(r.getTxnId(), saved_results); m_txnIdResponses.put(r.getTxnId(), r); first_response = true; } else { first_results = m_txnIdResults.get(r.getTxnId()); } if (first_response) { // If this is a read-only transaction then we'll return // the first response to the client if (state.isReadOnly) { enqueueResponse(r, state); } } else { assert(first_results != null); ClientResponseImpl curr_response = r.getClientResponseData(); VoltTable[] curr_results = curr_response.getResults(); if (first_results.length != curr_results.length) { String msg = "Mismatched result count received for transaction ID: " + r.getTxnId(); msg += "\n while executing stored procedure: " + state.invocation.getProcName(); msg += "\n from execution site: " + r.getCoordinatorSiteId(); msg += "\n Expected number of results: " + first_results.length; msg += "\n Mismatched number of results: " + curr_results.length; throw new RuntimeException(msg); } for (int i = 0; i < first_results.length; ++i) { if (!curr_results[i].hasSameContents(first_results[i])) { String msg = "Mismatched results received for transaction ID: " + r.getTxnId(); msg += "\n while executing stored procedure: " + state.invocation.getProcName(); msg += "\n from execution site: " + r.getCoordinatorSiteId(); msg += "\n Expected results: " + first_results[i].toString(); msg += "\n Mismatched results: " + curr_results[i].toString(); throw new RuntimeException(msg); } } } if (sites_left == 0) { m_pendingTxns.removeTxnId(r.getTxnId()); m_initiator.reduceBackpressure(state.messageSize); m_txnIdResults.remove(r.getTxnId()); m_txnIdResponses.remove(r.getTxnId()); if (!state.isReadOnly) { enqueueResponse(r, state); } } return true; } } private void enqueueResponse(InitiateResponseMessage response, InFlightTxnState state) { response.setClientHandle(state.invocation.getClientHandle()); //Horrible but so much more efficient. final Connection c = (Connection)state.clientData; assert(c != null) : "NULL connection in connection state client data."; final long now = EstTime.currentTimeMillis(); final int delta = (int)(now - state.initiateTime); final ClientResponseImpl client_response = response.getClientResponseData(); client_response.setClusterRoundtrip(delta); m_stats.logTransactionCompleted( state.connectionId, state.connectionHostname, state.invocation, delta, client_response.getStatus()); c.writeStream().enqueue(client_response); } @Override public boolean remove(Object arg0) { throw new UnsupportedOperationException(); } @Override public VoltMessage element() { throw new UnsupportedOperationException(); } @Override public VoltMessage peek() { throw new UnsupportedOperationException(); } @Override public VoltMessage poll() { throw new UnsupportedOperationException(); } @Override public VoltMessage remove() { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends VoltMessage> arg0) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public Iterator<VoltMessage> iterator() { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public int size() { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] arg0) { throw new UnsupportedOperationException(); } /** * Currently used to provide object state for the dump manager * @return A list of outstanding transaction state objects */ public List<InFlightTxnState> getInFlightTxns() { return m_pendingTxns.getInFlightTxns(); } }
src/frontend/org/voltdb/dtxn/DtxnInitiatorQueue.java
/* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB L.L.C. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.dtxn; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Queue; import org.voltdb.ClientResponseImpl; import org.voltdb.VoltDB; import org.voltdb.VoltTable; import org.voltdb.fault.FaultHandler; import org.voltdb.fault.NodeFailureFault; import org.voltdb.fault.VoltFault; import org.voltdb.fault.VoltFault.FaultType; import org.voltdb.messaging.HeartbeatResponseMessage; import org.voltdb.messaging.InitiateResponseMessage; import org.voltdb.messaging.VoltMessage; import org.voltdb.network.Connection; import org.voltdb.utils.EstTime; /** * DtxnInitiatorQueue matches incoming result set responses to outstanding * transactions, performing duplicate suppression and consistency checking * for single-partition transactions when replication is enabled. * * It currently shares/uses m_initiator's intrinsic lock to maintain * thread-safety across callers into SimpleDtxnInitiator and threads which * provide InitiateResponses via offer(). This is a bit ugly but is identical * with the synchronization mechanism that existed before the extraction of * this class, so it should JustWork(tm). */ public class DtxnInitiatorQueue implements Queue<VoltMessage> { private class InitiatorNodeFailureFaultHandler implements FaultHandler { @Override public void faultOccured(VoltFault fault) { if (fault instanceof NodeFailureFault) { NodeFailureFault node_fault = (NodeFailureFault) fault; ArrayList<Integer> dead_sites = VoltDB.instance().getCatalogContext().siteTracker. getAllSitesForHost(node_fault.getHostId()); for (Integer site_id : dead_sites) { removeSite(site_id); m_safetyState.removeState(site_id); } } } } /** Map of transaction ids to transaction information */ private final int m_siteId; private final PendingTxnList m_pendingTxns = new PendingTxnList(); private TransactionInitiator m_initiator; private final HashMap<Long, InitiateResponseMessage> m_txnIdResponses; // need a separate copy of the VoltTables so that we can have // thread-safe meta-data private final HashMap<Long, VoltTable[]> m_txnIdResults; private final ExecutorTxnIdSafetyState m_safetyState; /** * Storage for initiator statistics */ final InitiatorStats m_stats; /** * Construct a new DtxnInitiatorQueue * @param siteId The mailbox siteId for this initiator */ public DtxnInitiatorQueue(int siteId, ExecutorTxnIdSafetyState safetyState) { assert(safetyState != null); m_siteId = siteId; m_safetyState = safetyState; m_stats = new InitiatorStats("Initiator " + siteId + " stats", siteId); m_txnIdResults = new HashMap<Long, VoltTable[]>(); m_txnIdResponses = new HashMap<Long, InitiateResponseMessage>(); VoltDB.instance().getFaultDistributor(). // For Node failure, the initiators need to be ordered after the catalog // but before everything else (to prevent any new work for bad sites) registerFaultHandler(FaultType.NODE_FAILURE, new InitiatorNodeFailureFaultHandler(), NodeFailureFault.NODE_FAILURE_INITIATOR); } public void setInitiator(TransactionInitiator initiator) { m_initiator = initiator; } public void addPendingTxn(InFlightTxnState txn) { synchronized (m_initiator) { m_pendingTxns.addTxn(txn.txnId, txn.coordinatorId, txn); } } public void removeSite(int siteId) { synchronized (m_initiator) { Map<Long, InFlightTxnState> txn_ids_affected = m_pendingTxns.removeSite(siteId); for (Long txn_id : txn_ids_affected.keySet()) { if (m_pendingTxns.getTxnIdSize(txn_id) == 0) { InFlightTxnState state = txn_ids_affected.get(txn_id); if (!m_txnIdResponses.containsKey(txn_id)) { // No response was ever received for this TXN. // What's the right thing to return to the client? // XXX-FAILURE don't like this crashing long-term VoltDB.crashVoltDB(); } InitiateResponseMessage r = m_txnIdResponses.get(txn_id); m_pendingTxns.removeTxnId(r.getTxnId()); m_initiator.reduceBackpressure(state.messageSize); m_txnIdResponses.remove(r.getTxnId()); if (!state.isReadOnly) { enqueueResponse(r, state); } } } } } @Override public boolean add(VoltMessage arg0) { throw new UnsupportedOperationException(); } @Override public boolean contains(Object arg0) { throw new UnsupportedOperationException(); } @Override public boolean offer(VoltMessage message) { synchronized(m_initiator) { // update the state of seen txnids for each executor if (message instanceof HeartbeatResponseMessage) { HeartbeatResponseMessage hrm = (HeartbeatResponseMessage) message; m_safetyState.updateLastSeenTxnIdFromExecutorBySiteId(hrm.getExecSiteId(), hrm.getLastReceivedTxnId(), hrm.isBlocked()); return true; } // only valid messages are this and heartbeatresponse assert(message instanceof InitiateResponseMessage); final InitiateResponseMessage r = (InitiateResponseMessage) message; // update the state of seen txnids for each executor m_safetyState.updateLastSeenTxnIdFromExecutorBySiteId(r.getCoordinatorSiteId(), r.getLastReceivedTxnId(), false); InFlightTxnState state; int sites_left = -1; state = m_pendingTxns.getTxn(r.getTxnId(), r.getCoordinatorSiteId()); sites_left = m_pendingTxns.getTxnIdSize(r.getTxnId()); assert(state.coordinatorId == r.getCoordinatorSiteId()); assert(m_siteId == r.getInitiatorSiteId()); boolean first_response = false; VoltTable[] first_results = null; if (!m_txnIdResults.containsKey(r.getTxnId())) { ClientResponseImpl curr_response = r.getClientResponseData(); VoltTable[] curr_results = curr_response.getResults(); VoltTable[] saved_results = new VoltTable[curr_results.length]; // Create shallow copies of all the VoltTables to avoid // race conditions with the ByteBuffer metadata for (int i = 0; i < curr_results.length; ++i) { saved_results[i] = new VoltTable(curr_results[i].getTableDataReference(), true); } m_txnIdResults.put(r.getTxnId(), saved_results); m_txnIdResponses.put(r.getTxnId(), r); first_response = true; } else { first_results = m_txnIdResults.get(r.getTxnId()); } if (first_response) { // If this is a read-only transaction then we'll return // the first response to the client if (state.isReadOnly) { enqueueResponse(r, state); } } else { assert(first_results != null); ClientResponseImpl curr_response = r.getClientResponseData(); VoltTable[] curr_results = curr_response.getResults(); if (first_results.length != curr_results.length) { String msg = "Mismatched result count received for transaction ID: " + r.getTxnId(); msg += "\n while executing stored procedure: " + state.invocation.getProcName(); msg += "\n from execution site: " + r.getCoordinatorSiteId(); msg += "\n Expected number of results: " + first_results.length; msg += "\n Mismatched number of results: " + curr_results.length; throw new RuntimeException(msg); } for (int i = 0; i < first_results.length; ++i) { if (!curr_results[i].hasSameContents(first_results[i])) { String msg = "Mismatched results received for transaction ID: " + r.getTxnId(); msg += "\n while executing stored procedure: " + state.invocation.getProcName(); msg += "\n from execution site: " + r.getCoordinatorSiteId(); msg += "\n Expected results: " + first_results[i].toString(); msg += "\n Mismatched results: " + curr_results[i].toString(); throw new RuntimeException(msg); } } } // XXX_K-SAFE if we never receive a response from a site, // this data structure is going to leak memory. Need to ponder // where to jam a timeout. Maybe just wait for failure detection // to tell us to clean up if (sites_left == 0) { m_pendingTxns.removeTxnId(r.getTxnId()); m_initiator.reduceBackpressure(state.messageSize); m_txnIdResults.remove(r.getTxnId()); m_txnIdResponses.remove(r.getTxnId()); if (!state.isReadOnly) { enqueueResponse(r, state); } } return true; } } private void enqueueResponse(InitiateResponseMessage response, InFlightTxnState state) { response.setClientHandle(state.invocation.getClientHandle()); //Horrible but so much more efficient. final Connection c = (Connection)state.clientData; assert(c != null) : "NULL connection in connection state client data."; final long now = EstTime.currentTimeMillis(); final int delta = (int)(now - state.initiateTime); final ClientResponseImpl client_response = response.getClientResponseData(); client_response.setClusterRoundtrip(delta); m_stats.logTransactionCompleted( state.connectionId, state.connectionHostname, state.invocation, delta, client_response.getStatus()); c.writeStream().enqueue(client_response); } @Override public boolean remove(Object arg0) { throw new UnsupportedOperationException(); } @Override public VoltMessage element() { throw new UnsupportedOperationException(); } @Override public VoltMessage peek() { throw new UnsupportedOperationException(); } @Override public VoltMessage poll() { throw new UnsupportedOperationException(); } @Override public VoltMessage remove() { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends VoltMessage> arg0) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean containsAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public Iterator<VoltMessage> iterator() { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> arg0) { throw new UnsupportedOperationException(); } @Override public int size() { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { throw new UnsupportedOperationException(); } @Override public <T> T[] toArray(T[] arg0) { throw new UnsupportedOperationException(); } /** * Currently used to provide object state for the dump manager * @return A list of outstanding transaction state objects */ public List<InFlightTxnState> getInFlightTxns() { return m_pendingTxns.getInFlightTxns(); } }
Clean up DtxnInitiatorQueue comments: - Remove a stale XXX comment - Add some additional RecordForFuture to a place with crashVoltDB()
src/frontend/org/voltdb/dtxn/DtxnInitiatorQueue.java
Clean up DtxnInitiatorQueue comments: - Remove a stale XXX comment - Add some additional RecordForFuture to a place with crashVoltDB()
<ide><path>rc/frontend/org/voltdb/dtxn/DtxnInitiatorQueue.java <ide> if (!m_txnIdResponses.containsKey(txn_id)) <ide> { <ide> // No response was ever received for this TXN. <del> // What's the right thing to return to the client? <del> // XXX-FAILURE don't like this crashing long-term <add> // Currently, crashing is okay because there are <add> // no valid node failures that can lead us to the <add> // state where there are no more pending <add> // InFlightTxnStates AND no responses for a TXN ID. <add> // Multipartition initiators and coordinators are <add> // currently co-located, so a node failure kills both <add> // and this code doesn't run. Single partition <add> // transactions with replications are guaranteed a <add> // response or an outstanding InFlightTxnState. <add> // Single partition transactions with no replication <add> // means that a node failure kills the cluster. <ide> VoltDB.crashVoltDB(); <ide> } <ide> InitiateResponseMessage r = m_txnIdResponses.get(txn_id); <ide> } <ide> } <ide> <del> // XXX_K-SAFE if we never receive a response from a site, <del> // this data structure is going to leak memory. Need to ponder <del> // where to jam a timeout. Maybe just wait for failure detection <del> // to tell us to clean up <ide> if (sites_left == 0) <ide> { <ide> m_pendingTxns.removeTxnId(r.getTxnId());
Java
apache-2.0
8a0b81020b24dffebc1e3a7980f3e7a8b58d24c9
0
ditadewindita/CodeUSummer2017,ditadewindita/CodeUSummer2017
package codeu.chat.common; import codeu.chat.server.Server; import codeu.chat.util.Logger; import codeu.chat.util.Time; import codeu.chat.util.Uuid; import java.io.IOException; /** * Created by dita on 5/20/17. */ public final class ServerInfo { private final static String SERVER_VERSION = "1.0.0"; private static final Logger.Log LOG = Logger.newLog(ServerInfo.class); public Time startTime; // Removed 'final' because of try/catch error public Uuid version; public ServerInfo() { this.startTime = Time.now(); try { this.version = Uuid.parse(SERVER_VERSION); } catch(Exception ex) { this.version = Uuid.NULL; LOG.error(ex, "Server version cannot be parsed. Default Uuid version used."); } } public ServerInfo(Time startTime) { this.startTime = startTime; } public ServerInfo(Uuid version) { this.version = version; } }
src/codeu/chat/common/ServerInfo.java
package codeu.chat.common; import codeu.chat.server.Server; import codeu.chat.util.Logger; import codeu.chat.util.Uuid; import java.io.IOException; /** * Created by dita on 5/20/17. */ public final class ServerInfo { private final static String SERVER_VERSION = "1.0.0"; private static final Logger.Log LOG = Logger.newLog(ServerInfo.class); public final Time startTime; // Removed 'final' because of try/catch error public Uuid version; public ServerInfo() { this.startTime = Time.now(); try { this.version = Uuid.parse(SERVER_VERSION); } catch(Exception ex) { this.version = Uuid.NULL; LOG.error(ex, "Server version cannot be parsed. Default Uuid version used."); } } public ServerInfo(Time startTime) { this.startTime = startTime; } public ServerInfo(Uuid version) { this.version = version; } }
Time import - quick fix
src/codeu/chat/common/ServerInfo.java
Time import - quick fix
<ide><path>rc/codeu/chat/common/ServerInfo.java <ide> <ide> import codeu.chat.server.Server; <ide> import codeu.chat.util.Logger; <add>import codeu.chat.util.Time; <ide> import codeu.chat.util.Uuid; <ide> import java.io.IOException; <ide> <ide> <ide> private static final Logger.Log LOG = Logger.newLog(ServerInfo.class); <ide> <del> public final Time startTime; <add> public Time startTime; <add> <ide> // Removed 'final' because of try/catch error <ide> public Uuid version; <ide> <ide> public ServerInfo() { <ide> this.startTime = Time.now(); <add> <ide> try { <ide> this.version = Uuid.parse(SERVER_VERSION); <ide> } catch(Exception ex) {
JavaScript
mit
2a9a5e50f566acab0efefd6a42f9618f1b191130
0
JS-UI-And-DOM-Team-Pisco-Sour/Team-Pisco-Sour,JS-UI-And-DOM-Team-Pisco-Sour/Team-Pisco-Sour
window.onload = function () { var CONSTANTS = { STAGE_WIDTH: 800, STAGE_HEIGHT: 600 }; var stage, layer, backgroundImageObj, playerImageObj; function loadCanvas() { var container = document.getElementById('gameplay-container'); container.position = stage = new Kinetic.Stage({ container: 'gameplay-container', width: CONSTANTS.STAGE_WIDTH, height: CONSTANTS.STAGE_HEIGHT }); layer = new Kinetic.Layer(); } function loadPlayer() { } function loadBackground() { backgroundImageObj = new Image(); backgroundImageObj.src = "sources/images/canvas-bg.jpg"; backgroundImageObj.onload = function () { var background = new Kinetic.Image({ x: 0, y: 0, image: backgroundImageObj, width: CONSTANTS.STAGE_WIDTH, height: CONSTANTS.STAGE_HEIGHT }); layer.add(background); stage.add(layer); }; } function initialize() { loadCanvas(); loadBackground(); loadPlayer(); } function run() { } (function () { initialize(); run(); }()); };
GameplayScreen/Sources/js/gameplay-controls.js
window.onload = function () { var CONSTANTS = { STAGE_WIDTH: 800, STAGE_HEIGHT: 600 }; var stage, layer, backgroundImageObj, player = new Image(); function loadCanvas() { stage = new Kinetic.Stage({ container: 'gameplay-container', width: CONSTANTS.STAGE_WIDTH, height: CONSTANTS.STAGE_HEIGHT }); layer = new Kinetic.Layer(); } function loadPlayer() { } function loadBackground() { backgroundImageObj = new Image(); backgroundImageObj.width = 800; backgroundImageObj.src = "sources/images/canvas-bg.jpg"; backgroundImageObj.onload = function () { var background = new Kinetic.Image({ x: 0, y: 0, image: backgroundImageObj, width: CONSTANTS.STAGE_WIDTH, height: CONSTANTS.STAGE_HEIGHT }); layer.add(background); stage.add(layer); }; } function initialize() { loadCanvas(); loadBackground(); loadPlayer(); } function run() { } (function () { initialize(); run(); }()); };
Minor changes made
GameplayScreen/Sources/js/gameplay-controls.js
Minor changes made
<ide><path>ameplayScreen/Sources/js/gameplay-controls.js <ide> STAGE_HEIGHT: 600 <ide> }; <ide> <del> var stage, layer, backgroundImageObj, <del> player = new Image(); <add> var stage, layer, backgroundImageObj, playerImageObj; <ide> <ide> function loadCanvas() { <add> var container = document.getElementById('gameplay-container'); <add> container.position = <ide> stage = new Kinetic.Stage({ <ide> container: 'gameplay-container', <ide> width: CONSTANTS.STAGE_WIDTH, <ide> <ide> function loadBackground() { <ide> backgroundImageObj = new Image(); <del> backgroundImageObj.width = 800; <ide> backgroundImageObj.src = "sources/images/canvas-bg.jpg"; <ide> <ide> backgroundImageObj.onload = function () {
Java
mit
9d8873a1b1e963269d5a89bd895129769dc6e542
0
Hydral1k/HTMLEditor,Hydral1k/HTMLEditor
/* * The Command to create a new file. */ package htmleditor.commands; import htmleditor.CloseListener; import htmleditor.HTMLEditor; import htmleditor.MyEventHandler; import htmleditor.TabData; import javafx.event.Event; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TextArea; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * * @author aac6012 */ public class NewFileCommand implements Command { HTMLEditor editor ; public NewFileCommand(HTMLEditor editor){ this.editor = editor; } public void execute(Event t){ Tab tab = new Tab(); tab.setOnClosed(new CloseListener(this.editor)); tab.setText("Untitled"); tab.setId("Untitled"); tab.setUserData(new TabData(this.editor)); BorderPane tabBorderContent = new BorderPane(); // line numbers /* TextArea lineNumbers = new TextArea("1"); lineNumbers.setDisable(true); lineNumbers.setWrapText(true); lineNumbers.setPrefWidth(20); tabBorderContent.setLeft(lineNumbers); */ GridPane lineNumbers = new GridPane(); Label lineno = new Label(" 1 "); GridPane.setConstraints(lineno, 3, 1); // column=3 row=1 lineNumbers.getChildren().addAll(lineno); tabBorderContent.setLeft(lineNumbers); // text area TextArea ta = new TextArea(); ta.setOnKeyReleased(new MyEventHandler(new TextAnalysisCommand(this.editor))); ta.setWrapText(true); ta.prefHeightProperty().bind(this.editor.getScene().heightProperty()); ta.prefWidthProperty().bind(this.editor.getScene().widthProperty()); ta.setStyle("-fx-font: \"Segoe UI Semibold\"; "); tabBorderContent.setRight(ta); tab.setContent(tabBorderContent); this.editor.getTabPane().getTabs().add(tab); this.editor.getTabPane().getSelectionModel().select(tab); /* if (tab.isSelected()){ tab.getContent().requestFocus(); } */ //This saves the initial state to the newly created tab's undoManager. ((TabData)tab.getUserData()).getUndoManager().save(this.editor.createMemento()); } }
HTMLEditor/src/htmleditor/commands/NewFileCommand.java
/* * The Command to create a new file. */ package htmleditor.commands; import htmleditor.CloseListener; import htmleditor.HTMLEditor; import htmleditor.MyEventHandler; import htmleditor.TabData; import javafx.event.Event; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TextArea; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * * @author aac6012 */ public class NewFileCommand implements Command { HTMLEditor editor ; public NewFileCommand(HTMLEditor editor){ this.editor = editor; } public void execute(Event t){ Tab tab = new Tab(); tab.setOnClosed(new CloseListener(this.editor)); tab.setText("Untitled"); tab.setId("Untitled"); tab.setUserData(new TabData(this.editor)); BorderPane tabBorderContent = new BorderPane(); // line numbers /* TextArea lineNumbers = new TextArea("1"); lineNumbers.setDisable(true); lineNumbers.setWrapText(true); lineNumbers.setPrefWidth(20); tabBorderContent.setLeft(lineNumbers); */ GridPane lineNumbers = new GridPane(); Label lineno = new Label(" 1 "); GridPane.setConstraints(lineno, 3, 1); // column=3 row=1 lineNumbers.getChildren().addAll(lineno); tabBorderContent.setLeft(lineNumbers); // text area TextArea ta = new TextArea(); ta.setOnKeyReleased(new MyEventHandler(new TextAnalysisCommand(this.editor))); ta.setWrapText(true); ta.prefHeightProperty().bind(this.editor.getScene().heightProperty()); ta.prefWidthProperty().bind(this.editor.getScene().widthProperty()); ta.setStyle("-fx-font: \"Segoe UI Semibold\"; "); tabBorderContent.setRight(ta); tab.setContent(tabBorderContent); this.editor.getTabPane().getTabs().add(tab); this.editor.getTabPane().getSelectionModel().select(tab); /* if (tab.isSelected()){ tab.getContent().requestFocus(); } */ } }
Minor change to fix undo/redo.
HTMLEditor/src/htmleditor/commands/NewFileCommand.java
Minor change to fix undo/redo.
<ide><path>TMLEditor/src/htmleditor/commands/NewFileCommand.java <ide> tab.getContent().requestFocus(); <ide> } <ide> */ <add> <add> //This saves the initial state to the newly created tab's undoManager. <add> ((TabData)tab.getUserData()).getUndoManager().save(this.editor.createMemento()); <add> <ide> } <ide> }
Java
apache-2.0
fdeffbaf2dd78812aa0fd5bcf501e19e1f654fc5
0
Popalay/Cardme,Popalay/Cardme,Popalay/Cardme
package com.popalay.cardme; public final class Constants { private Constants() { } public static final String PRIVACY_POLICY_LINK = "https://rawgit.com/Popalay/Cardme/master/privacy_policy.html"; }
app/src/main/java/com/popalay/cardme/Constants.java
package com.popalay.cardme; public final class Constants { private Constants() { } public static final String PRIVACY_POLICY_LINK = "https://cdn.rawgit.com/Popalay/Cardme/48fdd882/privacy_policy.html"; }
Update privacy policy link
app/src/main/java/com/popalay/cardme/Constants.java
Update privacy policy link
<ide><path>pp/src/main/java/com/popalay/cardme/Constants.java <ide> } <ide> <ide> public static final String PRIVACY_POLICY_LINK <del> = "https://cdn.rawgit.com/Popalay/Cardme/48fdd882/privacy_policy.html"; <add> = "https://rawgit.com/Popalay/Cardme/master/privacy_policy.html"; <ide> }
Java
mit
37743d9bead781711c11354611dfe48ab860b7db
0
dcoraboeuf/ontrack,dcoraboeuf/ontrack,dcoraboeuf/ontrack,dcoraboeuf/ontrack,joansmith/ontrack,joansmith/ontrack,joansmith/ontrack,joansmith/ontrack,joansmith/ontrack
package net.ontrack.web.ui; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import net.ontrack.core.model.*; import net.ontrack.core.security.SecurityUtils; import net.ontrack.core.ui.ManageUI; import net.ontrack.core.ui.PropertyUI; import net.ontrack.service.ManagementService; import net.ontrack.service.ProfileService; import net.ontrack.web.support.EntityConverter; import net.ontrack.web.support.ErrorHandler; import net.ontrack.web.ui.model.ValidationRunStatusUpdateData; import net.sf.jstring.Strings; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.util.CookieGenerator; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; @Controller public class ManageUIController extends AbstractEntityUIController implements ManageUI { private final SecurityUtils securityUtils; private final ManagementService managementService; private final ProfileService profileService; private final PropertyUI propertyUI; private final ObjectMapper objectMapper; private final String version; @Autowired public ManageUIController(ErrorHandler errorHandler, Strings strings, ManagementService managementService, EntityConverter entityConverter, SecurityUtils securityUtils, ProfileService profileService, PropertyUI propertyUI, ObjectMapper objectMapper, @Value("${app.version}") String version) { super(errorHandler, strings, entityConverter); this.managementService = managementService; this.securityUtils = securityUtils; this.profileService = profileService; this.propertyUI = propertyUI; this.objectMapper = objectMapper; this.version = version; } // Projects @Override @RequestMapping(value = "/ui/manage/version", method = RequestMethod.GET) public @ResponseBody String getVersion() { return version; } @Override @RequestMapping(value = "/ui/manage/project", method = RequestMethod.GET) public @ResponseBody List<ProjectSummary> getProjectList() { return managementService.getProjectList(); } @Override @RequestMapping(value = "/ui/manage/project", method = RequestMethod.POST) public @ResponseBody ProjectSummary createProject(@RequestBody ProjectCreationForm form) { return managementService.createProject(form); } @Override @RequestMapping(value = "/ui/manage/project/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody ProjectSummary getProject(@PathVariable String name) { return managementService.getProject(entityConverter.getProjectId(name)); } @Override @RequestMapping(value = "/ui/manage/project/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteProject(@PathVariable String name) { return managementService.deleteProject(entityConverter.getProjectId(name)); } @Override @RequestMapping(value = "/ui/manage/project/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody ProjectSummary updateProject(@PathVariable String name, @RequestBody ProjectUpdateForm form) { return managementService.updateProject( entityConverter.getProjectId(name), form ); } // Branches @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch", method = RequestMethod.GET) public @ResponseBody List<BranchSummary> getBranchList(@PathVariable String project) { int projectId = entityConverter.getProjectId(project); return managementService.getBranchList(projectId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BranchSummary getBranch(@PathVariable String project, @PathVariable String name) { int branchId = entityConverter.getBranchId(project, name); return managementService.getBranch(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}/clone", method = RequestMethod.GET) public @ResponseBody BranchCloneInfo getBranchCloneInfo(Locale locale, @PathVariable String project, @PathVariable String name) { // Admin only securityUtils.checkIsAdmin(); // Branch int branchId = entityConverter.getBranchId(project, name); // Gets all the properties for the validation stamps Map<String, DisplayableProperty> validationStampIndex = new TreeMap<>(); List<ValidationStampSummary> validationStampList = managementService.getValidationStampList(branchId); for (ValidationStampSummary validationStampSummary : validationStampList) { // Gets the list of properties for this validation stamp List<DisplayablePropertyValue> validationStampProperties = propertyUI.getProperties(locale, Entity.VALIDATION_STAMP, validationStampSummary.getId()); for (DisplayablePropertyValue validationStampProperty : validationStampProperties) { String key = String.format("%s-%s", validationStampProperty.getExtension(), validationStampProperty.getName()); validationStampIndex.put( key, toDisplayableProperty(validationStampProperty) ); } } // Gets all the properties for the promotionlevels Map<String, DisplayableProperty> promotionLevelIndex = new TreeMap<>(); List<PromotionLevelSummary> promotionLevelList = managementService.getPromotionLevelList(branchId); for (PromotionLevelSummary promotionLevelSummary : promotionLevelList) { // Gets the list of properties for this promotion level List<DisplayablePropertyValue> promotionLevelProperties = propertyUI.getProperties(locale, Entity.PROMOTION_LEVEL, promotionLevelSummary.getId()); for (DisplayablePropertyValue promotionLevelProperty : promotionLevelProperties) { String key = String.format("%s-%s", promotionLevelProperty.getExtension(), promotionLevelProperty.getName()); promotionLevelIndex.put( key, toDisplayableProperty(promotionLevelProperty) ); } } // OK return new BranchCloneInfo( managementService.getBranch(branchId), Collections2.filter( propertyUI.getEditableProperties(locale, Entity.BRANCH, branchId), new Predicate<EditableProperty>() { @Override public boolean apply(EditableProperty property) { return StringUtils.isNotBlank(property.getValue()); } } ), validationStampIndex.values(), promotionLevelIndex.values() ); } private DisplayableProperty toDisplayableProperty(DisplayablePropertyValue promotionLevelProperty) { return new DisplayableProperty( promotionLevelProperty.getExtension(), promotionLevelProperty.getName(), promotionLevelProperty.getDisplayName(), promotionLevelProperty.getIconPath() ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}/decorated", method = RequestMethod.GET) public @ResponseBody DecoratedBranch getDecoratedBranch(Locale locale, String project, String name) { return managementService.getDecoratedBranch(locale, entityConverter.getBranchId(project, name)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/filter", method = RequestMethod.GET) public @ResponseBody BranchFilterData getBranchFilterData(Locale locale, @PathVariable String project, @PathVariable String branch) { return new BranchFilterData( getPromotionLevelList(project, branch), getValidationStampList(project, branch), Arrays.asList(Status.values()), propertyUI.getPropertyList(locale, Entity.BUILD) ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/cleanup", method = RequestMethod.GET) public @ResponseBody BuildCleanup getBuildCleanup(@PathVariable String project, @PathVariable String branch) { return managementService.getBuildCleanup(entityConverter.getBranchId(project, branch)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/cleanup", method = RequestMethod.PUT) public @ResponseBody Ack setBuildCleanup(@PathVariable String project, @PathVariable String branch, @RequestBody BuildCleanupForm form) { return managementService.setBuildCleanup(entityConverter.getBranchId(project, branch), form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch", method = RequestMethod.POST) public @ResponseBody BranchSummary createBranch(@PathVariable String project, @RequestBody BranchCreationForm form) { int projectId = entityConverter.getProjectId(project); return managementService.createBranch(projectId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody BranchSummary updateBranch(@PathVariable String project, @PathVariable String name, @RequestBody BranchUpdateForm form) { return managementService.updateBranch( entityConverter.getBranchId(project, name), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}/clone", method = RequestMethod.POST) public @ResponseBody BranchSummary cloneBranch(@PathVariable String project, @PathVariable String name, @RequestBody BranchCloneForm form) { return managementService.cloneBranch( entityConverter.getBranchId(project, name), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteBranch(@PathVariable String project, @PathVariable String name) { int branchId = entityConverter.getBranchId(project, name); return managementService.deleteBranch(branchId); } // Validation stamps @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp", method = RequestMethod.GET) public @ResponseBody List<ValidationStampSummary> getValidationStampList(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getValidationStampList(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody ValidationStampSummary getValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.getValidationStamp(validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/decorated", method = RequestMethod.GET) public @ResponseBody DecoratedValidationStamp getDecoratedValidationStamp(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.getDecoratedValidationStamp(locale, validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp", method = RequestMethod.POST) public @ResponseBody ValidationStampSummary createValidationStamp(@PathVariable String project, @PathVariable String branch, @RequestBody ValidationStampCreationForm form) { int branchId = entityConverter.getBranchId(project, branch); return managementService.createValidationStamp(branchId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody ValidationStampSummary updateValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestBody ValidationStampUpdateForm form) { return managementService.updateValidationStamp( entityConverter.getValidationStampId(project, branch, validationStamp), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.deleteValidationStamp(validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/comment", method = RequestMethod.POST) public @ResponseBody Ack addValidationStampComment(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestBody ValidationStampCommentForm form) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.addValidationStampComment(validationStampId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/comment", method = RequestMethod.GET) public @ResponseBody Collection<Comment> getValidationStampComments(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getValidationStampComments(locale, entityConverter.getValidationStampId(project, branch, validationStamp), offset, count); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.POST) public @ResponseBody Ack setImageValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name, @RequestParam MultipartFile image) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.imageValidationStamp(validationStampId, image); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.GET) public @ResponseBody byte[] imageValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.imageValidationStamp(validationStampId); } // Promotion levels @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level", method = RequestMethod.GET) public @ResponseBody List<PromotionLevelSummary> getPromotionLevelList(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getPromotionLevelList(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody PromotionLevelSummary getPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.getPromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level", method = RequestMethod.POST) public @ResponseBody PromotionLevelSummary createPromotionLevel(@PathVariable String project, @PathVariable String branch, @RequestBody PromotionLevelCreationForm form) { int branchId = entityConverter.getBranchId(project, branch); return managementService.createPromotionLevel(branchId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody PromotionLevelSummary updatePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel, @RequestBody PromotionLevelUpdateForm form) { return managementService.updatePromotionLevel( entityConverter.getPromotionLevelId(project, branch, promotionLevel), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/autopromote/set", method = RequestMethod.PUT) public @ResponseBody Flag setPromotionLevelAutoPromote(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.setPromotionLevelAutoPromote( entityConverter.getPromotionLevelId(project, branch, promotionLevel) ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/autopromote/unset", method = RequestMethod.PUT) public @ResponseBody Flag unsetPromotionLevelAutoPromote(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.unsetPromotionLevelAutoPromote( entityConverter.getPromotionLevelId(project, branch, promotionLevel) ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deletePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.deletePromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.POST) public @ResponseBody Ack setImagePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name, @RequestParam MultipartFile image) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.imagePromotionLevel(promotionLevelId, image); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.GET) public @ResponseBody byte[] imagePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.imagePromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/link/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody Ack linkValidationStampToPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @PathVariable String promotionLevel) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, promotionLevel); return managementService.linkValidationStampToPromotionLevel(validationStampId, promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/unlink", method = RequestMethod.GET) public @ResponseBody Ack unlinkValidationStampToPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.unlinkValidationStampToPromotionLevel(validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/up", method = RequestMethod.PUT) public @ResponseBody Ack upValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { return managementService.upValidationStamp(entityConverter.getValidationStampId(project, branch, validationStamp)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/down", method = RequestMethod.PUT) public @ResponseBody Ack downValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { return managementService.downValidationStamp(entityConverter.getValidationStampId(project, branch, validationStamp)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/owner/{ownerId:\\d+}", method = RequestMethod.PUT) public @ResponseBody Ack setValidationStampOwner(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @PathVariable int ownerId) { return managementService.setValidationStampOwner(entityConverter.getValidationStampId(project, branch, validationStamp), ownerId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/owner", method = RequestMethod.DELETE) public @ResponseBody Ack unsetValidationStampOwner(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { return managementService.unsetValidationStampOwner(entityConverter.getValidationStampId(project, branch, validationStamp)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/up", method = RequestMethod.GET) public @ResponseBody Ack upPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.upPromotionLevel(entityConverter.getPromotionLevelId(project, branch, promotionLevel)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/down", method = RequestMethod.GET) public @ResponseBody Ack downPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.downPromotionLevel(entityConverter.getPromotionLevelId(project, branch, promotionLevel)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level_manage", method = RequestMethod.GET) public @ResponseBody PromotionLevelManagementData getPromotionLevelManagementData(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getPromotionLevelManagementData(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/validation_stamps", method = RequestMethod.GET) public @ResponseBody PromotionLevelAndStamps getPromotionLevelValidationStamps(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.getPromotionLevelValidationStamps( entityConverter.getPromotionLevelId(project, branch, promotionLevel) ); } @Override public BranchBuilds getBuilds(Locale locale, String project, String branch, BuildFilter filter) { int branchId = entityConverter.getBranchId(project, branch); return managementService.queryBuilds(locale, branchId, filter); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteBuild(@PathVariable String project, @PathVariable String branch, @PathVariable String build) { return managementService.deleteBuild(entityConverter.getBuildId(project, branch, build)); } @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build", method = RequestMethod.POST) public @ResponseBody BranchBuilds getBuilds(HttpServletResponse response, Locale locale, @PathVariable String project, @PathVariable String branch, @RequestBody BuildFilter filter) throws IOException { // Performs the query BranchBuilds builds = getBuilds(locale, project, branch, filter); // Filters on validation stamps? int currentAccountId = securityUtils.getCurrentAccountId(); if (currentAccountId > 0) { // Gets the branch ID int branchId = entityConverter.getBranchId(project, branch); // Gets the list of filtered validation IDs Set<Integer> filteredStampIds = profileService.getFilteredValidationStampIds(branchId); // Operating the filter builds = builds.filterStamps(filteredStampIds); // Gets the list of saved filters builds = builds.withSavedBuildFilters(profileService.getFilters(branchId)); } // Setting the cookie for the filter CookieGenerator cookie = new CookieGenerator(); cookie.setCookieMaxAge(365 * 24 * 60 * 60); // 1 year cookie.setCookieName(String.format("%s|%s|filter", project, branch)); cookie.addCookie(response, objectMapper.writeValueAsString(filter)); // OK return builds; } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/last", method = RequestMethod.GET) public @ResponseBody BuildSummary getLastBuild(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getLastBuild(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/withValidationStamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BuildSummary getLastBuildWithValidationStamp(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.findLastBuildWithValidationStamp(validationStampId, Collections.singleton(Status.PASSED)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/withPromotionLevel/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BuildSummary getLastBuildWithPromotionLevel(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, promotionLevel); return managementService.findLastBuildWithPromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BuildSummary getBuild(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int buildId = entityConverter.getBuildId(project, branch, name); return managementService.getBuild(buildId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody BuildSummary updateBuild(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @RequestBody BranchUpdateForm form) { return managementService.updateBuild( entityConverter.getBuildId(project, branch, build), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{name:[A-Za-z0-9_\\.\\-]+}/validationStamps", method = RequestMethod.GET) public @ResponseBody List<BuildValidationStamp> getBuildValidationStamps(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String name) { int buildId = entityConverter.getBuildId(project, branch, name); return managementService.getBuildValidationStamps(locale, buildId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{name:[A-Za-z0-9_\\.\\-]+}/promotionLevels", method = RequestMethod.GET) public @ResponseBody List<BuildPromotionLevel> getBuildPromotionLevels(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String name) { int buildId = entityConverter.getBuildId(project, branch, name); return managementService.getBuildPromotionLevels(locale, buildId); } // Validation runs @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/validation_run/{run:[0-9]+}", method = RequestMethod.GET) public @ResponseBody ValidationRunSummary getValidationRun(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @PathVariable String validationStamp, @PathVariable int run) { int runId = entityConverter.getValidationRunId(project, branch, build, validationStamp, run); return managementService.getValidationRun(runId); } @Override @RequestMapping(value = "/ui/manage/validation_run/{validationRunId:[0-9]+}/history", method = RequestMethod.GET) public @ResponseBody List<ValidationRunEvent> getValidationRunHistory( Locale locale, @PathVariable int validationRunId, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getValidationRunHistory(locale, validationRunId, offset, count); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/validation_run", method = RequestMethod.GET) public @ResponseBody List<ValidationRunEvent> getValidationRunsForValidationStamp(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getValidationRunsForValidationStamp(locale, entityConverter.getValidationStampId(project, branch, validationStamp), offset, count); } @Override @RequestMapping(value = "/ui/manage/validation_run/{runId:[0-9]+}/comment", method = RequestMethod.POST) public @ResponseBody Ack addValidationRunComment(@PathVariable int runId, @RequestBody ValidationRunCommentCreationForm form) { return managementService.addValidationRunComment(runId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/validation_run/{runOrder:[0-9]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteValidationRun(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @PathVariable String validationStamp, @PathVariable int runOrder) { return managementService.deleteValidationRun(entityConverter.getValidationRunId( project, branch, build, validationStamp, runOrder )); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/promotions", method = RequestMethod.GET) public @ResponseBody List<Promotion> getPromotions(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getPromotions( locale, entityConverter.getPromotionLevelId(project, branch, promotionLevel), offset, count ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack removePromotedRun(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @PathVariable String promotionLevel) { int buildId = entityConverter.getBuildId(project, branch, build); int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, promotionLevel); return managementService.removePromotedRun(buildId, promotionLevelId); } @RequestMapping(value = "/ui/manage/validation_run/{validationRunId:[0-9]+}/statusUpdateData", method = RequestMethod.GET) public @ResponseBody ValidationRunStatusUpdateData getValidationRunStatusUpdateData(Locale locale, @PathVariable int validationRunId) { // Gets the validation run ValidationRunSummary validationRun = managementService.getValidationRun(validationRunId); Status currentStatus = validationRun.getValidationRunStatus().getStatus(); // Gets the properties for this run List<EditableProperty> editableProperties = propertyUI.getEditableProperties(locale, Entity.VALIDATION_RUN, validationRunId); // OK return new ValidationRunStatusUpdateData( Lists.newArrayList(currentStatus.getNext()), editableProperties ); } }
ontrack-web/src/main/java/net/ontrack/web/ui/ManageUIController.java
package net.ontrack.web.ui; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import net.ontrack.core.model.*; import net.ontrack.core.security.SecurityUtils; import net.ontrack.core.ui.ManageUI; import net.ontrack.core.ui.PropertyUI; import net.ontrack.service.ManagementService; import net.ontrack.service.ProfileService; import net.ontrack.web.support.EntityConverter; import net.ontrack.web.support.ErrorHandler; import net.ontrack.web.ui.model.ValidationRunStatusUpdateData; import net.sf.jstring.Strings; import org.apache.commons.lang3.StringUtils; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.util.CookieGenerator; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; @Controller public class ManageUIController extends AbstractEntityUIController implements ManageUI { private final SecurityUtils securityUtils; private final ManagementService managementService; private final ProfileService profileService; private final PropertyUI propertyUI; private final ObjectMapper objectMapper; private final String version; @Autowired public ManageUIController(ErrorHandler errorHandler, Strings strings, ManagementService managementService, EntityConverter entityConverter, SecurityUtils securityUtils, ProfileService profileService, PropertyUI propertyUI, ObjectMapper objectMapper, @Value("${app.version}") String version) { super(errorHandler, strings, entityConverter); this.managementService = managementService; this.securityUtils = securityUtils; this.profileService = profileService; this.propertyUI = propertyUI; this.objectMapper = objectMapper; this.version = version; } // Projects @Override @RequestMapping(value = "/ui/manage/version", method = RequestMethod.GET) public @ResponseBody String getVersion() { return version; } @Override @RequestMapping(value = "/ui/manage/project", method = RequestMethod.GET) public @ResponseBody List<ProjectSummary> getProjectList() { return managementService.getProjectList(); } @Override @RequestMapping(value = "/ui/manage/project", method = RequestMethod.POST) public @ResponseBody ProjectSummary createProject(@RequestBody ProjectCreationForm form) { return managementService.createProject(form); } @Override @RequestMapping(value = "/ui/manage/project/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody ProjectSummary getProject(@PathVariable String name) { return managementService.getProject(entityConverter.getProjectId(name)); } @Override @RequestMapping(value = "/ui/manage/project/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteProject(@PathVariable String name) { return managementService.deleteProject(entityConverter.getProjectId(name)); } @Override @RequestMapping(value = "/ui/manage/project/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody ProjectSummary updateProject(@PathVariable String name, @RequestBody ProjectUpdateForm form) { return managementService.updateProject( entityConverter.getProjectId(name), form ); } // Branches @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch", method = RequestMethod.GET) public @ResponseBody List<BranchSummary> getBranchList(@PathVariable String project) { int projectId = entityConverter.getProjectId(project); return managementService.getBranchList(projectId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BranchSummary getBranch(@PathVariable String project, @PathVariable String name) { int branchId = entityConverter.getBranchId(project, name); return managementService.getBranch(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}/clone", method = RequestMethod.GET) public @ResponseBody BranchCloneInfo getBranchCloneInfo(Locale locale, @PathVariable String project, @PathVariable String name) { // Admin only securityUtils.checkIsAdmin(); // Branch int branchId = entityConverter.getBranchId(project, name); // Gets all the properties for the validation stamps Map<String, DisplayableProperty> validationStampIndex = new TreeMap<>(); List<ValidationStampSummary> validationStampList = managementService.getValidationStampList(branchId); for (ValidationStampSummary validationStampSummary : validationStampList) { // Gets the list of properties for this validation stamp List<DisplayablePropertyValue> validationStampProperties = propertyUI.getProperties(locale, Entity.VALIDATION_STAMP, validationStampSummary.getId()); for (DisplayablePropertyValue validationStampProperty : validationStampProperties) { String key = String.format("%s-%s", validationStampProperty.getExtension(), validationStampProperty.getName()); validationStampIndex.put( key, toDisplayableProperty(validationStampProperty) ); } } // Gets all the properties for the promotionlevels Map<String, DisplayableProperty> promotionLevelIndex = new TreeMap<>(); List<PromotionLevelSummary> promotionLevelList = managementService.getPromotionLevelList(branchId); for (PromotionLevelSummary promotionLevelSummary : promotionLevelList) { // Gets the list of properties for this promotion level List<DisplayablePropertyValue> promotionLevelProperties = propertyUI.getProperties(locale, Entity.PROMOTION_LEVEL, promotionLevelSummary.getId()); for (DisplayablePropertyValue promotionLevelProperty : promotionLevelProperties) { String key = String.format("%s-%s", promotionLevelProperty.getExtension(), promotionLevelProperty.getName()); promotionLevelIndex.put( key, toDisplayableProperty(promotionLevelProperty) ); } } // OK return new BranchCloneInfo( managementService.getBranch(branchId), Collections2.filter( propertyUI.getEditableProperties(locale, Entity.BRANCH, branchId), new Predicate<EditableProperty>() { @Override public boolean apply(EditableProperty property) { return StringUtils.isNotBlank(property.getValue()); } } ), validationStampIndex.values(), promotionLevelIndex.values() ); } private DisplayableProperty toDisplayableProperty(DisplayablePropertyValue promotionLevelProperty) { return new DisplayableProperty( promotionLevelProperty.getExtension(), promotionLevelProperty.getName(), promotionLevelProperty.getDisplayName(), promotionLevelProperty.getIconPath() ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}/decorated", method = RequestMethod.GET) public @ResponseBody DecoratedBranch getDecoratedBranch(Locale locale, String project, String name) { return managementService.getDecoratedBranch(locale, entityConverter.getBranchId(project, name)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/filter", method = RequestMethod.GET) public @ResponseBody BranchFilterData getBranchFilterData(Locale locale, @PathVariable String project, @PathVariable String branch) { return new BranchFilterData( getPromotionLevelList(project, branch), getValidationStampList(project, branch), Arrays.asList(Status.values()), propertyUI.getPropertyList(locale, Entity.BUILD) ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/cleanup", method = RequestMethod.GET) public @ResponseBody BuildCleanup getBuildCleanup(@PathVariable String project, @PathVariable String branch) { return managementService.getBuildCleanup(entityConverter.getBranchId(project, branch)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/cleanup", method = RequestMethod.PUT) public @ResponseBody Ack setBuildCleanup(@PathVariable String project, @PathVariable String branch, @RequestBody BuildCleanupForm form) { return managementService.setBuildCleanup(entityConverter.getBranchId(project, branch), form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch", method = RequestMethod.POST) public @ResponseBody BranchSummary createBranch(@PathVariable String project, @RequestBody BranchCreationForm form) { int projectId = entityConverter.getProjectId(project); return managementService.createBranch(projectId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody BranchSummary updateBranch(@PathVariable String project, @PathVariable String name, @RequestBody BranchUpdateForm form) { return managementService.updateBranch( entityConverter.getBranchId(project, name), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}/clone", method = RequestMethod.POST) public @ResponseBody BranchSummary cloneBranch(@PathVariable String project, @PathVariable String name, @RequestBody BranchCloneForm form) { return managementService.cloneBranch( entityConverter.getBranchId(project, name), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteBranch(@PathVariable String project, @PathVariable String name) { int branchId = entityConverter.getBranchId(project, name); return managementService.deleteBranch(branchId); } // Validation stamps @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp", method = RequestMethod.GET) public @ResponseBody List<ValidationStampSummary> getValidationStampList(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getValidationStampList(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody ValidationStampSummary getValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.getValidationStamp(validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}/decorated", method = RequestMethod.GET) public @ResponseBody DecoratedValidationStamp getDecoratedValidationStamp(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.getDecoratedValidationStamp(locale, validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp", method = RequestMethod.POST) public @ResponseBody ValidationStampSummary createValidationStamp(@PathVariable String project, @PathVariable String branch, @RequestBody ValidationStampCreationForm form) { int branchId = entityConverter.getBranchId(project, branch); return managementService.createValidationStamp(branchId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody ValidationStampSummary updateValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestBody ValidationStampUpdateForm form) { return managementService.updateValidationStamp( entityConverter.getValidationStampId(project, branch, validationStamp), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.deleteValidationStamp(validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/comment", method = RequestMethod.POST) public @ResponseBody Ack addValidationStampComment(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestBody ValidationStampCommentForm form) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.addValidationStampComment(validationStampId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/comment", method = RequestMethod.GET) public @ResponseBody Collection<Comment> getValidationStampComments(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getValidationStampComments(locale, entityConverter.getValidationStampId(project, branch, validationStamp), offset, count); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.POST) public @ResponseBody Ack setImageValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name, @RequestParam MultipartFile image) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.imageValidationStamp(validationStampId, image); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.GET) public @ResponseBody byte[] imageValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int validationStampId = entityConverter.getValidationStampId(project, branch, name); return managementService.imageValidationStamp(validationStampId); } // Promotion levels @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level", method = RequestMethod.GET) public @ResponseBody List<PromotionLevelSummary> getPromotionLevelList(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getPromotionLevelList(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody PromotionLevelSummary getPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.getPromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level", method = RequestMethod.POST) public @ResponseBody PromotionLevelSummary createPromotionLevel(@PathVariable String project, @PathVariable String branch, @RequestBody PromotionLevelCreationForm form) { int branchId = entityConverter.getBranchId(project, branch); return managementService.createPromotionLevel(branchId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody PromotionLevelSummary updatePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel, @RequestBody PromotionLevelUpdateForm form) { return managementService.updatePromotionLevel( entityConverter.getPromotionLevelId(project, branch, promotionLevel), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/autopromote/set", method = RequestMethod.PUT) public @ResponseBody Flag setPromotionLevelAutoPromote(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.setPromotionLevelAutoPromote( entityConverter.getPromotionLevelId(project, branch, promotionLevel) ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/autopromote/unset", method = RequestMethod.PUT) public @ResponseBody Flag unsetPromotionLevelAutoPromote(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.unsetPromotionLevelAutoPromote( entityConverter.getPromotionLevelId(project, branch, promotionLevel) ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deletePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.deletePromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.POST) public @ResponseBody Ack setImagePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name, @RequestParam MultipartFile image) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.imagePromotionLevel(promotionLevelId, image); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{name:[A-Za-z0-9_\\.\\-]+}/image", method = RequestMethod.GET) public @ResponseBody byte[] imagePromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, name); return managementService.imagePromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/link/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody Ack linkValidationStampToPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @PathVariable String promotionLevel) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, promotionLevel); return managementService.linkValidationStampToPromotionLevel(validationStampId, promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/unlink", method = RequestMethod.GET) public @ResponseBody Ack unlinkValidationStampToPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.unlinkValidationStampToPromotionLevel(validationStampId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/up", method = RequestMethod.PUT) public @ResponseBody Ack upValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { return managementService.upValidationStamp(entityConverter.getValidationStampId(project, branch, validationStamp)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/down", method = RequestMethod.PUT) public @ResponseBody Ack downValidationStamp(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { return managementService.downValidationStamp(entityConverter.getValidationStampId(project, branch, validationStamp)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/owner/{ownerId:\\d+}", method = RequestMethod.PUT) public @ResponseBody Ack setValidationStampOwner(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @PathVariable int ownerId) { return managementService.setValidationStampOwner(entityConverter.getValidationStampId(project, branch, validationStamp), ownerId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/owner", method = RequestMethod.DELETE) public @ResponseBody Ack unsetValidationStampOwner(@PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { return managementService.unsetValidationStampOwner(entityConverter.getValidationStampId(project, branch, validationStamp)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/up", method = RequestMethod.GET) public @ResponseBody Ack upPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.upPromotionLevel(entityConverter.getPromotionLevelId(project, branch, promotionLevel)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/down", method = RequestMethod.GET) public @ResponseBody Ack downPromotionLevel(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.downPromotionLevel(entityConverter.getPromotionLevelId(project, branch, promotionLevel)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level_manage", method = RequestMethod.GET) public @ResponseBody PromotionLevelManagementData getPromotionLevelManagementData(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getPromotionLevelManagementData(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/validation_stamps", method = RequestMethod.GET) public @ResponseBody PromotionLevelAndStamps getPromotionLevelValidationStamps(@PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { return managementService.getPromotionLevelValidationStamps( entityConverter.getPromotionLevelId(project, branch, promotionLevel) ); } @Override public BranchBuilds getBuilds(Locale locale, String project, String branch, BuildFilter filter) { int branchId = entityConverter.getBranchId(project, branch); return managementService.queryBuilds(locale, branchId, filter); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteBuild(@PathVariable String project, @PathVariable String branch, @PathVariable String build) { return managementService.deleteBuild(entityConverter.getBuildId(project, branch, build)); } @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build", method = RequestMethod.POST) public @ResponseBody BranchBuilds getBuilds(HttpServletResponse response, Locale locale, @PathVariable String project, @PathVariable String branch, @RequestBody BuildFilter filter) throws IOException { // Performs the query BranchBuilds builds = getBuilds(locale, project, branch, filter); // Filters on validation stamps? int currentAccountId = securityUtils.getCurrentAccountId(); if (currentAccountId > 0) { // Gets the branch ID int branchId = entityConverter.getBranchId(project, branch); // Gets the list of filtered validation IDs Set<Integer> filteredStampIds = profileService.getFilteredValidationStampIds(branchId); // Operating the filter builds = builds.filterStamps(filteredStampIds); // Gets the list of saved filters builds = builds.withSavedBuildFilters(profileService.getFilters(branchId)); } // Setting the cookie for the filter CookieGenerator cookie = new CookieGenerator(); cookie.setCookieMaxAge(365 * 24 * 60 * 60); // 1 year cookie.setCookieName(String.format("%s|%s|filter", project, branch)); cookie.addCookie(response, objectMapper.writeValueAsString(filter)); // OK return builds; } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/last", method = RequestMethod.GET) public @ResponseBody BuildSummary getLastBuild(@PathVariable String project, @PathVariable String branch) { int branchId = entityConverter.getBranchId(project, branch); return managementService.getLastBuild(branchId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/withValidationStamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BuildSummary getLastBuildWithValidationStamp(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) { int validationStampId = entityConverter.getValidationStampId(project, branch, validationStamp); return managementService.findLastBuildWithValidationStamp(validationStampId, Collections.singleton(Status.PASSED)); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/withPromotionLevel/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BuildSummary getLastBuildWithPromotionLevel(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel) { int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, promotionLevel); return managementService.findLastBuildWithPromotionLevel(promotionLevelId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{name:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.GET) public @ResponseBody BuildSummary getBuild(@PathVariable String project, @PathVariable String branch, @PathVariable String name) { int buildId = entityConverter.getBuildId(project, branch, name); return managementService.getBuild(buildId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.PUT) public @ResponseBody BuildSummary updateBuild(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @RequestBody BranchUpdateForm form) { return managementService.updateBuild( entityConverter.getBuildId(project, branch, build), form ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{name:[A-Za-z0-9_\\.\\-]+}/validationStamps", method = RequestMethod.GET) public @ResponseBody List<BuildValidationStamp> getBuildValidationStamps(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String name) { int buildId = entityConverter.getBuildId(project, branch, name); return managementService.getBuildValidationStamps(locale, buildId); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{name:[A-Za-z0-9_\\.\\-]+}/promotionLevels", method = RequestMethod.GET) public @ResponseBody List<BuildPromotionLevel> getBuildPromotionLevels(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String name) { int buildId = entityConverter.getBuildId(project, branch, name); return managementService.getBuildPromotionLevels(locale, buildId); } // Validation runs @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/validation_run/{run:[0-9]+}", method = RequestMethod.GET) public @ResponseBody ValidationRunSummary getValidationRun(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @PathVariable String validationStamp, @PathVariable int run) { int runId = entityConverter.getValidationRunId(project, branch, build, validationStamp, run); return managementService.getValidationRun(runId); } @Override @RequestMapping(value = "/ui/manage/validation_run/{validationRunId:[0-9]+}/history", method = RequestMethod.GET) public @ResponseBody List<ValidationRunEvent> getValidationRunHistory( Locale locale, @PathVariable int validationRunId, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getValidationRunHistory(locale, validationRunId, offset, count); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/validation_run", method = RequestMethod.GET) public @ResponseBody List<ValidationRunEvent> getValidationRunsForValidationStamp(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getValidationRunsForValidationStamp(locale, entityConverter.getValidationStampId(project, branch, validationStamp), offset, count); } @Override @RequestMapping(value = "/ui/manage/validation_run/{runId:[0-9]+}/comment", method = RequestMethod.POST) public @ResponseBody Ack addValidationRunComment(@PathVariable int runId, @RequestBody ValidationRunCommentCreationForm form) { return managementService.addValidationRunComment(runId, form); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/validation_run/{runOrder:[0-9]+}", method = RequestMethod.DELETE) public @ResponseBody Ack deleteValidationRun(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @PathVariable String validationStamp, @PathVariable int runOrder) { return managementService.deleteValidationRun(entityConverter.getValidationRunId( project, branch, build, validationStamp, runOrder )); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}/promotions", method = RequestMethod.GET) public @ResponseBody List<Promotion> getPromotions(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String promotionLevel, @RequestParam(required = false, defaultValue = "0") int offset, @RequestParam(required = false, defaultValue = "10") int count) { return managementService.getPromotions( locale, entityConverter.getPromotionLevelId(project, branch, promotionLevel), offset, count ); } @Override @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/build/{build:[A-Za-z0-9_\\.\\-]+}/promotion_level/{promotionLevel:[A-Za-z0-9_\\.\\-]+}", method = RequestMethod.DELETE) public @ResponseBody Ack removePromotedRun(@PathVariable String project, @PathVariable String branch, @PathVariable String build, @PathVariable String promotionLevel) { int buildId = entityConverter.getBuildId(project, branch, build); int promotionLevelId = entityConverter.getPromotionLevelId(project, branch, promotionLevel); return managementService.removePromotedRun(buildId, promotionLevelId); } @RequestMapping(value = "/ui/manage/validation_run/{validationRunId:[0-9]+}/statusUpdateData", method = RequestMethod.GET) public @ResponseBody ValidationRunStatusUpdateData getValidationRunStatusUpdateData(Locale locale, @PathVariable int validationRunId) { // Gets the validation run ValidationRunSummary validationRun = managementService.getValidationRun(validationRunId); Status currentStatus = validationRun.getValidationRunStatus().getStatus(); // Gets the properties for this run List<EditableProperty> editableProperties = propertyUI.getEditableProperties(locale, Entity.VALIDATION_RUN, validationRunId); // OK return new ValidationRunStatusUpdateData( Lists.newArrayList(currentStatus.getNext()), editableProperties ); } }
#224 Correction of the UI for the decoration of one validation stamp
ontrack-web/src/main/java/net/ontrack/web/ui/ManageUIController.java
#224 Correction of the UI for the decoration of one validation stamp
<ide><path>ntrack-web/src/main/java/net/ontrack/web/ui/ManageUIController.java <ide> } <ide> <ide> @Override <del> @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{name:[A-Za-z0-9_\\.\\-]+}/decorated", method = RequestMethod.GET) <add> @RequestMapping(value = "/ui/manage/project/{project:[A-Za-z0-9_\\.\\-]+}/branch/{branch:[A-Za-z0-9_\\.\\-]+}/validation_stamp/{validationStamp:[A-Za-z0-9_\\.\\-]+}/decorated", method = RequestMethod.GET) <ide> public <ide> @ResponseBody <ide> DecoratedValidationStamp getDecoratedValidationStamp(Locale locale, @PathVariable String project, @PathVariable String branch, @PathVariable String validationStamp) {
JavaScript
mit
9a1d6fbef659622d36c3b4237fc21faabe958c01
0
nqdy666/grunt-autoprefixer,yuhualingfeng/grunt-autoprefixer,nDmitry/grunt-autoprefixer
'use strict'; var path = require('path'); var autoprefixer = require('autoprefixer'); var diff = require('diff'); module.exports = function(grunt) { grunt.registerMultiTask( 'autoprefixer', 'Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website.', function() { var options = this.options({ diff: false, map: false }); /** * @type {Autoprefixer} */ var processor = autoprefixer(options.browsers); // Iterate over all specified file groups. this.files.forEach(function(f) { /** * @type {string[]} */ var sources = f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }); /** * Ensure that `file` property in a given map exists * and it's a filename of a generated content (not a path) * @param {string} map * @param {string} filePath * @returns {string} */ function ensureFile(map, filePath) { map = JSON.parse(map); map.file = path.basename(filePath); return JSON.stringify(map); } /** * Set the correct path to a source file * @param {string[]} sources * @param {string} to * @returns {string[]} */ function fixSources(sources, to) { for (var i = 0, ii = sources.length; i < ii; i++) { sources[i] = path.relative(path.dirname(to), sources[i]); if (path.sep === '\\') { sources[i] = sources[i].replace(/\\/g, '/'); } } return sources; } /** * Returns an input source map or `true` if it doesn't exist * @param {string} mapPath A path to an input source map file * @param {string} from * @returns {string|true} */ function getMapParam(mapPath, from) { if (grunt.file.exists(mapPath)) { return ensureFile(grunt.file.read(mapPath), from); } else { return true; } } /** * Create a patch file and write it to the destination folder * @param {string} to * @param {string} input Input CSS * @param {string} output Prefixed CSS */ function writeDiff(to, input, output) { var diffPath = (typeof options.diff === 'string') ? options.diff : to + '.patch'; grunt.file.write(diffPath, diff.createPatch(to, input, output)); } /** * PostCSS doesn't handle the annotation yet * @param {string} css * @param {string} to * @returns {string} */ function updateAnnotation(css, to) { var pattern = /(\/\*(?:#|@)\ssourceMappingURL=\s*)(?:.*)(\s*\*\/)/; var mapName = path.basename(to) + '.map'; if (pattern.test(css)) { css = css.replace(pattern, '$1' + mapName + ' $2'); } else { css = css.concat( grunt.util.linefeed, '/*# sourceMappingURL=' + mapName + ' */' ); } return css; } /** * @param {string} input Input CSS * @param {string} from Input path * @param {string} to Output path */ function compile(input, from, to) { var result; if (options.map) { var mapPath; if (options.map === true) { mapPath = from + '.map'; } else { mapPath = options.map + path.basename(from) + '.map'; } // source-map lib works incorrectly if an input file is in subdirectory // so we must cwd to subdirectry and make all paths relative to it // https://github.com/ai/postcss/issues/13 process.chdir(path.dirname(from)); mapPath = path.relative(path.dirname(from), mapPath); to = path.relative(path.dirname(from), to); from = path.basename(from); result = processor.process(input, { map: getMapParam(mapPath, from), from: from, to: to }); var map = JSON.parse(ensureFile(result.map, to)); fixSources(map.sources, to); result.css = updateAnnotation(result.css, to); grunt.file.write(to + '.map', JSON.stringify(map)); } else { result = processor.process(input); } grunt.file.write(to, result.css); options.diff && writeDiff(to, input, result.css); } sources.forEach(function(filepath) { var dest = f.dest || filepath; var cwd = process.cwd(); compile(grunt.file.read(filepath), filepath, dest); // Restore the default cwd process.chdir(cwd); grunt.log.writeln('File "' + dest + '" prefixed.'); }); }); } ); };
tasks/autoprefixer.js
'use strict'; var path = require('path'); var autoprefixer = require('autoprefixer'); var diff = require('diff'); module.exports = function(grunt) { grunt.registerMultiTask( 'autoprefixer', 'Parse CSS and add vendor prefixes to CSS rules using values from the Can I Use website.', function() { var options = this.options({ diff: false, map: false }); /** * @type {Autoprefixer} */ var processor = autoprefixer(options.browsers); // Iterate over all specified file groups. this.files.forEach(function(f) { /** * @type {string[]} */ var sources = f.src.filter(function(filepath) { // Warn on and remove invalid source files (if nonull was set). if (!grunt.file.exists(filepath)) { grunt.log.warn('Source file "' + filepath + '" not found.'); return false; } else { return true; } }); /** * Ensure that `file` property in a given map exists * and it's a filename of a generated content (not a path) * @param {string} map * @param {string} filePath * @returns {string} */ function ensureFile(map, filePath) { map = JSON.parse(map); map.file = path.basename(filePath); return JSON.stringify(map); } /** * Set the correct path to a source file * @param {string[]} sources * @param {string} to * @returns {string[]} */ function fixSources(sources, to) { for (var i = 0, ii = sources.length; i < ii; i++) { sources[i] = path.relative(path.dirname(to), sources[i]); } return sources; } /** * Returns an input source map or `true` if it doesn't exist * @param {string} mapPath A path to an input source map file * @param {string} from * @returns {string|true} */ function getMapParam(mapPath, from) { if (grunt.file.exists(mapPath)) { return ensureFile(grunt.file.read(mapPath), from); } else { return true; } } /** * Create a patch file and write it to the destination folder * @param {string} to * @param {string} input Input CSS * @param {string} output Prefixed CSS */ function writeDiff(to, input, output) { var diffPath = (typeof options.diff === 'string') ? options.diff : to + '.patch'; grunt.file.write(diffPath, diff.createPatch(to, input, output)); } /** * PostCSS doesn't handle the annotation yet * @param {string} css * @param {string} to * @returns {string} */ function updateAnnotation(css, to) { var pattern = /(\/\*(?:#|@)\ssourceMappingURL=\s*)(?:.*)(\s*\*\/)/; var mapName = path.basename(to) + '.map'; if (pattern.test(css)) { css = css.replace(pattern, '$1' + mapName + ' $2'); } else { css = css.concat( grunt.util.linefeed, '/*# sourceMappingURL=' + mapName + ' */' ); } return css; } /** * @param {string} input Input CSS * @param {string} from Input path * @param {string} to Output path */ function compile(input, from, to) { var result; if (options.map) { var mapPath; if (options.map === true) { mapPath = from + '.map'; } else { mapPath = options.map + path.basename(from) + '.map'; } // source-map lib works incorrectly if an input file is in subdirectory // so we must cwd to subdirectry and make all paths relative to it // https://github.com/ai/postcss/issues/13 process.chdir(path.dirname(from)); mapPath = path.relative(path.dirname(from), mapPath); to = path.relative(path.dirname(from), to); from = path.basename(from); result = processor.process(input, { map: getMapParam(mapPath, from), from: from, to: to }); var map = JSON.parse(ensureFile(result.map, to)); fixSources(map.sources, to); result.css = updateAnnotation(result.css, to); grunt.file.write(to + '.map', JSON.stringify(map)); } else { result = processor.process(input); } grunt.file.write(to, result.css); options.diff && writeDiff(to, input, result.css); } sources.forEach(function(filepath) { var dest = f.dest || filepath; var cwd = process.cwd(); compile(grunt.file.read(filepath), filepath, dest); // Restore the default cwd process.chdir(cwd); grunt.log.writeln('File "' + dest + '" prefixed.'); }); }); } ); };
Use slashes for the `sources` map property on Windows. Fixes #25
tasks/autoprefixer.js
Use slashes for the `sources` map property on Windows. Fixes #25
<ide><path>asks/autoprefixer.js <ide> function fixSources(sources, to) { <ide> for (var i = 0, ii = sources.length; i < ii; i++) { <ide> sources[i] = path.relative(path.dirname(to), sources[i]); <add> <add> if (path.sep === '\\') { <add> sources[i] = sources[i].replace(/\\/g, '/'); <add> } <ide> } <ide> <ide> return sources;
Java
mit
bae6fde67614c3f55c0b6084da1cf200f88c4a9a
0
Permafrost/Tundra.java,Permafrost/Tundra.java
/* * The MIT License (MIT) * * Copyright (c) 2015 Lachlan Dowding * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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 permafrost.tundra.server; import com.wm.app.b2b.server.InvokeState; import com.wm.app.b2b.server.ServerThread; import permafrost.tundra.id.UUIDHelper; import permafrost.tundra.lang.ThreadHelper; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; /** * A thread factory that creates webMethods Integration Server ServerThread threads. */ public class ServerThreadFactory implements ThreadFactory { /** * The prefix and suffix used on all created thread names. */ protected String threadNamePrefix, threadNameSuffix; /** * The count of threads created by this factory, used to suffix thread names. */ protected AtomicLong count = new AtomicLong(1); /** * The priority threads will be created with. */ protected int threadPriority; /** * The invoke state threads will be created with. */ protected InvokeState invokeState; /** * Whether created threads should be daemon threads. */ protected boolean daemon; /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The prefix used on all created thread names. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, InvokeState invokeState) { this(threadNamePrefix, null, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The prefix used on all created thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, String threadNameSuffix, InvokeState invokeState) { this(threadNamePrefix, threadNameSuffix, Thread.NORM_PRIORITY, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The prefix used on all created thread names. * @param threadPriority The priority used for each thread created. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, int threadPriority, InvokeState invokeState) { this(threadNamePrefix, null, threadPriority, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The threadNamePrefix of the factory, used to prefix thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param threadPriority The priority used for each thread created. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, String threadNameSuffix, int threadPriority, InvokeState invokeState) { this(threadNamePrefix, threadNameSuffix, threadPriority, false, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The threadNamePrefix of the factory, used to prefix thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param threadPriority The priority used for each thread created. * @param daemon Whether the created threads should be daemon threads. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, String threadNameSuffix, int threadPriority, boolean daemon, InvokeState invokeState) { if (threadNamePrefix == null) throw new NullPointerException("threadNamePrefix must not be null"); if (invokeState == null) throw new NullPointerException("invokeState must not be null"); this.threadNamePrefix = threadNamePrefix; this.threadNameSuffix = threadNameSuffix; this.invokeState = invokeState; this.threadPriority = ThreadHelper.normalizePriority(threadPriority); this.daemon = daemon; } /** * Returns a newly constructed Thread that will execute the given Runnable. * * @param runnable The Runnable to be executed by the thread. * @return The newly constructed thread. */ @Override public Thread newThread(Runnable runnable) { ServerThread thread = new ServerThread(runnable); String threadContext = UUIDHelper.generate(); long threadCount = count.getAndIncrement(); if (threadNameSuffix != null) { thread.setName(String.format("%s #%03d ThreadContext=%s %s", threadNamePrefix, threadCount, threadContext, threadNameSuffix)); } else { thread.setName(String.format("%s #%03d ThreadContext=%s", threadNamePrefix, threadCount, threadContext)); } InvokeState state = InvokeStateHelper.clone(invokeState); state.setSession(SessionHelper.create(thread.getName(), invokeState.getUser())); state.setCheckAccess(false); thread.setInvokeState(state); thread.setUncaughtExceptionHandler(UncaughtExceptionLogger.getInstance()); thread.setPriority(threadPriority); thread.setDaemon(daemon); return thread; } }
src/main/java/permafrost/tundra/server/ServerThreadFactory.java
/* * The MIT License (MIT) * * Copyright (c) 2015 Lachlan Dowding * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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 permafrost.tundra.server; import com.wm.app.b2b.server.InvokeState; import com.wm.app.b2b.server.ServerThread; import permafrost.tundra.id.UUIDHelper; import permafrost.tundra.lang.ThreadHelper; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; /** * A thread factory that creates webMethods Integration Server ServerThread threads. */ public class ServerThreadFactory implements ThreadFactory { /** * The prefix and suffix used on all created thread names. */ protected String threadNamePrefix, threadNameSuffix; /** * The count of threads created by this factory, used to suffix thread names. */ protected AtomicLong count = new AtomicLong(1); /** * The priority threads will be created with. */ protected int threadPriority; /** * The invoke state threads will be created with. */ protected InvokeState invokeState; /** * Whether created threads should be daemon threads. */ protected boolean daemon; /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The prefix used on all created thread names. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, InvokeState invokeState) { this(threadNamePrefix, null, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The prefix used on all created thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, String threadNameSuffix, InvokeState invokeState) { this(threadNamePrefix, threadNameSuffix, Thread.NORM_PRIORITY, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The prefix used on all created thread names. * @param threadPriority The priority used for each thread created. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, int threadPriority, InvokeState invokeState) { this(threadNamePrefix, null, threadPriority, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The threadNamePrefix of the factory, used to prefix thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param threadPriority The priority used for each thread created. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, String threadNameSuffix, int threadPriority, InvokeState invokeState) { this(threadNamePrefix, threadNameSuffix, threadPriority, false, invokeState); } /** * Constructs a new ServerThreadFactory. * * @param threadNamePrefix The threadNamePrefix of the factory, used to prefix thread names. * @param threadNameSuffix The suffix used on all created thread names. * @param threadPriority The priority used for each thread created. * @param daemon Whether the created threads should be daemon threads. * @param invokeState The invoke state to clone for each thread created. */ public ServerThreadFactory(String threadNamePrefix, String threadNameSuffix, int threadPriority, boolean daemon, InvokeState invokeState) { if (threadNamePrefix == null) throw new NullPointerException("threadNamePrefix must not be null"); if (invokeState == null) throw new NullPointerException("invokeState must not be null"); this.threadNamePrefix = threadNamePrefix; this.threadNameSuffix = threadNameSuffix; this.invokeState = invokeState; this.threadPriority = ThreadHelper.normalizePriority(threadPriority); this.daemon = daemon; } /** * Returns a newly constructed Thread that will execute the given Runnable. * * @param runnable The Runnable to be executed by the thread. * @return The newly constructed thread. */ @Override public Thread newThread(Runnable runnable) { ServerThread thread = new ServerThread(runnable); String threadContext = UUIDHelper.generate(); long threadCount = count.getAndIncrement(); if (threadNameSuffix != null) { thread.setName(String.format("%s #%03d ThreadContext=%s %s", threadNamePrefix, threadCount, threadContext, threadNameSuffix)); } else { thread.setName(String.format("%s #%03d ThreadContext=%s", threadNamePrefix, threadCount, threadContext)); } thread.setInvokeState(InvokeStateHelper.clone(invokeState)); thread.setUncaughtExceptionHandler(UncaughtExceptionLogger.getInstance()); thread.setPriority(threadPriority); thread.setDaemon(daemon); return thread; } }
Change ServerThreadFactory to create a new session for each new thread
src/main/java/permafrost/tundra/server/ServerThreadFactory.java
Change ServerThreadFactory to create a new session for each new thread
<ide><path>rc/main/java/permafrost/tundra/server/ServerThreadFactory.java <ide> thread.setName(String.format("%s #%03d ThreadContext=%s", threadNamePrefix, threadCount, threadContext)); <ide> } <ide> <del> thread.setInvokeState(InvokeStateHelper.clone(invokeState)); <add> InvokeState state = InvokeStateHelper.clone(invokeState); <add> state.setSession(SessionHelper.create(thread.getName(), invokeState.getUser())); <add> state.setCheckAccess(false); <add> <add> thread.setInvokeState(state); <ide> thread.setUncaughtExceptionHandler(UncaughtExceptionLogger.getInstance()); <ide> thread.setPriority(threadPriority); <ide> thread.setDaemon(daemon);
JavaScript
apache-2.0
9e43da5a01c1e541aa0fbf092ddbd3ce9e55bb2b
0
aaxelb/osf.io,felliott/osf.io,abought/osf.io,brianjgeiger/osf.io,amyshi188/osf.io,HalcyonChimera/osf.io,Nesiehr/osf.io,cwisecarver/osf.io,kch8qx/osf.io,crcresearch/osf.io,binoculars/osf.io,monikagrabowska/osf.io,baylee-d/osf.io,rdhyee/osf.io,acshi/osf.io,cslzchen/osf.io,aaxelb/osf.io,mluo613/osf.io,emetsger/osf.io,RomanZWang/osf.io,samchrisinger/osf.io,aaxelb/osf.io,abought/osf.io,icereval/osf.io,alexschiller/osf.io,alexschiller/osf.io,zachjanicki/osf.io,icereval/osf.io,laurenrevere/osf.io,erinspace/osf.io,Nesiehr/osf.io,SSJohns/osf.io,rdhyee/osf.io,mfraezz/osf.io,emetsger/osf.io,TomBaxter/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,SSJohns/osf.io,zachjanicki/osf.io,mfraezz/osf.io,DanielSBrown/osf.io,Nesiehr/osf.io,kch8qx/osf.io,baylee-d/osf.io,caneruguz/osf.io,chennan47/osf.io,chennan47/osf.io,erinspace/osf.io,jnayak1/osf.io,jnayak1/osf.io,Johnetordoff/osf.io,zamattiac/osf.io,HalcyonChimera/osf.io,chrisseto/osf.io,DanielSBrown/osf.io,mluke93/osf.io,TomHeatwole/osf.io,leb2dg/osf.io,TomBaxter/osf.io,cwisecarver/osf.io,caneruguz/osf.io,zamattiac/osf.io,hmoco/osf.io,caseyrollins/osf.io,samchrisinger/osf.io,monikagrabowska/osf.io,jnayak1/osf.io,emetsger/osf.io,HalcyonChimera/osf.io,adlius/osf.io,kch8qx/osf.io,aaxelb/osf.io,acshi/osf.io,erinspace/osf.io,amyshi188/osf.io,laurenrevere/osf.io,emetsger/osf.io,mluo613/osf.io,DanielSBrown/osf.io,abought/osf.io,wearpants/osf.io,mluke93/osf.io,binoculars/osf.io,mluke93/osf.io,felliott/osf.io,icereval/osf.io,laurenrevere/osf.io,chrisseto/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,jnayak1/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,RomanZWang/osf.io,saradbowman/osf.io,CenterForOpenScience/osf.io,RomanZWang/osf.io,RomanZWang/osf.io,rdhyee/osf.io,binoculars/osf.io,cwisecarver/osf.io,monikagrabowska/osf.io,mattclark/osf.io,cslzchen/osf.io,CenterForOpenScience/osf.io,Johnetordoff/osf.io,doublebits/osf.io,mluke93/osf.io,sloria/osf.io,caseyrollins/osf.io,asanfilippo7/osf.io,saradbowman/osf.io,wearpants/osf.io,hmoco/osf.io,mluo613/osf.io,rdhyee/osf.io,sloria/osf.io,samchrisinger/osf.io,caneruguz/osf.io,doublebits/osf.io,sloria/osf.io,kwierman/osf.io,DanielSBrown/osf.io,SSJohns/osf.io,chennan47/osf.io,kch8qx/osf.io,pattisdr/osf.io,crcresearch/osf.io,mluo613/osf.io,samchrisinger/osf.io,brianjgeiger/osf.io,hmoco/osf.io,amyshi188/osf.io,doublebits/osf.io,wearpants/osf.io,leb2dg/osf.io,asanfilippo7/osf.io,TomHeatwole/osf.io,doublebits/osf.io,alexschiller/osf.io,zachjanicki/osf.io,adlius/osf.io,brianjgeiger/osf.io,zamattiac/osf.io,chrisseto/osf.io,zamattiac/osf.io,wearpants/osf.io,TomHeatwole/osf.io,alexschiller/osf.io,caseyrollins/osf.io,cslzchen/osf.io,mluo613/osf.io,amyshi188/osf.io,crcresearch/osf.io,doublebits/osf.io,mattclark/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,TomHeatwole/osf.io,adlius/osf.io,TomBaxter/osf.io,mfraezz/osf.io,acshi/osf.io,cwisecarver/osf.io,hmoco/osf.io,RomanZWang/osf.io,chrisseto/osf.io,pattisdr/osf.io,alexschiller/osf.io,asanfilippo7/osf.io,Nesiehr/osf.io,CenterForOpenScience/osf.io,SSJohns/osf.io,kwierman/osf.io,mattclark/osf.io,acshi/osf.io,asanfilippo7/osf.io,kwierman/osf.io,felliott/osf.io,adlius/osf.io,felliott/osf.io,monikagrabowska/osf.io,kch8qx/osf.io,abought/osf.io,baylee-d/osf.io,acshi/osf.io,HalcyonChimera/osf.io,zachjanicki/osf.io,caneruguz/osf.io,leb2dg/osf.io,monikagrabowska/osf.io,kwierman/osf.io
/** * Builds full page project browser */ 'use strict'; var $ = require('jquery'); // jQuery var m = require('mithril'); // exposes mithril methods, useful for redraw etc. var ProjectOrganizer = require('js/project-organizer'); var $osf = require('js/osfHelpers'); var Raven = require('raven-js'); var LogText = require('js/logTextParser'); var AddProject = require('js/addProjectPlugin'); var mC = require('js/mithrilComponents'); var MOBILE_WIDTH = 767; // Mobile view break point for responsiveness var NODE_PAGE_SIZE = 10; // Load 10 nodes at a time from server /* Counter for unique ids for link objects */ if (!window.fileBrowserCounter) { window.fileBrowserCounter = 0; } //Backport of Set if (!window.Set) { window.Set = function Set(initial) { this.data = {}; initial = initial || []; for(var i = 0; i < initial.length; i++) this.add(initial[i]); }; Set.prototype = { has: function(item) { return this.data[item] === true; }, clear: function() { this.data = {}; }, add:function(item) { this.data[item] = true; }, delete: function(item) { delete this.data[item]; } }; } function NodeFetcher(type, link) { this.type = type || 'nodes'; this.loaded = 0; this.total = 0; this._flat = []; this._orphans = []; this._cache = {}; this._promise = null; this._continue = true; this.tree = { 0: { id: 0, data: {}, children: [] } }; this._callbacks = { done: [this._onFinish.bind(this)], page: [], children: [], fetch : [] }; this.nextLink = link || $osf.apiV2Url('users/me/' + this.type + '/', { query : { 'related_counts' : 'children', 'embed' : 'contributors' }}); } NodeFetcher.prototype = { isFinished: function() { return this.loaded >= this.total && this._promise === null && this._orphans.length === 0; }, isEmpty: function() { return this.loaded === 0 && this.isFinished(); }, progress: function() { return Math.ceil(this.loaded / (this.total || 1) * 100); }, start: function() { return this.resume(); }, pause: function() { this._continue = false; }, resume: function() { this._continue = true; if (!this.nextLink) return this._promise = null; if (this._promise) return this._promise; return this._promise = m.request({method: 'GET', url: this.nextLink, config: xhrconfig, background: true}) .then(function(results) {this._promise = null; return results;}.bind(this)) .then(this._success.bind(this), this._fail.bind(this)) .then((function() { m.redraw(true); if(this.nextLink && this._continue) return this.resume(); }).bind(this)); }, add: function(item) { if (!this.isFinished() && this._flat.indexOf(item) !== - 1) return; this.total++; this.loaded++; this._flat.unshift(item); }, remove: function(item) { item = item.id || item; if (!this._cache[item]) return; delete this._cache[item]; for(var i = 0; i < this._flat.length; i++) if (this._flat[i].id === item) { this._flat.splice(i, 1); break; } }, get: function(id) { if (!this._cache[id]) return this.fetch(id); var deferred = m.deferred(); deferred.resolve(this._cache[id]); return deferred.promise; }, getChildren: function(id) { //TODO Load via rootNode if (this._cache[id].relationships.children.links.related.meta.count !== this._cache[id].children.length) { return this.fetchChildren(this._cache[id]); } var deferred = m.deferred(); deferred.resolve(this._cache[id].children); return deferred.promise; }, fetch: function(id, cb) { // TODO This method is currently untested var url = $osf.apiV2Url(this.type + '/' + id + '/', {query: {related_counts: 'children', embed: 'contributors' }}); return m.request({method: 'GET', url: url, config: xhrconfig, background: true}) .then((function(result) { this.add(result.data); return result.data; }).bind(this), this._fail.bind(this)); }, fetchChildren: function(parent) { //TODO Allow suspending of children return m.request({method: 'GET', url: parent.relationships.children.links.related.href + '?embed=contributors', config: xhrconfig, background: true}) .then(this._childrenSuccess.bind(this, parent), this._fail.bind(this)); }, _success: function(results) { // Only reset if we're lower as loading children will increment this number if (this.total < results.links.meta.total) this.total = results.links.meta.total; this.nextLink = results.links.next; this.loaded += results.data.length; for(var i = 0; i < results.data.length; i++) { if (this.type === 'registrations' && (results.data[i].attributes.retracted === true || results.data[i].attributes.pending_registration_approval === true)) continue; // Exclude retracted and pending registrations else if (results.data[i].relationships.parent) this._orphans.push(results.data[i]); else this._flat.push(results.data[i]); if (this._cache[results.data[i].id]) continue; this._cache[results.data[i].id] = _formatDataforPO(results.data[i]); this._cache[results.data[i].id].children = []; this._orphans = this._orphans.filter((function(item) { var parentId = item.relationships.parent.links.related.href.split('/').splice(-2, 1)[0]; if (!this._cache[parentId]) return true; this._cache[parentId].children.push(item); return false; }).bind(this)); // if (results.data[i].relationships.children.links.related.meta.count > 0) // this.fetchChildren(results.data[i]); } this._callbacks.page.forEach((function(cb) { cb(this, results.data); }).bind(this)); if (!this.nextLink) this._callbacks.done.forEach((function(cb) { cb(this); }).bind(this)); }, _childrenSuccess: function(parent, results) { this.total += results.links.meta.total; for(var i = 0; i < results.data.length; i++) { this._cache[results.data[i].id] = results.data[i]; this._cache[parent.id].children.push(_formatDataforPO(results.data[i])); } return this._cache[parent.id].children; }, _fail: function(result) { Raven.captureMessage('Error loading nodes with nodeType ' + this.type + ' at url ' + this.nextLink, {requestReturn: result}); $osf.growl('We\'re having some trouble contacting our servers. Try reloading the page.', 'Something went wrong!', 'danger', 5000); this.resume(); }, _onFinish: function() { this._flat = this._orphans.concat(this._flat).sort(function(a,b) { a = new Date(a.attributes.date_modified); b = new Date(b.attributes.date_modified); if (a > b) return -1; if (a < b) return 1; return 0; }); this._orphans = []; }, on: function(type, func) { if (!Array.isArray(type)) type = [type]; //Valid types are children, page, done for(var i = 0; i < type.length; i++) this._callbacks[type[i]].push(func); } }; function getUID() { window.fileBrowserCounter = window.fileBrowserCounter + 1; return window.fileBrowserCounter; } /* Send with ajax calls to work with api2 */ var xhrconfig = function (xhr) { xhr.withCredentials = true; xhr.setRequestHeader('Content-Type', 'application/vnd.api+json;'); xhr.setRequestHeader('Accept', 'application/vnd.api+json; ext=bulk'); }; /* Adjust item data for treebeard to be able to filter tags and contributors not in the view */ function _formatDataforPO(item) { item.kind = 'folder'; item.uid = item.id; item.name = item.attributes.title; item.tags = item.attributes.tags.toString(); item.contributors = ''; if (item.embeds.contributors.data){ item.embeds.contributors.data.forEach(function(c){ var attr; if (c.embeds.users.data) { attr = c.embeds.users.data.attributes; } else { attr = c.embeds.users.errors[0].meta; } item.contributors += attr.full_name + ' ' + attr.middle_names + ' ' + attr.given_name + ' ' + attr.family_name + ' ' ; }); } item.date = new $osf.FormattableDate(item.attributes.date_modified); return item; } /* Small constructor for creating same type of links */ var LinkObject = function _LinkObject (type, data, label, institutionId) { if (type === undefined || data === undefined || label === undefined) { throw new Error('LinkObject expects type, data and label to be defined.'); } var self = this; self.id = getUID(); self.type = type; self.data = data; self.label = label; }; /** * Returns the object to send to the API to send a node_link to collection * @param id {String} unique id of the node like 'ez8f3' * @returns {{data: {type: string, relationships: {nodes: {data: {type: string, id: *}}}}}} */ function buildCollectionNodeData (id) { return { 'data': [{ 'type': 'linked_nodes', 'id': id }] }; } /** * Initialize File Browser. Prepares an option object within FileBrowser * @constructor */ var MyProjects = { controller : function (options) { var self = this; self.wrapperSelector = options.wrapperSelector; // For encapsulating each implementation of this component in multiple use self.projectOrganizerOptions = options.projectOrganizerOptions || {}; self.viewOnly = options.viewOnly || false; self.institutionId = options.institutionId || false; self.logUrlCache = {}; // dictionary of load urls to avoid multiple calls with little refactor self.nodeUrlCache = {}; // Cached returns of the project related urls // VIEW STATES self.showInfo = m.prop(true); // Show the info panel self.showSidebar = m.prop(false); // Show the links with collections etc. used in narrow views self.allProjectsLoaded = m.prop(false); self.categoryList = []; self.loadValue = m.prop(0); // What percentage of the project loading is done //self.loadCounter = m.prop(0); // Count how many items are received from the server self.currentView = m.prop({ collection : null, // Linkobject contributor : [], tag : [], totalRows: 0 }); self.filesData = m.prop(); // Treebeard functions looped through project organizer. // We need to pass these in to avoid reinstantiating treebeard but instead repurpose (update) the top level folder self.treeData = m.prop({}); // Top level object that houses all the rows self.buildTree = m.prop(null); // Preprocess function that adds to each item TB specific attributes self.updateFolder = m.prop(null); // Updates view to redraw without messing up scroll location self.multiselected = m.prop(); // Updated the selected list in treebeard self.highlightMultiselect = m.prop(null); // does highlighting background of the row // Add All my Projects and All my registrations to collections self.systemCollections = options.systemCollections || [ new LinkObject('collection', { nodeType : 'projects'}, 'All my projects'), new LinkObject('collection', { nodeType : 'registrations'}, 'All my registrations') ]; self.fetchers = {}; self.fetchers[self.systemCollections[0].id] = new NodeFetcher('nodes'); self.fetchers[self.systemCollections[1].id] = new NodeFetcher('registrations'); // Initial Breadcrumb for All my projects var initialBreadcrumbs = options.initialBreadcrumbs || [self.systemCollections[0]]; self.breadcrumbs = m.prop(initialBreadcrumbs); // Calculate name filters self.nameFilters = []; // Calculate tag filters self.tagFilters = []; // Load categories to pass in to create project self.loadCategories = function _loadCategories () { var promise = m.request({method : 'OPTIONS', url : $osf.apiV2Url('nodes/', { query : {}}), config : xhrconfig}); promise.then(function _success(results){ if(results.actions && results.actions.POST.category){ self.categoryList = results.actions.POST.category.choices; self.categoryList.sort(function(a, b){ // Quick alphabetical sorting if(a.value < b.value) return -1; if(a.value > b.value) return 1; return 0; }); } }, function _error(results){ var message = 'Error loading project category names.'; Raven.captureMessage(message, {requestReturn: results}); }); return promise; }; // Activity Logs self.activityLogs = m.prop(); self.logRequestPending = false; self.showMoreActivityLogs = m.prop(null); self.getLogs = function _getLogs (url, addToExistingList) { var cachedResults; if(!addToExistingList){ self.activityLogs([]); // Empty logs from other projects while load is happening; self.showMoreActivityLogs(null); } function _processResults (result){ self.logUrlCache[url] = result; result.data.map(function(log){ log.attributes.formattableDate = new $osf.FormattableDate(log.attributes.date); if(addToExistingList){ self.activityLogs().push(log); } }); if(!addToExistingList){ self.activityLogs(result.data); // Set activity log data } self.showMoreActivityLogs(result.links.next); // Set view for show more button } if(self.logUrlCache[url]){ cachedResults = self.logUrlCache[url]; _processResults(cachedResults); } else { self.logRequestPending = true; var promise = m.request({method : 'GET', url : url, config : xhrconfig}); promise.then(_processResults); promise.then(function(){ self.logRequestPending = false; }); return promise; } }; // separate concerns, wrap getlogs here to get logs for the selected item self.getCurrentLogs = function _getCurrentLogs ( ){ if(self.selected().length === 1 && !self.logRequestPending){ var item = self.selected()[0]; var id = item.data.id; if(!item.data.attributes.retracted){ var urlPrefix = item.data.attributes.registration ? 'registrations' : 'nodes'; var url = $osf.apiV2Url(urlPrefix + '/' + id + '/logs/', { query : { 'page[size]' : 6, 'embed' : ['nodes', 'user', 'linked_node', 'template_node', 'contributors']}}); var promise = self.getLogs(url); return promise; } } }; /* filesData is the link that loads tree data. This function refreshes that information. */ self.updateFilesData = function _updateFilesData(linkObject) { if ((linkObject.type === 'node') && self.viewOnly){ return; } self.updateTbMultiselect([]); // clear multiselected, updateTreeData will repick self.updateFilter(linkObject); // Update what filters currently selected self.updateBreadcrumbs(linkObject); // Change breadcrumbs self.updateList(); // Reset and load item self.showSidebar(false); }; // INFORMATION PANEL /* Defines the current selected item so appropriate information can be shown */ self.selected = m.prop([]); self.updateSelected = function _updateSelected (selectedList){ self.selected(selectedList); self.getCurrentLogs(); }; /** * Update the currentView * @param filter */ self.updateFilter = function _updateFilter(filter) { // if collection, reset currentView otherwise toggle the item in the list of currentview items if (['node', 'collection'].indexOf(filter.type) === -1 ) { var filterIndex = self.currentView()[filter.type].indexOf(filter); if(filterIndex !== -1) self.currentView()[filter.type].splice(filterIndex,1); else self.currentView()[filter.type].push(filter); return; } if (self.currentView().fetcher) self.currentView().fetcher.pause(); self.currentView().tag = []; self.currentView().contributor = []; self.currentView().fetcher = self.fetchers[filter.id]; self.currentView().fetcher.resume(); self.loadValue(self.currentView().fetcher.isFinished() ? 100 : self.currentView().fetcher.progress()); self.generateFiltersList(); if (filter.type === 'collection') self.currentView().collection = filter; }; self.removeProjectFromCollections = function _removeProjectFromCollection () { // Removes selected items from collect var currentCollection = self.currentView().collection; var collectionNode = currentCollection.data.node; // If it's not a system collection like projects or registrations this will have a node var data = { data: self.selected().map(function(item){ return {id: item.data.id, type: 'linked_nodes'}; }) }; m.request({ method : 'DELETE', url : collectionNode.links.self + 'relationships/' + 'linked_nodes/', //collection.links.self + 'node_links/' + item.data.id + '/', //collection.links.self + relationship/ + linked_nodes/ config : xhrconfig, data : data }).then(function(result) { data.data.forEach(function(item) { self.fetchers[currentCollection.id].remove(item.id); currentCollection.data.count(currentCollection.data.count()-1); }); self.updateList(); }, function _removeProjectFromCollectionsFail(result){ var message = 'Some projects'; if(data.data.length === 1) { message = self.selected()[0].data.name; } else { message += ' could not be removed from the collection'; } $osf.growl(message, 'Please try again.', 'danger', 5000); }); }; // remove this contributor from list of contributors self.unselectContributor = function (id){ self.currentView().contributor.forEach(function (c, index, arr) { if(c.data.id === id){ arr.splice(index, 1); self.updateList(); } }); }; self.unselectTag = function (tag){ self.currentView().tag.forEach(function (c, index, arr) { if(c.data.tag === tag){ arr.splice(index, 1); self.updateList(); } }); }; // Update what is viewed self.updateList = function _updateList (){ if (!self.buildTree()) return; // Treebeard hasn't loaded yet var viewData = self.filteredData(); self.updateTreeData(0, viewData, true); self.currentView().totalRows = viewData.length; }; self.filteredData = function() { var tags = self.currentView().tag; var contributors = self.currentView().contributor; return self.currentView().fetcher._flat.filter(function(node) { var tagMatch = tags.length === 0; var contribMatch = contributors.length === 0; for (var i = 0; i < contributors.length; i++) if (node.contributorSet.has(contributors[i].data.id)) { contribMatch = true; break; } for (var j = 0; j < tags.length; j++) if (node.tagSet.has(tags[j].label)) { tagMatch = true; break; } return tagMatch && contribMatch; }); }; self.updateTbMultiselect = function (itemsArray) { self.multiselected()(itemsArray); self.highlightMultiselect()(); self.updateSelected(itemsArray); }; self.updateTreeData = function (begin, data, clear) { var item; if (clear) { self.treeData().children = []; } for (var i = begin; i < data.length; i++){ item = data[i]; _formatDataforPO(item); var child = self.buildTree()(item, self.treeData()); self.treeData().add(child); } self.updateFolder()(null, self.treeData()); // Manually select first item without triggering a click if(self.multiselected()().length === 0 && self.treeData().children[0]){ self.updateTbMultiselect([self.treeData().children[0]]); } m.redraw(true); }; self.generateSets = function (item){ item.tagSet = new Set(item.attributes.tags || []); var contributors = item.embeds.contributors.data || []; item.contributorSet= new Set(contributors.map(function(contrib) { return contrib.id; })); }; self.nonLoadTemplate = function (){ var template = ''; if(!self.currentView().fetcher.isEmpty()) { return; } var lastcrumb = self.breadcrumbs()[self.breadcrumbs().length-1]; var hasFilters = self.currentView().contributor.length || self.currentView().tag.length; if(hasFilters){ template = m('.db-non-load-template.m-md.p-md.osf-box', 'No projects match this filter.'); } else { if(lastcrumb.type === 'collection'){ if(lastcrumb.data.nodeType === 'projects'){ template = m('.db-non-load-template.m-md.p-md.osf-box', 'You have not created any projects yet.'); } else if (lastcrumb.data.nodeType === 'registrations'){ template = m('.db-non-load-template.m-md.p-md.osf-box', 'You have not made any registrations yet.'); } else { template = m('.db-non-load-template.m-md.p-md.osf-box', 'This collection is empty. To add projects or registrations, click "All my projects" or "All my registrations" in the sidebar, and then drag and drop items into the collection link.'); } } else { if(!self.currentView().fetcher.isEmpty()){ template = m('.db-non-load-template.m-md.p-md.osf-box.text-center', m('.ball-scale.text-center', m('')) ); } else { template = m('.db-non-load-template.m-md.p-md.osf-box.text-center', [ 'No components to display. Either there are no components, or there are private components in which you are not a contributor.' ]); } } } return template; }; /** * Generate this list from user's projects */ self.generateFiltersList = function(noClear) { self.users = {}; self.tags = {}; Object.keys(self.currentView().fetcher._cache).forEach(function(key) { var item = self.currentView().fetcher._cache[key]; self.generateSets(item); var contributors = item.embeds.contributors.data || []; for(var i = 0; i < contributors.length; i++) { var u = contributors[i]; if (u.id === window.contextVars.currentUser.id) { continue; } if(self.users[u.id] === undefined) { self.users[u.id] = { data : u, count: 1 }; } else { self.users[u.id].count++; } } var tags = item.attributes.tags || []; for(var j = 0; j < tags.length; j++) { var t = tags[j]; if(self.tags[t] === undefined) { self.tags[t] = 1; } else { self.tags[t]++; } } }); // Sorting by number of items utility function function sortByCountDesc (a,b){ var aValue = a.data.count; var bValue = b.data.count; if (bValue > aValue) { return 1; } if (bValue < aValue) { return -1; } return 0; } // Add to lists with numbers if (!noClear) self.nameFilters = []; for (var user in self.users) { var u2 = self.users[user]; if (u2.data.embeds.users.data) { var found = self.nameFilters.find(function(lo) { return lo.label === u2.data.embeds.users.data.attributes.full_name; }); if (!found) self.nameFilters.push(new LinkObject('contributor', { id : u2.data.id, count : u2.count, query : { 'related_counts' : 'children' }}, u2.data.embeds.users.data.attributes.full_name, options.institutionId || false)); else found.data.count = u2.count; } } // order names self.nameFilters.sort(sortByCountDesc); if (!noClear) self.tagFilters = []; for (var tag in self.tags){ var t2 = self.tags[tag]; var found = self.tagFilters.find(function(lo) { return lo.label === tag; }); if (!found) self.tagFilters.push(new LinkObject('tag', { tag : tag, count : t2, query : { 'related_counts' : 'children' }}, tag, options.institutionId || false)); else found.data.count = t2; } // order tags self.tagFilters.sort(sortByCountDesc); m.redraw(true); }; // BREADCRUMBS self.updateBreadcrumbs = function _updateBreadcrumbs (linkObject){ if (linkObject.type === 'collection'){ self.breadcrumbs([linkObject]); return; } if (linkObject.type === 'contributor' || linkObject.type === 'tag'){ return; } if (linkObject.placement === 'breadcrumb'){ self.breadcrumbs().splice(linkObject.index+1, self.breadcrumbs().length-linkObject.index-1); return; } if(linkObject.ancestors && linkObject.ancestors.length > 0){ linkObject.ancestors.forEach(function(item){ var ancestorLink = new LinkObject('node', item.data, item.data.name); self.fetchers[ancestorLink.id] = new NodeFetcher(item.data.types, item.data.relationships.children.links.related.href + '?embed=contributors'); self.fetchers[ancestorLink.id].on(['page', 'done'], self.onPageLoad); self.breadcrumbs().push(ancestorLink); }); } self.breadcrumbs().push(linkObject); }; // GET COLLECTIONS // Default system collections self.collections = m.prop([].concat(self.systemCollections)); self.collectionsPageSize = m.prop(5); // Load collection list self.loadCollections = function _loadCollections (url){ var promise = m.request({method : 'GET', url : url, config : xhrconfig}); promise.then(function(result){ result.data.forEach(function(node){ var count = node.relationships.linked_nodes.links.related.meta.count; self.collections().push(new LinkObject('collection', { path : 'collections/' + node.id + '/linked_nodes/', query : { 'related_counts' : 'children', 'embed' : 'contributors' }, nodeType : 'collection', node : node, count : m.prop(count), loaded: 1 }, node.attributes.title)); var link = $osf.apiV2Url('collections/' + node.id + '/linked_nodes/', { query : { 'related_counts' : 'children', 'embed' : 'contributors' }}); self.fetchers[self.collections()[self.collections().length-1].id] = new NodeFetcher('nodes', link); self.fetchers[self.collections()[self.collections().length-1].id].on(['page', 'done'], self.onPageLoad); }); if(result.links.next){ self.loadCollections(result.links.next); } }, function(){ var message = 'Collections could not be loaded.'; $osf.growl(message, 'Please reload the page.'); Raven.captureMessage(message, { url: url }); }); return promise; }; self.sidebarInit = function _sidebarInit (element, isInit) { $('[data-toggle="tooltip"]').tooltip(); }; // Resets UI to show All my projects and update states self.resetUi = function _resetUi(){ var linkObject = self.systemCollections[0]; self.updateBreadcrumbs(linkObject); self.updateFilter(linkObject); }; self.onPageLoad = function(fetcher, pageData) { if(self.currentView().fetcher === fetcher) { self.loadValue(fetcher.isFinished() ? 100 : fetcher.progress()); self.generateFiltersList(true); if (!pageData) { for(var i = 0; i < fetcher._flat.length; i++){ var fetcherItem = fetcher._flat[i]; var tbItem = self.treeData().children[i] ? self.treeData().children[i].data : {}; if(fetcherItem === tbItem){ continue; } var itemToAdd = self.buildTree()(fetcherItem, self.treeData()); itemToAdd.parentID = self.treeData().id; itemToAdd.open = false; itemToAdd.load = false; self.treeData().children.splice(i, 0, itemToAdd); } self.updateFolder()(null, self.treeData(), true); return m.redraw(); } if(self.treeData().children){ var begin = self.treeData().children.length; var data = self.filteredData(); self.updateTreeData(begin, data); self.currentView().totalRows = fetcher._flat.length; } } }; self.init = function _init_fileBrowser() { self.loadCategories().then(function(){ self.fetchers[self.systemCollections[0].id].on(['page', 'done'], self.onPageLoad); self.fetchers[self.systemCollections[1].id].on(['page', 'done'], self.onPageLoad); }); if (!self.viewOnly){ var collectionsUrl = $osf.apiV2Url('collections/', { query : {'related_counts' : 'linked_nodes', 'page[size]' : self.collectionsPageSize(), 'sort' : 'date_created', 'embed' : 'node_links'}}); self.loadCollections(collectionsUrl); } // Add linkObject to the currentView self.updateFilter(self.collections()[0]); }; self.init(); }, view : function (ctrl, args) { var mobile = window.innerWidth < MOBILE_WIDTH; // true if mobile view var infoPanel = ''; var poStyle = 'width : 72%'; // Other percentages are set in CSS in file-browser.css These are here because they change var sidebarButtonClass = 'btn-default'; if (ctrl.showInfo() && !mobile){ infoPanel = m('.db-infobar', m.component(Information, ctrl)); poStyle = 'width : 47%; display: block'; } if(ctrl.showSidebar()){ sidebarButtonClass = 'btn-primary'; } if (mobile) { poStyle = 'width : 100%; display: block'; if(ctrl.showSidebar()){ poStyle = 'display: none'; } } else { ctrl.showSidebar(true); } var projectOrganizerOptions = $.extend( {}, { filesData : [], onPageLoad: ctrl.onPageLoad, updateSelected : ctrl.updateSelected, updateFilesData : ctrl.updateFilesData, LinkObject : LinkObject, NodeFetcher : NodeFetcher, formatDataforPO : _formatDataforPO, wrapperSelector : args.wrapperSelector, resetUi : ctrl.resetUi, showSidebar : ctrl.showSidebar, loadValue : ctrl.loadValue, loadCounter : ctrl.loadCounter, treeData : ctrl.treeData, buildTree : ctrl.buildTree, updateFolder : ctrl.updateFolder, currentView: ctrl.currentView, fetchers : ctrl.fetchers, indexes : ctrl.indexes, multiselected : ctrl.multiselected, highlightMultiselect : ctrl.highlightMultiselect }, ctrl.projectOrganizerOptions ); return [ !ctrl.institutionId ? m('.dashboard-header', m('.row', [ m('.col-xs-8', m('h3', [ 'My Projects ', m('small.hidden-xs', 'Browse and organize all your projects') ])), m('.col-xs-4.p-sm', m('.pull-right', m.component(AddProject, { buttonTemplate: m('.btn.btn-success.btn-success-high-contrast.f-w-xl[data-toggle="modal"][data-target="#addProject"]', {onclick: function() { $osf.trackClick('myProjects', 'add-project', 'open-add-project-modal'); }}, 'Create Project'), parentID: null, modalID: 'addProject', title: 'Create new project', categoryList: ctrl.categoryList, stayCallback: function () { // Fetch details of added item from server and redraw treebeard var projects = ctrl.fetchers[ctrl.systemCollections[0].id]; projects.fetch(this.saveResult().data.id).then(function(){ ctrl.updateTreeData(0, projects._flat, true); }); }, trackingCategory: 'myProjects', trackingAction: 'add-project', templatesFetcher: ctrl.fetchers[ctrl.systemCollections[0].id] }))) ])) : '', m('.db-header.row', [ m('.col-xs-12.col-sm-8.col-lg-9', m.component(Breadcrumbs,ctrl)), m('.db-buttonRow.col-xs-12.col-sm-4.col-lg-3', [ mobile ? m('button.btn.btn-sm.m-r-sm', { 'class' : sidebarButtonClass, onclick : function () { ctrl.showSidebar(!ctrl.showSidebar()); $osf.trackClick('myProjects', 'mobile', 'click-bars-to-toggle-collections-or-projects'); } }, m('.fa.fa-bars')) : '', m('.db-poFilter.m-r-xs') ]) ]), ctrl.showSidebar() ? m('.db-sidebar', { config : ctrl.sidebarInit}, [ mobile ? [ m('.db-dismiss', m('button.close[aria-label="Close"]', { onclick : function () { ctrl.showSidebar(false); $osf.trackClick('myProjects', 'mobile', 'close-toggle-instructions'); } }, [ m('span[aria-hidden="true"]','×') ])), m('p.p-sm.text-center.text-muted', [ 'Select a list below to see the projects. or click ', m('i.fa.fa-bars'), ' button above to toggle.' ]) ] : '', m.component(Collections, ctrl), m.component(Filters, ctrl) ]) : '', m('.db-main', { style : poStyle },[ ctrl.loadValue() < 100 ? m('.line-loader', [ m('.line-empty'), m('.line-full.bg-color-blue', { style : 'width: ' + ctrl.loadValue() +'%'}), m('.load-message', 'Fetching more projects') ]) : '', ctrl.nonLoadTemplate(), m('.db-poOrganizer', { style : ctrl.currentView().fetcher.isEmpty() ? 'display: none' : 'display: block' }, m.component( ProjectOrganizer, projectOrganizerOptions)) ] ), mobile ? '' : m('.db-info-toggle',{ onclick : function _showInfoOnclick(){ ctrl.showInfo(!ctrl.showInfo()); $osf.trackClick('myProjects', 'information-panel', 'show-hide-information-panel'); } }, ctrl.showInfo() ? m('i.fa.fa-chevron-right') : m('i.fa.fa-chevron-left') ), infoPanel, m.component(Modals, ctrl) ]; } }; /** * Collections Module. * @constructor */ var Collections = { controller : function(args){ var self = this; self.collections = args.collections; self.pageSize = args.collectionsPageSize; self.newCollectionName = m.prop(''); self.newCollectionRename = m.prop(''); self.dismissModal = function () { $('.modal').modal('hide'); }; self.currentPage = m.prop(1); self.totalPages = m.prop(1); self.calculateTotalPages = function _calculateTotalPages(result){ if(result){ // If this calculation comes after GET call to collections self.totalPages(Math.ceil((result.links.meta.total + args.systemCollections.length)/self.pageSize())); } else { self.totalPages(Math.ceil((self.collections().length)/self.pageSize())); } }; self.pageSize = m.prop(5); self.isValid = m.prop(false); self.validationError = m.prop(''); self.showCollectionMenu = m.prop(false); // Show hide ellipsis menu for collections self.collectionMenuObject = m.prop({item : {label:null}, x : 0, y : 0}); // Collection object to complete actions on menu self.resetCollectionMenu = function () { self.collectionMenuObject({item : {label:null}, x : 0, y : 0}); }; self.updateCollectionMenu = function _updateCollectionMenu (item, event) { var offset = $(event.target).offset(); var x = offset.left; var y = offset.top; if (event.view.innerWidth < MOBILE_WIDTH){ x = x-105; // width of this menu plus padding y = y-270; // fixed height from collections parent to top with adjustments for this menu div } self.showCollectionMenu(true); item.renamedLabel = item.label; self.collectionMenuObject({ item : item, x : x, y : y }); }; self.init = function _collectionsInit (element, isInit) { self.calculateTotalPages(); $(window).click(function(event){ var target = $(event.target); if(!target.hasClass('collectionMenu') && !target.hasClass('fa-ellipsis-v') && target.parents('.collection').length === 0) { self.showCollectionMenu(false); m.redraw(); // we have to force redraw here } }); }; self.addCollection = function _addCollection () { var url = $osf.apiV2Url('collections/', {}); var data = { 'data': { 'type': 'collections', 'attributes': { 'title': self.newCollectionName(), } } }; var promise = m.request({method : 'POST', url : url, config : xhrconfig, data : data}); promise.then(function(result){ var node = result.data; var count = node.relationships.linked_nodes.links.related.meta.count || 0; self.collections().push(new LinkObject('collection', { path : 'collections/' + node.id + '/linked_nodes/', query : { 'related_counts' : 'children' }, node : node, count : m.prop(count), nodeType : 'collection' }, node.attributes.title)); var link = $osf.apiV2Url('collections/' + node.id + '/linked_nodes/', { query : { 'related_counts' : 'children', 'embed' : 'contributors' }}); args.fetchers[self.collections()[self.collections().length-1].id] = new NodeFetcher('nodes', link); args.fetchers[self.collections()[self.collections().length-1].id].on(['page', 'done'], args.onPageLoad); self.newCollectionName(''); self.calculateTotalPages(); self.currentPage(self.totalPages()); // Go to last page args.sidebarInit(); }, function(){ var name = self.newCollectionName(); var message = '"' + name + '" collection could not be created.'; $osf.growl(message, 'Please try again', 'danger', 5000); Raven.captureMessage(message, { url: url, data : data }); self.newCollectionName(''); }); self.dismissModal(); return promise; }; self.deleteCollection = function _deleteCollection(){ var url = self.collectionMenuObject().item.data.node.links.self; var promise = m.request({method : 'DELETE', url : url, config : xhrconfig}); promise.then(function(result){ for ( var i = 0; i < self.collections().length; i++) { var item = self.collections()[i]; if (item.data.node && item.data.node.id === self.collectionMenuObject().item.data.node.id) { if (args.currentView().fetcher === args.fetchers[item.id]) args.updateFilesData(self.collections()[0]); // Reset to all my projects delete args.fetchers[item.id]; self.collections().splice(i, 1); break; } } self.calculateTotalPages(); }, function(){ var name = self.collectionMenuObject().item.label; var message = '"' + name + '" could not be deleted.'; $osf.growl(message, 'Please try again', 'danger', 5000); Raven.captureMessage(message, {collectionObject: self.collectionMenuObject() }); }); self.dismissModal(); return promise; }; self.renameCollection = function _renameCollection() { var url = self.collectionMenuObject().item.data.node.links.self; var nodeId = self.collectionMenuObject().item.data.node.id; var title = self.collectionMenuObject().item.renamedLabel; var data = { 'data': { 'type': 'collections', 'id': nodeId, 'attributes': { 'title': title } } }; var promise = m.request({method : 'PATCH', url : url, config : xhrconfig, data : data}); promise.then(function(result){ self.collectionMenuObject().item.label = title; }, function(){ var name = self.collectionMenuObject().item.label; var message = '"' + name + '" could not be renamed.'; $osf.growl(message, 'Please try again', 'danger', 5000); Raven.captureMessage(message, {collectionObject: self.collectionMenuObject() }); }); self.dismissModal(); self.isValid(false); return promise; }; self.applyDroppable = function _applyDroppable ( ){ $('.db-collections ul>li.acceptDrop').droppable({ hoverClass: 'bg-color-hover', drop: function( event, ui ) { var dataArray = []; var collection = self.collections()[$(this).attr('data-index')]; var collectionLink = $osf.apiV2Url(collection.data.path, { query : collection.data.query}); // If multiple items are dragged they have to be selected to make it work if (args.selected().length > 1) { dataArray = args.selected().map(function(item){ $osf.trackClick('myProjects', 'projectOrganizer', 'multiple-projects-dragged-to-collection'); return buildCollectionNodeData(item.data.id); }); } else { // if single items are passed use the event information dataArray.push(buildCollectionNodeData(ui.draggable.find('.title-text>a').attr('data-nodeID'))); // data-nodeID attribute needs to be set in project organizer building title column var projectName = ui.draggable.find('.title-text>a').attr('data-nodeTitle'); $osf.trackClick('myProjects', 'projectOrganizer', 'single-project-dragged-to-collection'); } function save(index, data) { if (!data[index]) return args.currentView().fetcher === args.fetchers[collection.id] ? args.updateList() : null; m.request({ method : 'POST', url : collection.data.node.links.self + 'relationships/linked_nodes/', config : xhrconfig, data : data[index] }).then(function(result){ if (result){ return args.currentView().fetcher .get(result.data[(result.data).length - 1].id) .then(function(item) { args.fetchers[collection.id].add(item); collection.data.count(collection.data.count() + 1); save(index + 1, data); }); } else { var name = projectName ? projectName : args.selected()[index] ? args.selected()[index].data.name : 'Item '; var message = '"' + name + '" is already in "' + collection.label + '"' ; $osf.growl(message,null, 'warning', 4000); save(index + 1, data); } }); } save(0, dataArray); } }); }; self.validateName = function _validateName (val){ if (val === 'Bookmarks') { self.isValid(false); self.validationError('"Bookmarks" is a reserved collection name. Please use another name.'); } else { self.validationError(''); self.isValid(val.length); } }; self.init(); }, view : function (ctrl, args) { var selectedCSS; var submenuTemplate; var viewOnly = args.viewOnly; ctrl.calculateTotalPages(); var collectionOnclick = function (item){ args.updateFilesData(item); $osf.trackClick('myProjects', 'projectOrganizer', 'open-collection'); }; var collectionList = function () { var item; var index; var list = []; var childCount; var dropAcceptClass; if(ctrl.currentPage() > ctrl.totalPages()){ ctrl.currentPage(ctrl.totalPages()); } var begin = ((ctrl.currentPage()-1)*ctrl.pageSize()); // remember indexes start from 0 var end = ((ctrl.currentPage()) *ctrl.pageSize()); // 1 more than the last item if (ctrl.collections().length < end) { end = ctrl.collections().length; } var openCollectionMenu = function _openCollectionMenu(e) { var index = $(this).attr('data-index'); var selectedItem = ctrl.collections()[index]; ctrl.updateCollectionMenu(selectedItem, e); $osf.trackClick('myProjects', 'edit-collection', 'open-edit-collection-menu'); }; for (var i = begin; i < end; i++) { item = ctrl.collections()[i]; index = i; dropAcceptClass = index > 1 ? 'acceptDrop' : ''; childCount = item.data.count ? ' (' + item.data.count() + ')' : ''; if (args.currentView().collection === item) { selectedCSS = 'active'; } else { selectedCSS = ''; } if (item.data.nodeType === 'collection' && !item.data.node.attributes.bookmarks) { submenuTemplate = m('i.fa.fa-ellipsis-v.pull-right.text-muted.p-xs.pointer', { 'data-index' : i, onclick : openCollectionMenu }); } else { submenuTemplate = ''; } list.push(m('li.pointer', { className : selectedCSS + ' ' + dropAcceptClass, 'data-index' : index, onclick : collectionOnclick.bind(null, item) },[ m('span', item.label + childCount), submenuTemplate ] )); } return list; }; var collectionListTemplate = [ m('h5.clearfix', [ 'Collections ', m('i.fa.fa-question-circle.text-muted', { 'data-toggle': 'tooltip', 'title': 'Collections are groups of projects. You can create custom collections. Drag and drop your projects or bookmarked projects to add them.', 'data-placement' : 'bottom' }, ''), !viewOnly ? m('button.btn.btn-xs.btn-default[data-toggle="modal"][data-target="#addColl"].m-h-xs', {onclick: function() { $osf.trackClick('myProjects', 'add-collection', 'open-add-collection-modal'); }}, m('i.fa.fa-plus')) : '', m('.pull-right', ctrl.totalPages() > 1 ? m.component(MicroPagination, { currentPage : ctrl.currentPage, totalPages : ctrl.totalPages, type: 'collections' }) : '' ) ]), m('ul', { config: ctrl.applyDroppable },[ collectionList(), ctrl.showCollectionMenu() ? m('.collectionMenu',{ style : 'position:absolute;top: ' + ctrl.collectionMenuObject().y + 'px;left: ' + ctrl.collectionMenuObject().x + 'px;' }, [ m('.menuClose', { onclick : function (e) { ctrl.showCollectionMenu(false); ctrl.resetCollectionMenu(); $osf.trackClick('myProjects', 'edit-collection', 'click-close-edit-collection-menu'); } }, m('.text-muted','×')), m('ul', [ m('li[data-toggle="modal"][data-target="#renameColl"].pointer',{ onclick : function (e) { ctrl.showCollectionMenu(false); $osf.trackClick('myProjects', 'edit-collection', 'open-rename-collection-modal'); } }, [ m('i.fa.fa-pencil'), ' Rename' ]), m('li[data-toggle="modal"][data-target="#removeColl"].pointer',{ onclick : function (e) { ctrl.showCollectionMenu(false); $osf.trackClick('myProjects', 'edit-collection', 'open-delete-collection-modal'); } }, [ m('i.fa.fa-trash'), ' Delete' ]) ]) ]) : '' ]) ]; return m('.db-collections', [ collectionListTemplate, m('.db-collections-modals', [ m.component(mC.modal, { id: 'addColl', header : m('.modal-header', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', {onclick: function() { $osf.trackClick('myProjects', 'add-collection', 'click-close-add-collection-modal'); }}, [ m('span[aria-hidden="true"]','×') ]), m('h3.modal-title', 'Add new collection') ]), body : m('.modal-body', [ m('p', 'Collections are groups of projects that help you organize your work. After you create your collection, you can add projects by dragging them into the collection.'), m('.form-group', [ m('label[for="addCollInput].f-w-lg.text-bigger', 'Collection name'), m('input[type="text"].form-control#addCollInput', { onkeyup: function (ev){ var val = $(this).val(); ctrl.validateName(val); if(ctrl.isValid()){ if(ev.which === 13){ ctrl.addCollection(); } } ctrl.newCollectionName(val); }, onchange: function() { $osf.trackClick('myProjects', 'add-collection', 'type-collection-name'); }, placeholder : 'e.g. My Replications', value : ctrl.newCollectionName() }), m('span.help-block', ctrl.validationError()) ]) ]), footer: m('.modal-footer', [ m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : function(){ ctrl.dismissModal(); ctrl.newCollectionName(''); ctrl.isValid(false); $osf.trackClick('myProjects', 'add-collection', 'click-cancel-button'); } }, 'Cancel'), ctrl.isValid() ? m('button[type="button"].btn.btn-success', { onclick : function() { ctrl.addCollection(); $osf.trackClick('myProjects', 'add-collection', 'click-add-button'); }},'Add') : m('button[type="button"].btn.btn-success[disabled]', 'Add') ]) }), m.component(mC.modal, { id : 'renameColl', header: m('.modal-header', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', {onclick: function() { $osf.trackClick('myProjects', 'edit-collection', 'click-close-rename-modal'); }}, [ m('span[aria-hidden="true"]','×') ]), m('h3.modal-title', 'Rename collection') ]), body: m('.modal-body', [ m('.form-inline', [ m('.form-group', [ m('label[for="addCollInput]', 'Rename to: '), m('input[type="text"].form-control.m-l-sm',{ onkeyup: function(ev){ var val = $(this).val(); ctrl.validateName(val); if(ctrl.isValid()) { if (ev.which === 13) { // if enter is pressed ctrl.renameCollection(); } } ctrl.collectionMenuObject().item.renamedLabel = val; }, onchange: function() { $osf.trackClick('myProjects', 'edit-collection', 'type-rename-collection'); }, value: ctrl.collectionMenuObject().item.renamedLabel}), m('span.help-block', ctrl.validationError()) ]) ]) ]), footer : m('.modal-footer', [ m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : function(){ ctrl.isValid(false); $osf.trackClick('myProjects', 'edit-collection', 'click-cancel-rename-button'); } },'Cancel'), ctrl.isValid() ? m('button[type="button"].btn.btn-success', { onclick : function() { ctrl.renameCollection(); $osf.trackClick('myProjects', 'edit-collection', 'click-rename-button'); }},'Rename') : m('button[type="button"].btn.btn-success[disabled]', 'Rename') ]) }), m.component(mC.modal, { id: 'removeColl', header: m('.modal-header', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', {onclick: function() { $osf.trackClick('myProjects', 'edit-collection', 'click-close-delete-collection'); }}, [ m('span[aria-hidden="true"]','×') ]), m('h3.modal-title', 'Delete collection "' + ctrl.collectionMenuObject().item.label + '"?') ]), body: m('.modal-body', [ m('p', 'This will delete your collection, but your projects will not be deleted.') ]), footer : m('.modal-footer', [ m('button[type="button"].btn.btn-default[data-dismiss="modal"]', {onclick: function() { $osf.trackClick('myProjects', 'edit-collection', 'click-cancel-delete-collection'); }}, 'Cancel'), m('button[type="button"].btn.btn-danger', { onclick : function() { ctrl.deleteCollection(); $osf.trackClick('myProjects', 'edit-collection', 'click-delete-collection-button'); }},'Delete') ]) }) ]) ]); } }; /** * Small view component for compact pagination * Requires currentPage and totalPages to be m.prop * @type {{view: MicroPagination.view}} */ var MicroPagination = { view : function(ctrl, args) { if (args.currentPage() > args.totalPages()) { args.currentPage(args.totalPages()); } return m('span.osf-micro-pagination.m-l-xs', [ args.currentPage() > 1 ? m('span.m-r-xs.arrow.left.live', { onclick : function(){ args.currentPage(args.currentPage() - 1); $osf.trackClick('myProjects', 'paginate', 'get-prev-page-' + args.type); }}, m('i.fa.fa-angle-left')) : m('span.m-r-xs.arrow.left', m('i.fa.fa-angle-left')), m('span', args.currentPage() + '/' + args.totalPages()), args.currentPage() < args.totalPages() ? m('span.m-l-xs.arrow.right.live', { onclick : function(){ args.currentPage(args.currentPage() + 1); $osf.trackClick('myProjects', 'paginate', 'get-next-page-' + args.type); }}, m('i.fa.fa-angle-right')) : m('span.m-l-xs.arrow.right', m('i.fa.fa-angle-right')) ]); } }; /** * Breadcrumbs Module * @constructor */ var Breadcrumbs = { view : function (ctrl, args) { var viewOnly = args.viewOnly; var mobile = window.innerWidth < MOBILE_WIDTH; // true if mobile view var updateFilesOnClick = function (item) { if (item.type === 'node') args.updateFilesData(item, item.data.id); else args.updateFilesData(item); $osf.trackClick('myProjects', 'projectOrganizer', 'click-on-breadcrumbs'); }; var contributorsTemplate = []; var tagsTemplate = []; if(args.currentView().contributor.length) { contributorsTemplate.push(m('span.text-muted', 'with ')); args.currentView().contributor.forEach(function (c) { contributorsTemplate.push(m('span.filter-breadcrumb.myprojects', [ c.label, ' ', m('button', { onclick: function(){ args.unselectContributor(c.data.id); }}, m('span', '×')) ])); }); } if(args.currentView().tag.length){ tagsTemplate.push(m('span.text-muted.m-l-sm', 'tagged ')); args.currentView().tag.forEach(function(t){ tagsTemplate.push(m('span.filter-breadcrumb.myprojects', [ t.label, ' ', m('button', { onclick: function(){ args.unselectTag(t.data.tag); }}, m('span', '×')) ])); }); } var items = args.breadcrumbs(); if (mobile && items.length > 1) { return m('.db-breadcrumbs', [ m('ul', [ m('li', [ m('.btn.btn-link[data-toggle="modal"][data-target="#parentsModal"]', '...'), m('i.fa.fa-angle-right') ]), m('li', m('span.btn', items[items.length-1].label)) ]), m('#parentsModal.modal.fade[tabindex=-1][role="dialog"][aria-hidden="true"]', m('.modal-dialog', m('.modal-content', [ m('.modal-body', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', [ m('span[aria-hidden="true"]','×') ]), m('h4', 'Parent projects'), args.breadcrumbs().map(function(item, index, array){ if(index === array.length-1){ return m('.db-parent-row.btn', { style : 'margin-left:' + (index*20) + 'px;' }, [ m('i.fa.fa-angle-right.m-r-xs'), item.label ]); } item.index = index; // Add index to update breadcrumbs item.placement = 'breadcrumb'; // differentiate location for proper breadcrumb actions return m('.db-parent-row',[ m('span.btn.btn-link', { style : 'margin-left:' + (index*20) + 'px;', onclick : function() { args.updateFilesData(item); $('.modal').modal('hide'); } }, [ m('i.fa.fa-angle-right.m-r-xs'), item.label ]), contributorsTemplate, tagsTemplate ] ); }) ]) ]) ) ) ]); } return m('.db-breadcrumbs', m('ul', [ items.map(function(item, index, arr){ if(index === arr.length-1){ if(item.type === 'node'){ var linkObject = args.breadcrumbs()[args.breadcrumbs().length - 1]; var parentID = linkObject.data.id; var showAddProject = true; var addProjectTemplate = ''; var permissions = item.data.attributes.current_user_permissions; showAddProject = permissions.indexOf('admin') > -1 || permissions.indexOf('write') > -1; if (item.type === 'registration' || item.data.type === 'registrations' || item.data.nodeType === 'registrations'){ showAddProject = false; } if(showAddProject && !viewOnly){ addProjectTemplate = m.component(AddProject, { buttonTemplate: m('.btn.btn-sm.text-muted[data-toggle="modal"][data-target="#addSubComponent"]', {onclick: function() { $osf.trackClick('myProjects', 'add-component', 'open-add-component-modal'); }}, [m('i.fa.fa-plus.m-r-xs', {style: 'font-size: 10px;'}), 'Create component']), parentID: parentID, modalID: 'addSubComponent', title: 'Create new component', categoryList: args.categoryList, stayCallback: function () { var topLevelProject = args.fetchers[linkObject.id]; topLevelProject.fetch(this.saveResult().data.id, function(){ args.updateTreeData(0, topLevelProject._flat, true); }); }, trackingCategory: 'myProjects', trackingAction: 'add-component' }); } return [ m('li', [ m('span.btn', item.label), contributorsTemplate, tagsTemplate, m('i.fa.fa-angle-right') ]), addProjectTemplate ]; } } item.index = index; // Add index to update breadcrumbs item.placement = 'breadcrumb'; // differentiate location for proper breadcrumb actions return m('li',[ m('span.btn.btn-link', {onclick : updateFilesOnClick.bind(null, item)}, item.label), index === 0 && arr.length === 1 ? [contributorsTemplate, tagsTemplate] : '', m('i.fa.fa-angle-right'), ] ); }) ])); } }; /** * Filters Module. * @constructor */ var Filters = { controller : function (args) { var self = this; self.nameCurrentPage = m.prop(1); self.namePageSize = m.prop(4); self.nameTotalPages = m.prop(1); self.tagCurrentPage = m.prop(1); self.tagPageSize = m.prop(4); self.tagTotalPages = m.prop(1); }, view : function (ctrl, args) { if(args.nameFilters.length > 0) { ctrl.nameTotalPages(Math.ceil(args.nameFilters.length/ctrl.namePageSize())); } if(args.tagFilters.length > 0){ ctrl.tagTotalPages(Math.ceil(args.tagFilters.length/ctrl.tagPageSize())); } var filterContributor = function(item, tracking) { args.updateFilesData(item); $osf.trackClick('myProjects', 'filter', 'filter-by-contributor'); }; var filterTag = function(item, tracking) { args.updateFilesData(item); $osf.trackClick('myProjects', 'filter', 'filter-by-tag'); }; var returnNameFilters = function _returnNameFilters(){ if(args.currentView().fetcher.isEmpty()) return m('.text-muted.text-smaller', 'There are no collaborators in this collection yet.'); var list = []; var item; var i; var selectedCSS; var begin = ((ctrl.nameCurrentPage()-1) * ctrl.namePageSize()); // remember indexes start from 0 var end = ((ctrl.nameCurrentPage()) * ctrl.namePageSize()); // 1 more than the last item if (args.nameFilters.length < end) { end = args.nameFilters.length; } for (i = begin; i < end; i++) { item = args.nameFilters[i]; selectedCSS = args.currentView().contributor.indexOf(item) !== -1 ? '.active' : ''; list.push(m('li.pointer' + selectedCSS, {onclick : filterContributor.bind(null, item)}, m('span', item.label) )); } return list; }; var returnTagFilters = function _returnTagFilters(){ if(args.currentView().fetcher.isEmpty()) return m('.text-muted.text-smaller', 'Projects in this collection don\'t have any tags yet.'); var list = []; var selectedCSS; var item; var i; var begin = ((ctrl.tagCurrentPage()-1) * ctrl.tagPageSize()); // remember indexes start from 0 var end = ((ctrl.tagCurrentPage()) * ctrl.tagPageSize()); // 1 more than the last item if (args.tagFilters.length < end) { end = args.tagFilters.length; } for (i = begin; i < end; i++) { item = args.tagFilters[i]; selectedCSS = args.currentView().tag.indexOf(item) !== -1 ? '.active' : ''; list.push(m('li.pointer' + selectedCSS, {onclick : filterTag.bind(null, item)}, m('span', item.label ) )); } return list; }; return m('.db-filters.m-t-lg', [ m('h5.m-t-sm', [ 'Contributors ', m('i.fa.fa-question-circle.text-muted', { 'data-toggle': 'tooltip', 'title': 'Click a contributor\'s name to see projects that you have in common.', 'data-placement' : 'bottom' }, ''), m('.pull-right', args.nameFilters.length && ctrl.nameTotalPages() > 1 ? m.component(MicroPagination, { currentPage : ctrl.nameCurrentPage, totalPages : ctrl.nameTotalPages, type: 'contributors'}) : '' ) ]), m('ul', [ args.currentView().fetcher.loaded === 0 && !args.currentView().fetcher.isEmpty() ? m('.ball-beat.text-center.m-t-md', m('')) : returnNameFilters() ]), m('h5.m-t-sm', [ 'Tags', m('.pull-right', args.tagFilters.length && ctrl.tagTotalPages() > 1 ? m.component(MicroPagination, { currentPage : ctrl.tagCurrentPage, totalPages : ctrl.tagTotalPages, type: 'tags' }) : '' ) ]), m('ul', [ args.currentView().fetcher.loaded === 0 && !args.currentView().fetcher.isEmpty() ? m('.ball-beat.text-center.m-t-md', m('')) : returnTagFilters() ]) ] ); } }; /** * Information Module. * @constructor */ var Information = { view : function (ctrl, args) { function categoryMap(category) { // TODO, you don't need to do this, CSS will do this case change switch (category) { case 'analysis': return 'Analysis'; case 'communication': return 'Communication'; case 'data': return 'Data'; case 'hypothesis': return 'Hypothesis'; case 'methods and measures': return 'Methods and Measures'; case 'procedure': return 'Procedure'; case 'project': return 'Project'; case 'software': return 'Software'; case 'other': return 'Other'; default: return 'Uncategorized'; } } var template = ''; var showRemoveFromCollection; var collectionFilter = args.currentView().collection; if (args.selected().length === 0) { template = m('.db-info-empty.text-muted.p-lg', 'Select a row to view project details.'); } if (args.selected().length === 1) { var item = args.selected()[0].data; showRemoveFromCollection = collectionFilter.data.nodeType === 'collection' && args.selected()[0].depth === 1 && args.fetchers[collectionFilter.id]._cache[item.id]; // Be able to remove top level items but not their children if(item.attributes.category === ''){ item.attributes.category = 'Uncategorized'; } template = m('.p-sm', [ showRemoveFromCollection ? m('.clearfix', m('.btn.btn-default.btn-sm.btn.p-xs.text-danger.pull-right', { onclick : function() { args.removeProjectFromCollections(); $osf.trackClick('myProjects', 'information-panel', 'remove-project-from-collection'); } }, 'Remove from collection')) : '', m('h3', m('a', { href : item.links.html, onclick: function(){ $osf.trackClick('myProjects', 'information-panel', 'navigate-to-project'); }}, item.attributes.title)), m('[role="tabpanel"]', [ m('ul.nav.nav-tabs.m-b-md[role="tablist"]', [ m('li[role="presentation"].active', m('a[href="#tab-information"][aria-controls="information"][role="tab"][data-toggle="tab"]', {onclick: function(){ $osf.trackClick('myProjects', 'information-panel', 'open-information-tab'); }}, 'Information')), m('li[role="presentation"]', m('a[href="#tab-activity"][aria-controls="activity"][role="tab"][data-toggle="tab"]', {onclick : function() { args.getCurrentLogs(); $osf.trackClick('myProjects', 'information-panel', 'open-activity-tab'); }}, 'Activity')) ]), m('.tab-content', [ m('[role="tabpanel"].tab-pane.active#tab-information',[ m('p.db-info-meta.text-muted', [ m('', 'Visibility : ' + (item.attributes.public ? 'Public' : 'Private')), m('', 'Category: ' + categoryMap(item.attributes.category)), m('', 'Last Modified on: ' + (item.date ? item.date.local : '')) ]), m('p', [ m('span', {style: 'white-space:pre-wrap'}, item.attributes.description) ]), item.attributes.tags.length > 0 ? m('p.m-t-md', [ m('h5', 'Tags'), item.attributes.tags.map(function(tag){ return m('a.tag', { href : '/search/?q=(tags:' + tag + ')', onclick: function(){ $osf.trackClick('myProjects', 'information-panel', 'navigate-to-search-by-tag'); }}, tag); }) ]) : '' ]), m('[role="tabpanel"].tab-pane#tab-activity',[ m.component(ActivityLogs, args) ]) ]) ]) ]); } if (args.selected().length > 1) { showRemoveFromCollection = collectionFilter.data.nodeType === 'collection' && args.selected()[0].depth === 1; template = m('.p-sm', [ showRemoveFromCollection ? m('.clearfix', m('.btn.btn-default.btn-sm.p-xs.text-danger.pull-right', { onclick : function() { args.removeProjectFromCollections(); $osf.trackClick('myProjects', 'information-panel', 'remove-multiple-projects-from-collections'); } }, 'Remove selected from collection')) : '', args.selected().map(function(item){ return m('.db-info-multi', [ m('h4', m('a', { href : item.data.links.html, onclick: function(){ $osf.trackClick('myProjects', 'information-panel', 'navigate-to-project-multiple-selected'); }}, item.data.attributes.title)), m('p.db-info-meta.text-muted', [ m('span', item.data.attributes.public ? 'Public' : 'Private' + ' ' + item.data.attributes.category), m('span', ', Last Modified on ' + item.data.date.local) ]) ]); }) ]); } return m('.db-information', template); } }; var ActivityLogs = { view : function (ctrl, args) { return m('.db-activity-list.m-t-md', [ args.activityLogs() ? args.activityLogs().map(function(item){ item.trackingCategory = 'myProjects'; item.trackingAction = 'information-panel'; var image = m('i.fa.fa-desktop'); if (item.embeds.user && item.embeds.user.data) { image = m('img', { src : item.embeds.user.data.links.profile_image}); } else if (item.embeds.user && item.embeds.user.errors[0].meta){ image = m('img', { src : item.embeds.user.errors[0].meta.profile_image}); } return m('.db-activity-item', [ m('', [ m('.db-log-avatar.m-r-xs', image), m.component(LogText, item)]), m('.text-right', m('span.text-muted.m-r-xs', item.attributes.formattableDate.local))]); }) : '', m('.db-activity-nav.text-center', [ args.showMoreActivityLogs() ? m('.btn.btn-sm.btn-link', { onclick: function(){ args.getLogs(args.showMoreActivityLogs(), true); $osf.trackClick('myProjects', 'information-panel', 'show-more-activity'); }}, [ 'Show more', m('i.fa.fa-caret-down.m-l-xs')]) : '' ]) ]); } }; /** * Modals views. * @constructor */ var Modals = { view : function(ctrl, args) { return m('.db-fbModals', [ m('#infoModal.modal.fade[tabindex=-1][role="dialog"][aria-hidden="true"]', m('.modal-dialog', m('.modal-content', [ m('.modal-body', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', [ m('span[aria-hidden="true"]','×') ]), m.component(Information, args) ]) ]) ) ) ]); } }; module.exports = { MyProjects : MyProjects, Collections : Collections, MicroPagination : MicroPagination, ActivityLogs : ActivityLogs, LinkObject: LinkObject, NodeFetcher: NodeFetcher, };
website/static/js/myProjects.js
/** * Builds full page project browser */ 'use strict'; var $ = require('jquery'); // jQuery var m = require('mithril'); // exposes mithril methods, useful for redraw etc. var ProjectOrganizer = require('js/project-organizer'); var $osf = require('js/osfHelpers'); var Raven = require('raven-js'); var LogText = require('js/logTextParser'); var AddProject = require('js/addProjectPlugin'); var mC = require('js/mithrilComponents'); var MOBILE_WIDTH = 767; // Mobile view break point for responsiveness var NODE_PAGE_SIZE = 10; // Load 10 nodes at a time from server /* Counter for unique ids for link objects */ if (!window.fileBrowserCounter) { window.fileBrowserCounter = 0; } //Backport of Set if (!window.Set) { window.Set = function Set(initial) { this.data = {}; initial = initial || []; for(var i = 0; i < initial.length; i++) this.add(initial[i]); }; Set.prototype = { has: function(item) { return this.data[item] === true; }, clear: function() { this.data = {}; }, add:function(item) { this.data[item] = true; }, delete: function(item) { delete this.data[item]; } }; } function NodeFetcher(type, link) { this.type = type || 'nodes'; this.loaded = 0; this.total = 0; this._flat = []; this._orphans = []; this._cache = {}; this._promise = null; this._continue = true; this.tree = { 0: { id: 0, data: {}, children: [] } }; this._callbacks = { done: [this._onFinish.bind(this)], page: [], children: [], fetch : [] }; this.nextLink = link || $osf.apiV2Url('users/me/' + this.type + '/', { query : { 'related_counts' : 'children', 'embed' : 'contributors' }}); } NodeFetcher.prototype = { isFinished: function() { return this.loaded >= this.total && this._promise === null && this._orphans.length === 0; }, isEmpty: function() { return this.loaded === 0 && this.isFinished(); }, progress: function() { return Math.ceil(this.loaded / (this.total || 1) * 100); }, start: function() { return this.resume(); }, pause: function() { this._continue = false; }, resume: function() { this._continue = true; if (!this.nextLink) return this._promise = null; if (this._promise) return this._promise; return this._promise = m.request({method: 'GET', url: this.nextLink, config: xhrconfig, background: true}) .then(function(results) {this._promise = null; return results;}.bind(this)) .then(this._success.bind(this), this._fail.bind(this)) .then((function() { m.redraw(true); if(this.nextLink && this._continue) return this.resume(); }).bind(this)); }, add: function(item) { if (!this.isFinished() && this._flat.indexOf(item) !== - 1) return; this.total++; this.loaded++; this._flat.unshift(item); }, remove: function(item) { item = item.id || item; if (!this._cache[item]) return; delete this._cache[item]; for(var i = 0; i < this._flat.length; i++) if (this._flat[i].id === item) { this._flat.splice(i, 1); break; } }, get: function(id) { if (!this._cache[id]) return this.fetch(id); var deferred = m.deferred(); deferred.resolve(this._cache[id]); return deferred.promise; }, getChildren: function(id) { //TODO Load via rootNode if (this._cache[id].relationships.children.links.related.meta.count !== this._cache[id].children.length) { return this.fetchChildren(this._cache[id]); } var deferred = m.deferred(); deferred.resolve(this._cache[id].children); return deferred.promise; }, fetch: function(id, cb) { // TODO This method is currently untested var url = $osf.apiV2Url(this.type + '/' + id + '/', {query: {related_counts: 'children', embed: 'contributors' }}); return m.request({method: 'GET', url: url, config: xhrconfig, background: true}) .then((function(result) { this.add(result.data); return result.data; }).bind(this), this._fail.bind(this)); }, fetchChildren: function(parent) { //TODO Allow suspending of children return m.request({method: 'GET', url: parent.relationships.children.links.related.href + '?embed=contributors', config: xhrconfig, background: true}) .then(this._childrenSuccess.bind(this, parent), this._fail.bind(this)); }, _success: function(results) { // Only reset if we're lower as loading children will increment this number if (this.total < results.links.meta.total) this.total = results.links.meta.total; this.nextLink = results.links.next; this.loaded += results.data.length; for(var i = 0; i < results.data.length; i++) { if (this.type === 'registrations' && (results.data[i].attributes.retracted === true || results.data[i].attributes.pending_registration_approval === true)) continue; // Exclude retracted and pending registrations else if (results.data[i].relationships.parent) this._orphans.push(results.data[i]); else this._flat.push(results.data[i]); if (this._cache[results.data[i].id]) continue; this._cache[results.data[i].id] = _formatDataforPO(results.data[i]); this._cache[results.data[i].id].children = []; this._orphans = this._orphans.filter((function(item) { var parentId = item.relationships.parent.links.related.href.split('/').splice(-2, 1)[0]; if (!this._cache[parentId]) return true; this._cache[parentId].children.push(item); return false; }).bind(this)); // if (results.data[i].relationships.children.links.related.meta.count > 0) // this.fetchChildren(results.data[i]); } this._callbacks.page.forEach((function(cb) { cb(this, results.data); }).bind(this)); if (!this.nextLink) this._callbacks.done.forEach((function(cb) { cb(this); }).bind(this)); }, _childrenSuccess: function(parent, results) { this.total += results.links.meta.total; for(var i = 0; i < results.data.length; i++) { this._cache[results.data[i].id] = results.data[i]; this._cache[parent.id].children.push(_formatDataforPO(results.data[i])); } return this._cache[parent.id].children; }, _fail: function(result) { Raven.captureMessage('Error loading nodes with nodeType ' + this.type + ' at url ' + this.nextLink, {requestReturn: result}); $osf.growl('We\'re having some trouble contacting our servers. Try reloading the page.', 'Something went wrong!', 'danger', 5000); this.resume(); }, _onFinish: function() { this._flat = this._orphans.concat(this._flat).sort(function(a,b) { a = new Date(a.attributes.date_modified); b = new Date(b.attributes.date_modified); if (a > b) return -1; if (a < b) return 1; return 0; }); this._orphans = []; }, on: function(type, func) { if (!Array.isArray(type)) type = [type]; //Valid types are children, page, done for(var i = 0; i < type.length; i++) this._callbacks[type[i]].push(func); } }; function getUID() { window.fileBrowserCounter = window.fileBrowserCounter + 1; return window.fileBrowserCounter; } /* Send with ajax calls to work with api2 */ var xhrconfig = function (xhr) { xhr.withCredentials = true; xhr.setRequestHeader('Content-Type', 'application/vnd.api+json;'); xhr.setRequestHeader('Accept', 'application/vnd.api+json; ext=bulk'); }; /* Adjust item data for treebeard to be able to filter tags and contributors not in the view */ function _formatDataforPO(item) { item.kind = 'folder'; item.uid = item.id; item.name = item.attributes.title; item.tags = item.attributes.tags.toString(); item.contributors = ''; if (item.embeds.contributors.data){ item.embeds.contributors.data.forEach(function(c){ var attr; if (c.embeds.users.data) { attr = c.embeds.users.data.attributes; } else { attr = c.embeds.users.errors[0].meta; } item.contributors += attr.full_name + ' ' + attr.middle_names + ' ' + attr.given_name + ' ' + attr.family_name + ' ' ; }); } item.date = new $osf.FormattableDate(item.attributes.date_modified); return item; } /* Small constructor for creating same type of links */ var LinkObject = function _LinkObject (type, data, label, institutionId) { if (type === undefined || data === undefined || label === undefined) { throw new Error('LinkObject expects type, data and label to be defined.'); } var self = this; self.id = getUID(); self.type = type; self.data = data; self.label = label; }; /** * Returns the object to send to the API to send a node_link to collection * @param id {String} unique id of the node like 'ez8f3' * @returns {{data: {type: string, relationships: {nodes: {data: {type: string, id: *}}}}}} */ function buildCollectionNodeData (id) { return { 'data': [{ 'type': 'linked_nodes', 'id': id }] }; } /** * Initialize File Browser. Prepares an option object within FileBrowser * @constructor */ var MyProjects = { controller : function (options) { var self = this; self.wrapperSelector = options.wrapperSelector; // For encapsulating each implementation of this component in multiple use self.projectOrganizerOptions = options.projectOrganizerOptions || {}; self.viewOnly = options.viewOnly || false; self.institutionId = options.institutionId || false; self.logUrlCache = {}; // dictionary of load urls to avoid multiple calls with little refactor self.nodeUrlCache = {}; // Cached returns of the project related urls // VIEW STATES self.showInfo = m.prop(true); // Show the info panel self.showSidebar = m.prop(false); // Show the links with collections etc. used in narrow views self.allProjectsLoaded = m.prop(false); self.categoryList = []; self.loadValue = m.prop(0); // What percentage of the project loading is done //self.loadCounter = m.prop(0); // Count how many items are received from the server self.currentView = m.prop({ collection : null, // Linkobject contributor : [], tag : [], totalRows: 0 }); self.filesData = m.prop(); // Treebeard functions looped through project organizer. // We need to pass these in to avoid reinstantiating treebeard but instead repurpose (update) the top level folder self.treeData = m.prop({}); // Top level object that houses all the rows self.buildTree = m.prop(null); // Preprocess function that adds to each item TB specific attributes self.updateFolder = m.prop(null); // Updates view to redraw without messing up scroll location self.multiselected = m.prop(); // Updated the selected list in treebeard self.highlightMultiselect = m.prop(null); // does highlighting background of the row // Add All my Projects and All my registrations to collections self.systemCollections = options.systemCollections || [ new LinkObject('collection', { nodeType : 'projects'}, 'All my projects'), new LinkObject('collection', { nodeType : 'registrations'}, 'All my registrations') ]; self.fetchers = {}; self.fetchers[self.systemCollections[0].id] = new NodeFetcher('nodes'); self.fetchers[self.systemCollections[1].id] = new NodeFetcher('registrations'); // Initial Breadcrumb for All my projects var initialBreadcrumbs = options.initialBreadcrumbs || [self.systemCollections[0]]; self.breadcrumbs = m.prop(initialBreadcrumbs); // Calculate name filters self.nameFilters = []; // Calculate tag filters self.tagFilters = []; // Load categories to pass in to create project self.loadCategories = function _loadCategories () { var promise = m.request({method : 'OPTIONS', url : $osf.apiV2Url('nodes/', { query : {}}), config : xhrconfig}); promise.then(function _success(results){ if(results.actions && results.actions.POST.category){ self.categoryList = results.actions.POST.category.choices; self.categoryList.sort(function(a, b){ // Quick alphabetical sorting if(a.value < b.value) return -1; if(a.value > b.value) return 1; return 0; }); } }, function _error(results){ var message = 'Error loading project category names.'; Raven.captureMessage(message, {requestReturn: results}); }); return promise; }; // Activity Logs self.activityLogs = m.prop(); self.logRequestPending = false; self.showMoreActivityLogs = m.prop(null); self.getLogs = function _getLogs (url, addToExistingList) { var cachedResults; if(!addToExistingList){ self.activityLogs([]); // Empty logs from other projects while load is happening; self.showMoreActivityLogs(null); } function _processResults (result){ self.logUrlCache[url] = result; result.data.map(function(log){ log.attributes.formattableDate = new $osf.FormattableDate(log.attributes.date); if(addToExistingList){ self.activityLogs().push(log); } }); if(!addToExistingList){ self.activityLogs(result.data); // Set activity log data } self.showMoreActivityLogs(result.links.next); // Set view for show more button } if(self.logUrlCache[url]){ cachedResults = self.logUrlCache[url]; _processResults(cachedResults); } else { self.logRequestPending = true; var promise = m.request({method : 'GET', url : url, config : xhrconfig}); promise.then(_processResults); promise.then(function(){ self.logRequestPending = false; }); return promise; } }; // separate concerns, wrap getlogs here to get logs for the selected item self.getCurrentLogs = function _getCurrentLogs ( ){ if(self.selected().length === 1 && !self.logRequestPending){ var item = self.selected()[0]; var id = item.data.id; if(!item.data.attributes.retracted){ var urlPrefix = item.data.attributes.registration ? 'registrations' : 'nodes'; var url = $osf.apiV2Url(urlPrefix + '/' + id + '/logs/', { query : { 'page[size]' : 6, 'embed' : ['nodes', 'user', 'linked_node', 'template_node', 'contributors']}}); var promise = self.getLogs(url); return promise; } } }; /* filesData is the link that loads tree data. This function refreshes that information. */ self.updateFilesData = function _updateFilesData(linkObject) { if ((linkObject.type === 'node') && self.viewOnly){ return; } self.updateTbMultiselect([]); // clear multiselected, updateTreeData will repick self.updateFilter(linkObject); // Update what filters currently selected self.updateBreadcrumbs(linkObject); // Change breadcrumbs self.updateList(); // Reset and load item self.showSidebar(false); }; // INFORMATION PANEL /* Defines the current selected item so appropriate information can be shown */ self.selected = m.prop([]); self.updateSelected = function _updateSelected (selectedList){ self.selected(selectedList); self.getCurrentLogs(); }; /** * Update the currentView * @param filter */ self.updateFilter = function _updateFilter(filter) { // if collection, reset currentView otherwise toggle the item in the list of currentview items if (['node', 'collection'].indexOf(filter.type) === -1 ) { var filterIndex = self.currentView()[filter.type].indexOf(filter); if(filterIndex !== -1) self.currentView()[filter.type].splice(filterIndex,1); else self.currentView()[filter.type].push(filter); return; } if (self.currentView().fetcher) self.currentView().fetcher.pause(); self.currentView().tag = []; self.currentView().contributor = []; self.currentView().fetcher = self.fetchers[filter.id]; self.currentView().fetcher.resume(); self.loadValue(self.currentView().fetcher.isFinished() ? 100 : self.currentView().fetcher.progress()); self.generateFiltersList(); if (filter.type === 'collection') self.currentView().collection = filter; }; self.removeProjectFromCollections = function _removeProjectFromCollection () { // Removes selected items from collect var currentCollection = self.currentView().collection; var collectionNode = currentCollection.data.node; // If it's not a system collection like projects or registrations this will have a node var data = { data: self.selected().map(function(item){ return {id: item.data.id, type: 'linked_nodes'}; }) }; m.request({ method : 'DELETE', url : collectionNode.links.self + 'relationships/' + 'linked_nodes/', //collection.links.self + 'node_links/' + item.data.id + '/', //collection.links.self + relationship/ + linked_nodes/ config : xhrconfig, data : data }).then(function(result) { data.data.forEach(function(item) { self.fetchers[currentCollection.id].remove(item.id); currentCollection.data.count(currentCollection.data.count()-1); }); self.updateList(); }, function _removeProjectFromCollectionsFail(result){ var message = 'Some projects'; if(data.data.length === 1) { message = self.selected()[0].data.name; } else { message += ' could not be removed from the collection'; } $osf.growl(message, 'Please try again.', 'danger', 5000); }); }; // remove this contributor from list of contributors self.unselectContributor = function (id){ self.currentView().contributor.forEach(function (c, index, arr) { if(c.data.id === id){ arr.splice(index, 1); self.updateList(); } }); }; self.unselectTag = function (tag){ self.currentView().tag.forEach(function (c, index, arr) { if(c.data.tag === tag){ arr.splice(index, 1); self.updateList(); } }); }; // Update what is viewed self.updateList = function _updateList (){ if (!self.buildTree()) return; // Treebeard hasn't loaded yet var viewData = self.filteredData(); self.updateTreeData(0, viewData, true); self.currentView().totalRows = viewData.length; }; self.filteredData = function() { var tags = self.currentView().tag; var contributors = self.currentView().contributor; return self.currentView().fetcher._flat.filter(function(node) { var tagMatch = tags.length === 0; var contribMatch = contributors.length === 0; for (var i = 0; i < contributors.length; i++) if (node.contributorSet.has(contributors[i].data.id)) { contribMatch = true; break; } for (var j = 0; j < tags.length; j++) if (node.tagSet.has(tags[j].label)) { tagMatch = true; break; } return tagMatch && contribMatch; }); }; self.updateTbMultiselect = function (itemsArray) { self.multiselected()(itemsArray); self.highlightMultiselect()(); self.updateSelected(itemsArray); }; self.updateTreeData = function (begin, data, clear) { var item; if (clear) { self.treeData().children = []; } for (var i = begin; i < data.length; i++){ item = data[i]; _formatDataforPO(item); var child = self.buildTree()(item, self.treeData()); self.treeData().add(child); } self.updateFolder()(null, self.treeData()); // Manually select first item without triggering a click if(self.multiselected()().length === 0 && self.treeData().children[0]){ self.updateTbMultiselect([self.treeData().children[0]]); } m.redraw(true); }; self.generateSets = function (item){ item.tagSet = new Set(item.attributes.tags || []); var contributors = item.embeds.contributors.data || []; item.contributorSet= new Set(contributors.map(function(contrib) { return contrib.id; })); }; self.nonLoadTemplate = function (){ var template = ''; if(!self.currentView().fetcher.isEmpty()) { return; } var lastcrumb = self.breadcrumbs()[self.breadcrumbs().length-1]; var hasFilters = self.currentView().contributor.length || self.currentView().tag.length; if(hasFilters){ template = m('.db-non-load-template.m-md.p-md.osf-box', 'No projects match this filter.'); } else { if(lastcrumb.type === 'collection'){ if(lastcrumb.data.nodeType === 'projects'){ template = m('.db-non-load-template.m-md.p-md.osf-box', 'You have not created any projects yet.'); } else if (lastcrumb.data.nodeType === 'registrations'){ template = m('.db-non-load-template.m-md.p-md.osf-box', 'You have not made any registrations yet.'); } else { template = m('.db-non-load-template.m-md.p-md.osf-box', 'This collection is empty. To add projects or registrations, click "All my projects" or "All my registrations" in the sidebar, and then drag and drop items into the collection link.'); } } else { if(!self.currentView().fetcher.isEmpty()){ template = m('.db-non-load-template.m-md.p-md.osf-box.text-center', m('.ball-scale.text-center', m('')) ); } else { template = m('.db-non-load-template.m-md.p-md.osf-box.text-center', [ 'No components to display. Either there are no components, or there are private components in which you are not a contributor.' ]); } } } return template; }; /** * Generate this list from user's projects */ self.generateFiltersList = function(noClear) { self.users = {}; self.tags = {}; Object.keys(self.currentView().fetcher._cache).forEach(function(key) { var item = self.currentView().fetcher._cache[key]; self.generateSets(item); var contributors = item.embeds.contributors.data || []; for(var i = 0; i < contributors.length; i++) { var u = contributors[i]; if (u.id === window.contextVars.currentUser.id) { continue; } if(self.users[u.id] === undefined) { self.users[u.id] = { data : u, count: 1 }; } else { self.users[u.id].count++; } } var tags = item.attributes.tags || []; for(var j = 0; j < tags.length; j++) { var t = tags[j]; if(self.tags[t] === undefined) { self.tags[t] = 1; } else { self.tags[t]++; } } }); // Sorting by number of items utility function function sortByCountDesc (a,b){ var aValue = a.data.count; var bValue = b.data.count; if (bValue > aValue) { return 1; } if (bValue < aValue) { return -1; } return 0; } // Add to lists with numbers if (!noClear) self.nameFilters = []; for (var user in self.users) { var u2 = self.users[user]; if (u2.data.embeds.users.data) { var found = self.nameFilters.find(function(lo) { return lo.label === u2.data.embeds.users.data.attributes.full_name; }); if (!found) self.nameFilters.push(new LinkObject('contributor', { id : u2.data.id, count : u2.count, query : { 'related_counts' : 'children' }}, u2.data.embeds.users.data.attributes.full_name, options.institutionId || false)); else found.data.count = u2.count; } } // order names self.nameFilters.sort(sortByCountDesc); if (!noClear) self.tagFilters = []; for (var tag in self.tags){ var t2 = self.tags[tag]; var found = self.tagFilters.find(function(lo) { return lo.label === tag; }); if (!found) self.tagFilters.push(new LinkObject('tag', { tag : tag, count : t2, query : { 'related_counts' : 'children' }}, tag, options.institutionId || false)); else found.data.count = t2; } // order tags self.tagFilters.sort(sortByCountDesc); m.redraw(true); }; // BREADCRUMBS self.updateBreadcrumbs = function _updateBreadcrumbs (linkObject){ if (linkObject.type === 'collection'){ self.breadcrumbs([linkObject]); return; } if (linkObject.type === 'contributor' || linkObject.type === 'tag'){ return; } if (linkObject.placement === 'breadcrumb'){ self.breadcrumbs().splice(linkObject.index+1, self.breadcrumbs().length-linkObject.index-1); return; } if(linkObject.ancestors && linkObject.ancestors.length > 0){ linkObject.ancestors.forEach(function(item){ var ancestorLink = new LinkObject('node', item.data, item.data.name); self.fetchers[ancestorLink.id] = new NodeFetcher(item.data.types, item.data.relationships.children.links.related.href + '?embed=contributors'); self.fetchers[ancestorLink.id].on(['page', 'done'], self.onPageLoad); self.breadcrumbs().push(ancestorLink); }); } self.breadcrumbs().push(linkObject); }; // GET COLLECTIONS // Default system collections self.collections = m.prop([].concat(self.systemCollections)); self.collectionsPageSize = m.prop(5); // Load collection list self.loadCollections = function _loadCollections (url){ var promise = m.request({method : 'GET', url : url, config : xhrconfig}); promise.then(function(result){ result.data.forEach(function(node){ var count = node.relationships.linked_nodes.links.related.meta.count; self.collections().push(new LinkObject('collection', { path : 'collections/' + node.id + '/linked_nodes/', query : { 'related_counts' : 'children', 'embed' : 'contributors' }, nodeType : 'collection', node : node, count : m.prop(count), loaded: 1 }, node.attributes.title)); var link = $osf.apiV2Url('collections/' + node.id + '/linked_nodes/', { query : { 'related_counts' : 'children', 'embed' : 'contributors' }}); self.fetchers[self.collections()[self.collections().length-1].id] = new NodeFetcher('nodes', link); self.fetchers[self.collections()[self.collections().length-1].id].on(['page', 'done'], self.onPageLoad); }); if(result.links.next){ self.loadCollections(result.links.next); } }, function(){ var message = 'Collections could not be loaded.'; $osf.growl(message, 'Please reload the page.'); Raven.captureMessage(message, { url: url }); }); return promise; }; self.sidebarInit = function _sidebarInit (element, isInit) { $('[data-toggle="tooltip"]').tooltip(); }; // Resets UI to show All my projects and update states self.resetUi = function _resetUi(){ var linkObject = self.systemCollections[0]; self.updateBreadcrumbs(linkObject); self.updateFilter(linkObject); }; self.onPageLoad = function(fetcher, pageData) { if(self.currentView().fetcher === fetcher) { self.loadValue(fetcher.isFinished() ? 100 : fetcher.progress()); self.generateFiltersList(true); if (!pageData) { for(var i = 0; i < fetcher._flat.length; i++){ var fetcherItem = fetcher._flat[i]; var tbItem = self.treeData().children[i] ? self.treeData().children[i].data : {}; if(fetcherItem === tbItem){ continue; } var itemToAdd = self.buildTree()(fetcherItem, self.treeData()); itemToAdd.parentID = self.treeData().id; itemToAdd.open = false; itemToAdd.load = false; self.treeData().children.splice(i, 0, itemToAdd); } self.updateFolder()(null, self.treeData(), true); return m.redraw(); } if(self.treeData().children){ var begin = self.treeData().children.length; var data = self.filteredData(); self.updateTreeData(begin, data); self.currentView().totalRows = fetcher._flat.length; } } }; self.init = function _init_fileBrowser() { self.loadCategories().then(function(){ self.fetchers[self.systemCollections[0].id].on(['page', 'done'], self.onPageLoad); self.fetchers[self.systemCollections[1].id].on(['page', 'done'], self.onPageLoad); }); if (!self.viewOnly){ var collectionsUrl = $osf.apiV2Url('collections/', { query : {'related_counts' : 'linked_nodes', 'page[size]' : self.collectionsPageSize(), 'sort' : 'date_created', 'embed' : 'node_links'}}); self.loadCollections(collectionsUrl); } // Add linkObject to the currentView self.updateFilter(self.collections()[0]); }; self.init(); }, view : function (ctrl, args) { var mobile = window.innerWidth < MOBILE_WIDTH; // true if mobile view var infoPanel = ''; var poStyle = 'width : 72%'; // Other percentages are set in CSS in file-browser.css These are here because they change var sidebarButtonClass = 'btn-default'; if (ctrl.showInfo() && !mobile){ infoPanel = m('.db-infobar', m.component(Information, ctrl)); poStyle = 'width : 47%; display: block'; } if(ctrl.showSidebar()){ sidebarButtonClass = 'btn-primary'; } if (mobile) { poStyle = 'width : 100%; display: block'; if(ctrl.showSidebar()){ poStyle = 'display: none'; } } else { ctrl.showSidebar(true); } var projectOrganizerOptions = $.extend( {}, { filesData : [], onPageLoad: ctrl.onPageLoad, updateSelected : ctrl.updateSelected, updateFilesData : ctrl.updateFilesData, LinkObject : LinkObject, NodeFetcher : NodeFetcher, formatDataforPO : _formatDataforPO, wrapperSelector : args.wrapperSelector, resetUi : ctrl.resetUi, showSidebar : ctrl.showSidebar, loadValue : ctrl.loadValue, loadCounter : ctrl.loadCounter, treeData : ctrl.treeData, buildTree : ctrl.buildTree, updateFolder : ctrl.updateFolder, currentView: ctrl.currentView, fetchers : ctrl.fetchers, indexes : ctrl.indexes, multiselected : ctrl.multiselected, highlightMultiselect : ctrl.highlightMultiselect }, ctrl.projectOrganizerOptions ); return [ !ctrl.institutionId ? m('.dashboard-header', m('.row', [ m('.col-xs-8', m('h3', [ 'My Projects ', m('small.hidden-xs', 'Browse and organize all your projects') ])), m('.col-xs-4.p-sm', m('.pull-right', m.component(AddProject, { buttonTemplate: m('.btn.btn-success.btn-success-high-contrast.f-w-xl[data-toggle="modal"][data-target="#addProject"]', {onclick: function() { $osf.trackClick('myProjects', 'add-project', 'open-add-project-modal'); }}, 'Create Project'), parentID: null, modalID: 'addProject', title: 'Create new project', categoryList: ctrl.categoryList, stayCallback: function () { // Fetch details of added item from server and redraw treebeard var projects = ctrl.fetchers[ctrl.systemCollections[0].id]; projects.fetch(this.saveResult().data.id).then(function(){ ctrl.updateTreeData(0, projects._flat, true); }); }, trackingCategory: 'myProjects', trackingAction: 'add-project', templatesFetcher: ctrl.fetchers[ctrl.systemCollections[0].id] }))) ])) : '', m('.db-header.row', [ m('.col-xs-12.col-sm-8.col-lg-9', m.component(Breadcrumbs,ctrl)), m('.db-buttonRow.col-xs-12.col-sm-4.col-lg-3', [ mobile ? m('button.btn.btn-sm.m-r-sm', { 'class' : sidebarButtonClass, onclick : function () { ctrl.showSidebar(!ctrl.showSidebar()); $osf.trackClick('myProjects', 'mobile', 'click-bars-to-toggle-collections-or-projects'); } }, m('.fa.fa-bars')) : '', m('.db-poFilter.m-r-xs') ]) ]), ctrl.showSidebar() ? m('.db-sidebar', { config : ctrl.sidebarInit}, [ mobile ? [ m('.db-dismiss', m('button.close[aria-label="Close"]', { onclick : function () { ctrl.showSidebar(false); $osf.trackClick('myProjects', 'mobile', 'close-toggle-instructions'); } }, [ m('span[aria-hidden="true"]','×') ])), m('p.p-sm.text-center.text-muted', [ 'Select a list below to see the projects. or click ', m('i.fa.fa-bars'), ' button above to toggle.' ]) ] : '', m.component(Collections, ctrl), m.component(Filters, ctrl) ]) : '', m('.db-main', { style : poStyle },[ ctrl.loadValue() < 100 ? m('.line-loader', [ m('.line-empty'), m('.line-full.bg-color-blue', { style : 'width: ' + ctrl.loadValue() +'%'}), m('.load-message', 'Fetching more projects') ]) : '', ctrl.nonLoadTemplate(), m('.db-poOrganizer', { style : ctrl.currentView().fetcher.isEmpty() ? 'display: none' : 'display: block' }, m.component( ProjectOrganizer, projectOrganizerOptions)) ] ), mobile ? '' : m('.db-info-toggle',{ onclick : function _showInfoOnclick(){ ctrl.showInfo(!ctrl.showInfo()); $osf.trackClick('myProjects', 'information-panel', 'show-hide-information-panel'); } }, ctrl.showInfo() ? m('i.fa.fa-chevron-right') : m('i.fa.fa-chevron-left') ), infoPanel, m.component(Modals, ctrl) ]; } }; /** * Collections Module. * @constructor */ var Collections = { controller : function(args){ var self = this; self.collections = args.collections; self.pageSize = args.collectionsPageSize; self.newCollectionName = m.prop(''); self.newCollectionRename = m.prop(''); self.dismissModal = function () { $('.modal').modal('hide'); }; self.currentPage = m.prop(1); self.totalPages = m.prop(1); self.calculateTotalPages = function _calculateTotalPages(result){ if(result){ // If this calculation comes after GET call to collections self.totalPages(Math.ceil((result.links.meta.total + args.systemCollections.length)/self.pageSize())); } else { self.totalPages(Math.ceil((self.collections().length)/self.pageSize())); } }; self.pageSize = m.prop(5); self.isValid = m.prop(false); self.validationError = m.prop(''); self.showCollectionMenu = m.prop(false); // Show hide ellipsis menu for collections self.collectionMenuObject = m.prop({item : {label:null}, x : 0, y : 0}); // Collection object to complete actions on menu self.resetCollectionMenu = function () { self.collectionMenuObject({item : {label:null}, x : 0, y : 0}); }; self.updateCollectionMenu = function _updateCollectionMenu (item, event) { var offset = $(event.target).offset(); var x = offset.left; var y = offset.top; if (event.view.innerWidth < MOBILE_WIDTH){ x = x-105; // width of this menu plus padding y = y-270; // fixed height from collections parent to top with adjustments for this menu div } self.showCollectionMenu(true); item.renamedLabel = item.label; self.collectionMenuObject({ item : item, x : x, y : y }); }; self.init = function _collectionsInit (element, isInit) { self.calculateTotalPages(); $(window).click(function(event){ var target = $(event.target); if(!target.hasClass('collectionMenu') && !target.hasClass('fa-ellipsis-v') && target.parents('.collection').length === 0) { self.showCollectionMenu(false); m.redraw(); // we have to force redraw here } }); }; self.addCollection = function _addCollection () { var url = $osf.apiV2Url('collections/', {}); var data = { 'data': { 'type': 'collections', 'attributes': { 'title': self.newCollectionName(), } } }; var promise = m.request({method : 'POST', url : url, config : xhrconfig, data : data}); promise.then(function(result){ var node = result.data; var count = node.relationships.linked_nodes.links.related.meta.count || 0; self.collections().push(new LinkObject('collection', { path : 'collections/' + node.id + '/linked_nodes/', query : { 'related_counts' : 'children' }, node : node, count : m.prop(count), nodeType : 'collection' }, node.attributes.title)); var link = $osf.apiV2Url('collections/' + node.id + '/linked_nodes/', { query : { 'related_counts' : 'children', 'embed' : 'contributors' }}); args.fetchers[self.collections()[self.collections().length-1].id] = new NodeFetcher('nodes', link); args.fetchers[self.collections()[self.collections().length-1].id].on(['page', 'done'], args.onPageLoad); self.newCollectionName(''); self.calculateTotalPages(); self.currentPage(self.totalPages()); // Go to last page args.sidebarInit(); }, function(){ var name = self.newCollectionName(); var message = '"' + name + '" collection could not be created.'; $osf.growl(message, 'Please try again', 'danger', 5000); Raven.captureMessage(message, { url: url, data : data }); self.newCollectionName(''); }); self.dismissModal(); return promise; }; self.deleteCollection = function _deleteCollection(){ var url = self.collectionMenuObject().item.data.node.links.self; var promise = m.request({method : 'DELETE', url : url, config : xhrconfig}); promise.then(function(result){ for ( var i = 0; i < self.collections().length; i++) { var item = self.collections()[i]; if (item.data.node && item.data.node.id === self.collectionMenuObject().item.data.node.id) { if (args.currentView().fetcher === args.fetchers[item.id]) args.updateFilesData(self.collections()[0]); // Reset to all my projects delete args.fetchers[item.id]; self.collections().splice(i, 1); break; } } self.calculateTotalPages(); }, function(){ var name = self.collectionMenuObject().item.label; var message = '"' + name + '" could not be deleted.'; $osf.growl(message, 'Please try again', 'danger', 5000); Raven.captureMessage(message, {collectionObject: self.collectionMenuObject() }); }); self.dismissModal(); return promise; }; self.renameCollection = function _renameCollection() { var url = self.collectionMenuObject().item.data.node.links.self; var nodeId = self.collectionMenuObject().item.data.node.id; var title = self.collectionMenuObject().item.renamedLabel; var data = { 'data': { 'type': 'collections', 'id': nodeId, 'attributes': { 'title': title } } }; var promise = m.request({method : 'PATCH', url : url, config : xhrconfig, data : data}); promise.then(function(result){ self.collectionMenuObject().item.label = title; }, function(){ var name = self.collectionMenuObject().item.label; var message = '"' + name + '" could not be renamed.'; $osf.growl(message, 'Please try again', 'danger', 5000); Raven.captureMessage(message, {collectionObject: self.collectionMenuObject() }); }); self.dismissModal(); self.isValid(false); return promise; }; self.applyDroppable = function _applyDroppable ( ){ $('.db-collections ul>li.acceptDrop').droppable({ hoverClass: 'bg-color-hover', drop: function( event, ui ) { var dataArray = []; var collection = self.collections()[$(this).attr('data-index')]; var collectionLink = $osf.apiV2Url(collection.data.path, { query : collection.data.query}); // If multiple items are dragged they have to be selected to make it work if (args.selected().length > 1) { dataArray = args.selected().map(function(item){ $osf.trackClick('myProjects', 'projectOrganizer', 'multiple-projects-dragged-to-collection'); return buildCollectionNodeData(item.data.id); }); } else { // if single items are passed use the event information dataArray.push(buildCollectionNodeData(ui.draggable.find('.title-text>a').attr('data-nodeID'))); // data-nodeID attribute needs to be set in project organizer building title column var projectName = ui.draggable.find('.title-text>a').attr('data-nodeTitle'); $osf.trackClick('myProjects', 'projectOrganizer', 'single-project-dragged-to-collection'); } function save(index, data) { if (!data[index]) return args.currentView().fetcher === args.fetchers[collection.id] ? args.updateList() : null; m.request({ method : 'POST', url : collection.data.node.links.self + 'relationships/linked_nodes/', config : xhrconfig, data : data[index] }).then(function(result){ if (result){ return args.currentView().fetcher .get(result.data[(result.data).length - 1].id) .then(function(item) { args.fetchers[collection.id].add(item); collection.data.count(collection.data.count() + 1); save(index + 1, data); }); } else { var name = projectName ? projectName : args.selected()[index] ? args.selected()[index].data.name : 'Item '; var message = '"' + name + '" is already in "' + collection.label + '"' ; $osf.growl(message,null, 'warning', 4000); save(index + 1, data); } }); } save(0, dataArray); } }); }; self.validateName = function _validateName (val){ if (val === 'Bookmarks') { self.isValid(false); self.validationError('"Bookmarks" is a reserved collection name. Please use another name.'); } else { self.validationError(''); self.isValid(val.length); } }; self.init(); }, view : function (ctrl, args) { var selectedCSS; var submenuTemplate; var viewOnly = args.viewOnly; ctrl.calculateTotalPages(); var collectionOnclick = function (item){ args.updateFilesData(item); $osf.trackClick('myProjects', 'projectOrganizer', 'open-collection'); }; var collectionList = function () { var item; var index; var list = []; var childCount; var dropAcceptClass; if(ctrl.currentPage() > ctrl.totalPages()){ ctrl.currentPage(ctrl.totalPages()); } var begin = ((ctrl.currentPage()-1)*ctrl.pageSize()); // remember indexes start from 0 var end = ((ctrl.currentPage()) *ctrl.pageSize()); // 1 more than the last item if (ctrl.collections().length < end) { end = ctrl.collections().length; } var openCollectionMenu = function _openCollectionMenu(e) { var index = $(this).attr('data-index'); var selectedItem = ctrl.collections()[index]; ctrl.updateCollectionMenu(selectedItem, e); $osf.trackClick('myProjects', 'edit-collection', 'open-edit-collection-menu'); }; for (var i = begin; i < end; i++) { item = ctrl.collections()[i]; index = i; dropAcceptClass = index > 1 ? 'acceptDrop' : ''; childCount = item.data.count ? ' (' + item.data.count() + ')' : ''; if (args.currentView().collection === item) { selectedCSS = 'active'; } else { selectedCSS = ''; } if (item.data.nodeType === 'collection' && !item.data.node.attributes.bookmarks) { submenuTemplate = m('i.fa.fa-ellipsis-v.pull-right.text-muted.p-xs.pointer', { 'data-index' : i, onclick : openCollectionMenu }); } else { submenuTemplate = ''; } list.push(m('li.pointer', { className : selectedCSS + ' ' + dropAcceptClass, 'data-index' : index, onclick : collectionOnclick.bind(null, item) },[ m('span', item.label + childCount), submenuTemplate ] )); } return list; }; var collectionListTemplate = [ m('h5.clearfix', [ 'Collections ', m('i.fa.fa-question-circle.text-muted', { 'data-toggle': 'tooltip', 'title': 'Collections are groups of projects. You can create custom collections. Drag and drop your projects or bookmarked projects to add them.', 'data-placement' : 'bottom' }, ''), !viewOnly ? m('button.btn.btn-xs.btn-default[data-toggle="modal"][data-target="#addColl"].m-h-xs', {onclick: function() { $osf.trackClick('myProjects', 'add-collection', 'open-add-collection-modal'); }}, m('i.fa.fa-plus')) : '', m('.pull-right', ctrl.totalPages() > 1 ? m.component(MicroPagination, { currentPage : ctrl.currentPage, totalPages : ctrl.totalPages, type: 'collections' }) : '' ) ]), m('ul', { config: ctrl.applyDroppable },[ collectionList(), ctrl.showCollectionMenu() ? m('.collectionMenu',{ style : 'position:absolute;top: ' + ctrl.collectionMenuObject().y + 'px;left: ' + ctrl.collectionMenuObject().x + 'px;' }, [ m('.menuClose', { onclick : function (e) { ctrl.showCollectionMenu(false); ctrl.resetCollectionMenu(); $osf.trackClick('myProjects', 'edit-collection', 'click-close-edit-collection-menu'); } }, m('.text-muted','×')), m('ul', [ m('li[data-toggle="modal"][data-target="#renameColl"].pointer',{ onclick : function (e) { ctrl.showCollectionMenu(false); $osf.trackClick('myProjects', 'edit-collection', 'open-rename-collection-modal'); } }, [ m('i.fa.fa-pencil'), ' Rename' ]), m('li[data-toggle="modal"][data-target="#removeColl"].pointer',{ onclick : function (e) { ctrl.showCollectionMenu(false); $osf.trackClick('myProjects', 'edit-collection', 'open-delete-collection-modal'); } }, [ m('i.fa.fa-trash'), ' Delete' ]) ]) ]) : '' ]) ]; return m('.db-collections', [ collectionListTemplate, m('.db-collections-modals', [ m.component(mC.modal, { id: 'addColl', header : m('.modal-header', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', {onclick: function() { $osf.trackClick('myProjects', 'add-collection', 'click-close-add-collection-modal'); }}, [ m('span[aria-hidden="true"]','×') ]), m('h3.modal-title', 'Add new collection') ]), body : m('.modal-body', [ m('p', 'Collections are groups of projects that help you organize your work. After you create your collection, you can add projects by dragging them into the collection.'), m('.form-group', [ m('label[for="addCollInput].f-w-lg.text-bigger', 'Collection name'), m('input[type="text"].form-control#addCollInput', { onkeyup: function (ev){ var val = $(this).val(); ctrl.validateName(val); if(ctrl.isValid()){ if(ev.which === 13){ ctrl.addCollection(); } } ctrl.newCollectionName(val); }, onchange: function() { $osf.trackClick('myProjects', 'add-collection', 'type-collection-name'); }, placeholder : 'e.g. My Replications', value : ctrl.newCollectionName() }), m('span.help-block', ctrl.validationError()) ]) ]), footer: m('.modal-footer', [ m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : function(){ ctrl.dismissModal(); ctrl.newCollectionName(''); ctrl.isValid(false); $osf.trackClick('myProjects', 'add-collection', 'click-cancel-button'); } }, 'Cancel'), ctrl.isValid() ? m('button[type="button"].btn.btn-success', { onclick : function() { ctrl.addCollection(); $osf.trackClick('myProjects', 'add-collection', 'click-add-button'); }},'Add') : m('button[type="button"].btn.btn-success[disabled]', 'Add') ]) }), m.component(mC.modal, { id : 'renameColl', header: m('.modal-header', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', {onclick: function() { $osf.trackClick('myProjects', 'edit-collection', 'click-close-rename-modal'); }}, [ m('span[aria-hidden="true"]','×') ]), m('h3.modal-title', 'Rename collection') ]), body: m('.modal-body', [ m('.form-inline', [ m('.form-group', [ m('label[for="addCollInput]', 'Rename to: '), m('input[type="text"].form-control.m-l-sm',{ onkeyup: function(ev){ var val = $(this).val(); ctrl.validateName(val); if(ctrl.isValid()) { if (ev.which === 13) { // if enter is pressed ctrl.renameCollection(); } } ctrl.collectionMenuObject().item.renamedLabel = val; }, onchange: function() { $osf.trackClick('myProjects', 'edit-collection', 'type-rename-collection'); }, value: ctrl.collectionMenuObject().item.renamedLabel}), m('span.help-block', ctrl.validationError()) ]) ]) ]), footer : m('.modal-footer', [ m('button[type="button"].btn.btn-default[data-dismiss="modal"]', { onclick : function(){ ctrl.isValid(false); $osf.trackClick('myProjects', 'edit-collection', 'click-cancel-rename-button'); } },'Cancel'), ctrl.isValid() ? m('button[type="button"].btn.btn-success', { onclick : function() { ctrl.renameCollection(); $osf.trackClick('myProjects', 'edit-collection', 'click-rename-button'); }},'Rename') : m('button[type="button"].btn.btn-success[disabled]', 'Rename') ]) }), m.component(mC.modal, { id: 'removeColl', header: m('.modal-header', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', {onclick: function() { $osf.trackClick('myProjects', 'edit-collection', 'click-close-delete-collection'); }}, [ m('span[aria-hidden="true"]','×') ]), m('h3.modal-title', 'Delete collection "' + ctrl.collectionMenuObject().item.label + '"?') ]), body: m('.modal-body', [ m('p', 'This will delete your collection, but your projects will not be deleted.') ]), footer : m('.modal-footer', [ m('button[type="button"].btn.btn-default[data-dismiss="modal"]', {onclick: function() { $osf.trackClick('myProjects', 'edit-collection', 'click-cancel-delete-collection'); }}, 'Cancel'), m('button[type="button"].btn.btn-danger', { onclick : function() { ctrl.deleteCollection(); $osf.trackClick('myProjects', 'edit-collection', 'click-delete-collection-button'); }},'Delete') ]) }) ]) ]); } }; /** * Small view component for compact pagination * Requires currentPage and totalPages to be m.prop * @type {{view: MicroPagination.view}} */ var MicroPagination = { view : function(ctrl, args) { if (args.currentPage() > args.totalPages()) { args.currentPage(args.totalPages()); } return m('span.osf-micro-pagination.m-l-xs', [ args.currentPage() > 1 ? m('span.m-r-xs.arrow.left.live', { onclick : function(){ args.currentPage(args.currentPage() - 1); $osf.trackClick('myProjects', 'paginate', 'get-prev-page-' + args.type); }}, m('i.fa.fa-angle-left')) : m('span.m-r-xs.arrow.left', m('i.fa.fa-angle-left')), m('span', args.currentPage() + '/' + args.totalPages()), args.currentPage() < args.totalPages() ? m('span.m-l-xs.arrow.right.live', { onclick : function(){ args.currentPage(args.currentPage() + 1); $osf.trackClick('myProjects', 'paginate', 'get-next-page-' + args.type); }}, m('i.fa.fa-angle-right')) : m('span.m-l-xs.arrow.right', m('i.fa.fa-angle-right')) ]); } }; /** * Breadcrumbs Module * @constructor */ var Breadcrumbs = { view : function (ctrl, args) { var viewOnly = args.viewOnly; var mobile = window.innerWidth < MOBILE_WIDTH; // true if mobile view var updateFilesOnClick = function (item) { if (item.type === 'node') args.updateFilesData(item, item.data.id); else args.updateFilesData(item); $osf.trackClick('myProjects', 'projectOrganizer', 'click-on-breadcrumbs'); }; var contributorsTemplate = []; var tagsTemplate = []; if(args.currentView().contributor.length) { contributorsTemplate.push(m('span.text-muted', 'with ')); args.currentView().contributor.forEach(function (c) { contributorsTemplate.push(m('span.filter-breadcrumb.myprojects', [ c.label, ' ', m('button', { onclick: function(){ args.unselectContributor(c.data.id); }}, m('span', '×')) ])); }); } if(args.currentView().tag.length){ tagsTemplate.push(m('span.text-muted.m-l-sm', 'tagged ')); args.currentView().tag.forEach(function(t){ tagsTemplate.push(m('span.filter-breadcrumb.myprojects', [ t.label, ' ', m('button', { onclick: function(){ args.unselectTag(t.data.tag); }}, m('span', '×')) ])); }); } var items = args.breadcrumbs(); if (mobile && items.length > 1) { return m('.db-breadcrumbs', [ m('ul', [ m('li', [ m('.btn.btn-link[data-toggle="modal"][data-target="#parentsModal"]', '...'), m('i.fa.fa-angle-right') ]), m('li', m('span.btn', items[items.length-1].label)) ]), m('#parentsModal.modal.fade[tabindex=-1][role="dialog"][aria-hidden="true"]', m('.modal-dialog', m('.modal-content', [ m('.modal-body', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', [ m('span[aria-hidden="true"]','×') ]), m('h4', 'Parent projects'), args.breadcrumbs().map(function(item, index, array){ if(index === array.length-1){ return m('.db-parent-row.btn', { style : 'margin-left:' + (index*20) + 'px;' }, [ m('i.fa.fa-angle-right.m-r-xs'), item.label ]); } item.index = index; // Add index to update breadcrumbs item.placement = 'breadcrumb'; // differentiate location for proper breadcrumb actions return m('.db-parent-row',[ m('span.btn.btn-link', { style : 'margin-left:' + (index*20) + 'px;', onclick : function() { args.updateFilesData(item); $('.modal').modal('hide'); } }, [ m('i.fa.fa-angle-right.m-r-xs'), item.label ]), contributorsTemplate, tagsTemplate ] ); }) ]) ]) ) ) ]); } return m('.db-breadcrumbs', m('ul', [ items.map(function(item, index, arr){ if(index === arr.length-1){ if(item.type === 'node'){ var linkObject = args.breadcrumbs()[args.breadcrumbs().length - 1]; var parentID = linkObject.data.id; var showAddProject = true; var addProjectTemplate = ''; var permissions = item.data.attributes.current_user_permissions; showAddProject = permissions.indexOf('admin') > -1 || permissions.indexOf('write') > -1; if (item.type === 'registration' || item.data.type === 'registrations' || item.data.nodeType === 'registrations'){ showAddProject = false; } if(showAddProject && !viewOnly){ addProjectTemplate = m.component(AddProject, { buttonTemplate: m('.btn.btn-sm.text-muted[data-toggle="modal"][data-target="#addSubComponent"]', {onclick: function() { $osf.trackClick('myProjects', 'add-component', 'open-add-component-modal'); }}, [m('i.fa.fa-plus.m-r-xs', {style: 'font-size: 10px;'}), 'Create component']), parentID: parentID, modalID: 'addSubComponent', title: 'Create new component', categoryList: args.categoryList, stayCallback: function () { var topLevelProject = args.fetchers[linkObject.id]; topLevelProject.fetch(this.saveResult().data.id, function(){ args.updateTreeData(0, topLevelProject._flat, true); }); }, trackingCategory: 'myProjects', trackingAction: 'add-component' }); } return [ m('li', [ m('span.btn', item.label), contributorsTemplate, tagsTemplate, m('i.fa.fa-angle-right') ]), addProjectTemplate ]; } } item.index = index; // Add index to update breadcrumbs item.placement = 'breadcrumb'; // differentiate location for proper breadcrumb actions return m('li',[ m('span.btn.btn-link', {onclick : updateFilesOnClick.bind(null, item)}, item.label), index === 0 && arr.length === 1 ? [contributorsTemplate, tagsTemplate] : '', m('i.fa.fa-angle-right'), ] ); }) ])); } }; /** * Filters Module. * @constructor */ var Filters = { controller : function (args) { var self = this; self.nameCurrentPage = m.prop(1); self.namePageSize = m.prop(4); self.nameTotalPages = m.prop(1); self.tagCurrentPage = m.prop(1); self.tagPageSize = m.prop(4); self.tagTotalPages = m.prop(1); }, view : function (ctrl, args) { if(args.nameFilters.length > 0) { ctrl.nameTotalPages(Math.ceil(args.nameFilters.length/ctrl.namePageSize())); } if(args.tagFilters.length > 0){ ctrl.tagTotalPages(Math.ceil(args.tagFilters.length/ctrl.tagPageSize())); } var filterContributor = function(item, tracking) { args.updateFilesData(item); $osf.trackClick('myProjects', 'filter', 'filter-by-contributor'); }; var filterTag = function(item, tracking) { args.updateFilesData(item); $osf.trackClick('myProjects', 'filter', 'filter-by-tag'); }; var returnNameFilters = function _returnNameFilters(){ if(args.currentView().fetcher.isEmpty()) return m('.text-muted.text-smaller', 'There are no collaborators in this collection yet.'); var list = []; var item; var i; var selectedCSS; var begin = ((ctrl.nameCurrentPage()-1) * ctrl.namePageSize()); // remember indexes start from 0 var end = ((ctrl.nameCurrentPage()) * ctrl.namePageSize()); // 1 more than the last item if (args.nameFilters.length < end) { end = args.nameFilters.length; } for (i = begin; i < end; i++) { item = args.nameFilters[i]; selectedCSS = args.currentView().contributor.indexOf(item) !== -1 ? '.active' : ''; list.push(m('li.pointer' + selectedCSS, {onclick : filterContributor.bind(null, item)}, m('span', item.label) )); } return list; }; var returnTagFilters = function _returnTagFilters(){ if(args.currentView().fetcher.isEmpty()) return m('.text-muted.text-smaller', 'Projects in this collection don\'t have any tags yet.'); var list = []; var selectedCSS; var item; var i; var begin = ((ctrl.tagCurrentPage()-1) * ctrl.tagPageSize()); // remember indexes start from 0 var end = ((ctrl.tagCurrentPage()) * ctrl.tagPageSize()); // 1 more than the last item if (args.tagFilters.length < end) { end = args.tagFilters.length; } for (i = begin; i < end; i++) { item = args.tagFilters[i]; selectedCSS = args.currentView().tag.indexOf(item) !== -1 ? '.active' : ''; list.push(m('li.pointer' + selectedCSS, {onclick : filterTag.bind(null, item)}, m('span', item.label ) )); } return list; }; return m('.db-filters.m-t-lg', [ m('h5.m-t-sm', [ 'Contributors ', m('i.fa.fa-question-circle.text-muted', { 'data-toggle': 'tooltip', 'title': 'Click a contributor\'s name to see projects that you have in common.', 'data-placement' : 'bottom' }, ''), m('.pull-right', args.nameFilters.length && ctrl.nameTotalPages() > 1 ? m.component(MicroPagination, { currentPage : ctrl.nameCurrentPage, totalPages : ctrl.nameTotalPages, type: 'contributors'}) : '' ) ]), m('ul', [ args.currentView().fetcher.loaded === 0 && !args.currentView().fetcher.isEmpty() ? m('.ball-beat.text-center.m-t-md', m('')) : returnNameFilters() ]), m('h5.m-t-sm', [ 'Tags', m('.pull-right', args.tagFilters.length && ctrl.tagTotalPages() > 1 ? m.component(MicroPagination, { currentPage : ctrl.tagCurrentPage, totalPages : ctrl.tagTotalPages, type: 'tags' }) : '' ) ]), m('ul', [ args.currentView().fetcher.loaded === 0 && !args.currentView().fetcher.isEmpty() ? m('.ball-beat.text-center.m-t-md', m('')) : returnTagFilters() ]) ] ); } }; /** * Information Module. * @constructor */ var Information = { view : function (ctrl, args) { function categoryMap(category) { // TODO, you don't need to do this, CSS will do this case change switch (category) { case 'analysis': return 'Analysis'; case 'communication': return 'Communication'; case 'data': return 'Data'; case 'hypothesis': return 'Hypothesis'; case 'methods and measures': return 'Methods and Measures'; case 'procedure': return 'Procedure'; case 'project': return 'Project'; case 'software': return 'Software'; case 'other': return 'Other'; default: return 'Uncategorized'; } } var template = ''; var showRemoveFromCollection; var collectionFilter = args.currentView().collection; if (args.selected().length === 0) { template = m('.db-info-empty.text-muted.p-lg', 'Select a row to view project details.'); } if (args.selected().length === 1) { var item = args.selected()[0].data; showRemoveFromCollection = collectionFilter.data.nodeType === 'collection' && args.selected()[0].depth === 1 && args.fetchers[collectionFilter.id]._cache[item.id]; // Be able to remove top level items but not their children if(item.attributes.category === ''){ item.attributes.category = 'Uncategorized'; } template = m('.p-sm', [ showRemoveFromCollection ? m('.clearfix', m('.btn.btn-default.btn-sm.btn.p-xs.text-danger.pull-right', { onclick : function() { args.removeProjectFromCollections(); $osf.trackClick('myProjects', 'information-panel', 'remove-project-from-collection'); } }, 'Remove from collection')) : '', m('h3', m('a', { href : item.links.html, onclick: function(){ $osf.trackClick('myProjects', 'information-panel', 'navigate-to-project'); }}, item.attributes.title)), m('[role="tabpanel"]', [ m('ul.nav.nav-tabs.m-b-md[role="tablist"]', [ m('li[role="presentation"].active', m('a[href="#tab-information"][aria-controls="information"][role="tab"][data-toggle="tab"]', {onclick: function(){ $osf.trackClick('myProjects', 'information-panel', 'open-information-tab'); }}, 'Information')), m('li[role="presentation"]', m('a[href="#tab-activity"][aria-controls="activity"][role="tab"][data-toggle="tab"]', {onclick : function() { args.getCurrentLogs(); $osf.trackClick('myProjects', 'information-panel', 'open-activity-tab'); }}, 'Activity')) ]), m('.tab-content', [ m('[role="tabpanel"].tab-pane.active#tab-information',[ m('p.db-info-meta.text-muted', [ m('', 'Visibility : ' + (item.attributes.public ? 'Public' : 'Private')), m('', 'Category: ' + categoryMap(item.attributes.category)), m('', 'Last Modified on: ' + (item.date ? item.date.local : '')) ]), m('p', [ m('span', {style: 'white-space:pre-wrap'}, item.attributes.description) ]), item.attributes.tags.length > 0 ? m('p.m-t-md', [ m('h5', 'Tags'), item.attributes.tags.map(function(tag){ return m('a.tag', { href : '/search/?q=(tags:' + tag + ')', onclick: function(){ $osf.trackClick('myProjects', 'information-panel', 'navigate-to-search-by-tag'); }}, tag); }) ]) : '' ]), m('[role="tabpanel"].tab-pane#tab-activity',[ m.component(ActivityLogs, args) ]) ]) ]) ]); } if (args.selected().length > 1) { showRemoveFromCollection = collectionFilter.data.nodeType === 'collection' && args.selected()[0].depth === 1; template = m('.p-sm', [ showRemoveFromCollection ? m('.clearfix', m('.btn.btn-default.btn-sm.p-xs.text-danger.pull-right', { onclick : function() { args.removeProjectFromCollections(); $osf.trackClick('myProjects', 'information-panel', 'remove-multiple-projects-from-collections'); } }, 'Remove selected from collection')) : '', args.selected().map(function(item){ return m('.db-info-multi', [ m('h4', m('a', { href : item.data.links.html}, item.data.attributes.title)), m('p.db-info-meta.text-muted', [ m('span', item.data.attributes.public ? 'Public' : 'Private' + ' ' + item.data.attributes.category), m('span', ', Last Modified on ' + item.data.date.local) ]) ]); }) ]); } return m('.db-information', template); } }; var ActivityLogs = { view : function (ctrl, args) { return m('.db-activity-list.m-t-md', [ args.activityLogs() ? args.activityLogs().map(function(item){ item.trackingCategory = 'myProjects'; item.trackingAction = 'information-panel'; var image = m('i.fa.fa-desktop'); if (item.embeds.user && item.embeds.user.data) { image = m('img', { src : item.embeds.user.data.links.profile_image}); } else if (item.embeds.user && item.embeds.user.errors[0].meta){ image = m('img', { src : item.embeds.user.errors[0].meta.profile_image}); } return m('.db-activity-item', [ m('', [ m('.db-log-avatar.m-r-xs', image), m.component(LogText, item)]), m('.text-right', m('span.text-muted.m-r-xs', item.attributes.formattableDate.local))]); }) : '', m('.db-activity-nav.text-center', [ args.showMoreActivityLogs() ? m('.btn.btn-sm.btn-link', { onclick: function(){ args.getLogs(args.showMoreActivityLogs(), true); $osf.trackClick('myProjects', 'information-panel', 'show-more-activity'); }}, [ 'Show more', m('i.fa.fa-caret-down.m-l-xs')]) : '' ]) ]); } }; /** * Modals views. * @constructor */ var Modals = { view : function(ctrl, args) { return m('.db-fbModals', [ m('#infoModal.modal.fade[tabindex=-1][role="dialog"][aria-hidden="true"]', m('.modal-dialog', m('.modal-content', [ m('.modal-body', [ m('button.close[data-dismiss="modal"][aria-label="Close"]', [ m('span[aria-hidden="true"]','×') ]), m.component(Information, args) ]) ]) ) ) ]); } }; module.exports = { MyProjects : MyProjects, Collections : Collections, MicroPagination : MicroPagination, ActivityLogs : ActivityLogs, LinkObject: LinkObject, NodeFetcher: NodeFetcher, };
Add event tracking for navigating to project from information panel when multiple selected.
website/static/js/myProjects.js
Add event tracking for navigating to project from information panel when multiple selected.
<ide><path>ebsite/static/js/myProjects.js <ide> } }, 'Remove selected from collection')) : '', <ide> args.selected().map(function(item){ <ide> return m('.db-info-multi', [ <del> m('h4', m('a', { href : item.data.links.html}, item.data.attributes.title)), <add> m('h4', m('a', { href : item.data.links.html, onclick: function(){ <add> $osf.trackClick('myProjects', 'information-panel', 'navigate-to-project-multiple-selected'); <add> }}, item.data.attributes.title)), <ide> m('p.db-info-meta.text-muted', [ <ide> m('span', item.data.attributes.public ? 'Public' : 'Private' + ' ' + item.data.attributes.category), <ide> m('span', ', Last Modified on ' + item.data.date.local)
Java
apache-2.0
error: pathspec 'framework/db/test/com/cloud/utils/db/FilterTest.java' did not match any file(s) known to git
9d1a469ae5f0a3751b64d66582fbcc2180a9c97c
1
jcshen007/cloudstack,GabrielBrascher/cloudstack,wido/cloudstack,resmo/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,GabrielBrascher/cloudstack,DaanHoogland/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,GabrielBrascher/cloudstack,resmo/cloudstack,wido/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,GabrielBrascher/cloudstack,jcshen007/cloudstack,jcshen007/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,wido/cloudstack,wido/cloudstack,DaanHoogland/cloudstack,resmo/cloudstack,jcshen007/cloudstack,DaanHoogland/cloudstack
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package com.cloud.utils.db; import org.junit.Assert; import org.junit.Test; public class FilterTest { @Test /* * This test verifies that the Order By clause generated by the filter is correct and it separates each * order by field with a comma. Using DbTestVO to assert it */ public void testAddOrderBy() { Filter filter = new Filter(DbTestVO.class, "fieldString", true, 1L, 1L); Assert.assertTrue(filter.getOrderBy().trim().toLowerCase().equals("order by test.fld_string asc")); filter.addOrderBy(DbTestVO.class, "fieldLong", true); Assert.assertTrue(filter.getOrderBy().contains(",")); Assert.assertTrue(filter.getOrderBy().split(",")[1].trim().toLowerCase().equals("test.fld_long asc")); filter.addOrderBy(DbTestVO.class, "fieldInt", true); Assert.assertTrue(filter.getOrderBy().split(",").length == 3); Assert.assertTrue(filter.getOrderBy().split(",")[2].trim().toLowerCase().equals("test.fld_int asc")); } }
framework/db/test/com/cloud/utils/db/FilterTest.java
CLOUDSTACK-9006 - ListTemplates API returns result in inconsistent order when called concurrently Adding filter test to verify addOrderBy method.
framework/db/test/com/cloud/utils/db/FilterTest.java
CLOUDSTACK-9006 - ListTemplates API returns result in inconsistent order when called concurrently
<ide><path>ramework/db/test/com/cloud/utils/db/FilterTest.java <add>// Licensed to the Apache Software Foundation (ASF) under one <add>// or more contributor license agreements. See the NOTICE file <add>// distributed with this work for additional information <add>// regarding copyright ownership. The ASF licenses this file <add>// to you under the Apache License, Version 2.0 (the <add>// "License"); you may not use this file except in compliance <add>// the License. You may obtain a copy of the License at <add>// <add>// http://www.apache.org/licenses/LICENSE-2.0 <add>// <add>// Unless required by applicable law or agreed to in writing, <add>// software distributed under the License is distributed on an <add>// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add>// KIND, either express or implied. See the License for the <add>// specific language governing permissions and limitations <add>// under the License. <add>package com.cloud.utils.db; <add> <add>import org.junit.Assert; <add>import org.junit.Test; <add> <add>public class FilterTest { <add> <add> @Test <add> /* <add> * This test verifies that the Order By clause generated by the filter is correct and it separates each <add> * order by field with a comma. Using DbTestVO to assert it <add> */ <add> public void testAddOrderBy() { <add> Filter filter = new Filter(DbTestVO.class, "fieldString", true, 1L, 1L); <add> <add> Assert.assertTrue(filter.getOrderBy().trim().toLowerCase().equals("order by test.fld_string asc")); <add> <add> filter.addOrderBy(DbTestVO.class, "fieldLong", true); <add> <add> Assert.assertTrue(filter.getOrderBy().contains(",")); <add> Assert.assertTrue(filter.getOrderBy().split(",")[1].trim().toLowerCase().equals("test.fld_long asc")); <add> <add> filter.addOrderBy(DbTestVO.class, "fieldInt", true); <add> <add> Assert.assertTrue(filter.getOrderBy().split(",").length == 3); <add> Assert.assertTrue(filter.getOrderBy().split(",")[2].trim().toLowerCase().equals("test.fld_int asc")); <add> } <add>}
JavaScript
mpl-2.0
ba88fa6c28d166e12d49b5399a60808167ffaf06
0
linediconsine/biscreen-test,linediconsine/biscreen-test
/** * Created by ninja on 30/06/14. */ Modernizr.addTest('bigscreen', function () { var dim = { width: 0, height: 0 }; if (document.body && document.body.offsetWidth) { dim.width = document.body.offsetWidth; dim.height = document.body.offsetHeight; } if (document.compatMode == 'CSS1Compat' && document.documentElement && document.documentElement.offsetWidth) { dim.width = document.documentElement.offsetWidth; dim.height = document.documentElement.offsetHeight; } if (window.innerWidth && window.innerHeight) { dim.width = window.innerWidth; dim.height = window.innerHeight; } /* Detect height both Portrait/landscape mode */ little = Math.min(dim.width,dim.height); return little > 980; });
biscreen-test.js
/** * Created by ninja on 30/06/14. */ Modernizr.addTest('bigscreen', function () { var dim = { width: 0, height: 0 }; if (document.body && document.body.offsetWidth) { dim.width = document.body.offsetWidth; dim.height = document.body.offsetHeight; } if (document.compatMode == 'CSS1Compat' && document.documentElement && document.documentElement.offsetWidth) { dim.width = document.documentElement.offsetWidth; dim.height = document.documentElement.offsetHeight; } if (window.innerWidth && window.innerHeight) { dim.width = window.innerWidth; dim.height = window.innerHeight; } /* Detect height both Portrait/landscape mode */ little = Math.min(dim.width,dim.height); return little > 400; });
fix test from test done
biscreen-test.js
fix test from test done
<ide><path>iscreen-test.js <ide> } <ide> /* Detect height both Portrait/landscape mode */ <ide> little = Math.min(dim.width,dim.height); <del> return little > 400; <add> return little > 980; <ide> }); <ide> <ide>
JavaScript
mpl-2.0
0ecb2d1e4f578f095fb360a4e534f5f0d4525b1f
0
joyent/sdcadm,joyent/sdcadm,joyent/sdcadm
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ /* * Core SdcAdm class. */ var assert = require('assert-plus'); var child_process = require('child_process'), spawn = child_process.spawn, exec = child_process.exec; var util = require('util'), format = util.format; var fs = require('fs'); var http = require('http'); var https = require('https'); var p = console.log; var path = require('path'); var crypto = require('crypto'); var mkdirp = require('mkdirp'); var sdcClients = require('sdc-clients'); var semver = require('semver'); var sprintf = require('extsprintf').sprintf; var urclient = require('urclient'); var vasync = require('vasync'); var WfClient = require('wf-client'); var uuid = require('node-uuid'); var ProgressBar = require('progbar').ProgressBar; var common = require('./common'); var svcadm = require('./svcadm'); var errors = require('./errors'); var lock = require('./locker').lock; var pkg = require('../package.json'); var procedures = require('./procedures'); var History = require('./history').History; var ur = require('./ur'); var UA = format('%s/%s (node/%s; openssl/%s)', pkg.name, pkg.version, process.versions.node, process.versions.openssl); var UPDATE_PLAN_FORMAT_VER = 1; //---- UpdatePlan class // A light data object with some conveninence functions. function UpdatePlan(options) { assert.object(options, 'options'); assert.arrayOfObject(options.curr, 'options.curr'); assert.arrayOfObject(options.targ, 'options.targ'); assert.arrayOfObject(options.changes, 'options.changes'); assert.bool(options.justImages, 'options.justImages'); assert.optionalBool(options.rollback, 'options.rollback'); this.v = UPDATE_PLAN_FORMAT_VER; this.curr = options.curr; this.targ = options.targ; this.changes = options.changes; this.justImages = options.justImages; this.rollback = options.rollback || false; } UpdatePlan.prototype.serialize = function serialize() { return JSON.stringify({ v: this.v, targ: this.targ, changes: this.changes, justImages: this.justImages }, null, 4); }; //---- SdcAdm class /** * Create a SdcAdm. * * @param options {Object} * - log {Bunyan Logger} */ function SdcAdm(options) { assert.object(options, 'options'); assert.object(options.log, 'options.log'); // A unique UUID for this sdcadm run -- used for client req_id's below, // and for sdcadm history entries. if (!options.uuid) { options.uuid = uuid(); } if (!options.username) { options.username = process.env.USER; } var self = this; this.log = options.log; this.uuid = options.uuid; this.username = options.username; self._lockPath = '/var/run/sdcadm.lock'; self.userAgent = UA; Object.defineProperty(this, 'sapi', { get: function () { if (self._sapi === undefined) { self._sapi = new sdcClients.SAPI({ url: self.config.sapi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._sapi; } }); Object.defineProperty(this, 'cnapi', { get: function () { if (self._cnapi === undefined) { self._cnapi = new sdcClients.CNAPI({ url: self.config.cnapi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._cnapi; } }); Object.defineProperty(this, 'papi', { get: function () { if (self._papi === undefined) { self._papi = new sdcClients.PAPI({ url: self.config.papi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._papi; } }); Object.defineProperty(this, 'vmapi', { get: function () { if (self._vmapi === undefined) { self._vmapi = new sdcClients.VMAPI({ url: self.config.vmapi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._vmapi; } }); Object.defineProperty(this, 'imgapi', { get: function () { if (self._imgapi === undefined) { var opts = { url: self.config.imgapi.url, agent: false, userAgent: self.userAgent, /* * Don't *need* API version 2 and doing so breaks GetImage * with an old IMGAPI before: * commit de5c9bea58c934273b7efc7caa4ff46eeea380f6 * Date: Fri Aug 1 22:50:32 2014 -0700 * which currently is possible with the svcMinImages.imgapi * config in defaults.json. */ // version: '~2', log: self.log, headers: { 'x-request-id': self.uuid } }; self._imgapi = new sdcClients.IMGAPI(opts); } return self._imgapi; } }); Object.defineProperty(this, 'updates', { get: function () { if (self._updates === undefined) { var opts = { url: self.config.updatesServerUrl, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }; if (self.sdc.metadata.update_channel) { opts.channel = self.sdc.metadata.update_channel; } self._updates = new sdcClients.IMGAPI(opts); } return self._updates; } }); Object.defineProperty(this, 'imagesJo', { get: function () { if (self._imagesJo === undefined) { var opts = { url: 'https://images.joyent.com', agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }; self._imagesJo = new sdcClients.IMGAPI(opts); } return self._imagesJo; } }); Object.defineProperty(this, 'napi', { get: function () { if (self._napi === undefined) { self._napi = new sdcClients.NAPI({ url: self.config.napi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._napi; } }); Object.defineProperty(this, 'wfapi', { get: function () { if (self._wfapi === undefined) { self._wfapi = new WfClient({ url: self.config.wfapi.url, agent: false, path: './not/used/because/we/do/not/loadWorkflows', // TODO: Get wf-client to take `userAgent`. //userAgent: self.userAgent, log: self.log.child({client: 'wfapi'}, true), headers: { 'x-request-id': self.uuid } }); } return self._wfapi; } }); // NOTE: A method using self.ufds should take care of // calling self._ufds.close(function (err) {}); Yuck. Object.defineProperty(this, 'ufds', { get: function () { if (self._ufds === undefined) { self._ufds = new sdcClients.UFDS({ url: self.config.ufds.url, bindDN: self.config.ufds.bindDN, bindPassword: self.config.ufds.bindPassword, maxConnections: 1, retry: { initialDelay: 1000 }, clientTimeout: 120000, tlsOptions: { rejectUnauthorized: false }, log: self.log }); self._ufds.once('error', function (err) { throw err; }); self._ufds.once('connect', function () { self._ufds.removeAllListeners('error'); self._ufds.on('error', function (err) { self.log.info('UFDS disconnected'); }); self._ufds.on('connect', function () { self.log.info('UFDS reconnected'); }); self._ufds.on('timeout', function (msg) { self.log.error(msg); self._ufds.client.socket.destroy(); }); }); } return self._ufds; } }); this.urConnTimedOut = false; Object.defineProperty(this, 'ur', { get: function () { if (self._ur === undefined && !self.urConnTimedOut) { self._ur = urclient.create_ur_client({ connect_timeout: 5000, // in ms enable_http: false, amqp_config: self.config.amqp, log: self.log.child({client: 'ur'}, true) }); // Handle connection errors: self._ur.ur_urconn.on('error', function urErr(err) { self.log.error({ err: err }, 'Ur Connection Error'); self.urConnTimedOut = true; }); } return self._ur; } }); } // This function defines the sdcadm properties which require async callbacks // to be used: 'config', 'history' and 'sdc' application. SdcAdm.prototype.init = function init(cb) { var self = this; common.loadConfig({log: self.log}, function (err, config) { if (err) { return cb(err); } self.config = config; if (self.config.serverUuid) { self.userAgent += ' server=' + self.config.serverUuid; } self.history = new History({sdcadm: self}); self.getApp({app: 'sdc'}, function (appErr, app) { if (appErr) { // Couple known issues we can help operators with a friendly // message instead of the default "ENO..." errors: if (appErr.message) { if (appErr.message.match(/getaddrinfo ENOTFOUND/)) { console.log('Binder service seems to be down. ' + 'Please review it before proceeding'); } else if (appErr.message.match(/connect ECONNREFUSED/)) { console.log('Sapi service seems to be down. ' + 'Please review it before proceeding'); } } return cb(appErr); } self.sdc = app; return self.history.init(cb); }); }); }; /** * Gather a JSON object for every (or specified subset of) installed SDC * service instance. * * "Services" include: SDC core vms and agents. * * All types will have these fields: * type type of service, one of 'vm' or 'agent' * instance (Note: Agents don't current have a instance UUID * exposed.) * service name of service, e.g. 'vmapi, 'provisioner' * image image UUID (Note: Agents aren't * currently distributed as separate "images" in * updates.joyent.com. Until they are `image === null`.) * version version string, e.g. '1.2.3' * server server uuid (if available) * hostname server hostname (if available) * server_ip 'admin' network IP for the server (if available) * * Other fields for type=vm instances: * ip 'admin' network IP (for type=vm instances) * state the VM state from VMAPI, e.g. 'running', 'provisioning' * zonename * * @param opts {Object} Optional * - types {Array} instance types to which to limit results. Valid values * are 'vm' or 'agent'. * - svcs {Array} service names to which to limit results. * @param cb {Function} `function (err, insts)` */ SdcAdm.prototype.listInsts = function listInsts(opts, cb) { var self = this; if (cb === undefined) { cb = opts; opts = {}; } assert.object(opts, 'opts'); assert.optionalArrayOfString(opts.types, 'opts.types'); assert.optionalArrayOfString(opts.svcs, 'opts.svcs'); assert.func(cb, 'cb'); var isWantedSvc = null; if (opts.svcs) { isWantedSvc = {}; for (var j = 0; j < opts.svcs.length; j++) { isWantedSvc[opts.svcs[j]] = true; } } var context = { insts: [] }; vasync.pipeline({arg: context, funcs: [ function getServers(ctx, next) { ctx.serverFromUuid = {}; ctx.serverAdminIpFromUuid = {}; var serverOpts = { extras: 'sysinfo,agents' }; self.cnapi.listServers(serverOpts, function (serversErr, servers) { if (serversErr) { return next(new errors.SDCClientError(serversErr, 'cnapi')); } for (var i = 0; i < servers.length; i++) { var server = servers[i]; ctx.serverFromUuid[server.uuid] = server; var nics = server.sysinfo['Network Interfaces'] || {}; var adminIp = Object.keys(nics).map(function (nicName) { return nics[nicName]; }).filter(function (nic) { return nic['NIC Names'].indexOf('admin') !== -1; }).map(function (nic) { return nic.ip4addr; })[0]; ctx.serverAdminIpFromUuid[server.uuid] = adminIp; } next(); }); }, /* * Right now we don't have a way to match an agent inst in SAPI to * the server on which it lives. That's kind of lame. However a * proper answer should eventually come with sdc-update M10 work * to get agents individually managed. */ function fillOutAgentInsts(ctx, next) { if (opts.types && opts.types.indexOf('agent') === -1) { return next(); } var serverUuids = Object.keys(ctx.serverFromUuid); for (var i = 0; i < serverUuids.length; i++) { var server = ctx.serverFromUuid[serverUuids[i]]; (server.agents || server.sysinfo['SDC Agents'] || []).forEach( function (agent) { if (!isWantedSvc || isWantedSvc[agent.name]) { var inst = { type: 'agent', service: agent.name, instance: agent.uuid, version: agent.version, image: agent.image_uuid, server: server.uuid, hostname: server.hostname, server_ip: ctx.serverAdminIpFromUuid[server.uuid] }; ctx.insts.push(inst); } }); } next(); }, /* * Note: For *now* we gather for VMs that aren't listed as SAPI * instances because, e.g., SDC doesn't add an "assets" service. * It should. * * As a result, instead of SAPI being the authority on insts, it is * instead a VMAPI query for admin-owned VMs with `tags.smartdc_role`. */ function getVmInfo(ctx, next) { if (opts.types && opts.types.indexOf('vm') === -1) { return next(); } ctx.vmFromUuid = {}; /** * Instead of getting each VM (there could be up to dozens), * lets get all of admin's VMs in one req and filter those. * * 'cloudapi' zones typically don't have * `tags.smartdc_core=true` so we can't filter on that. And * VMAPI doesn't support filtering on presence of a tag * (e.g. `smartdc_role`). */ var filters = { state: 'active', owner_uuid: self.config.ufds_admin_uuid }; self.vmapi.listVms(filters, function (err, vms) { if (err) { return next(new errors.SDCClientError(err, 'vmapi')); } for (var i = 0; i < vms.length; i++) { var vm = vms[i]; if (vm.tags && vm.tags.smartdc_role) { if (!isWantedSvc || isWantedSvc[vm.tags.smartdc_role]) { ctx.vmFromUuid[vm.uuid] = vm; } } } next(); }); }, function getImgs(ctx, next) { if (opts.types && opts.types.indexOf('vm') === -1) { return next(); } ctx.imgFromUuid = {}; // Prefer *vmFromUuid* to *sapiInstFromUuid* b/c no 'assets' svc. var vmUuids = Object.keys(ctx.vmFromUuid); for (var i = 0; i < vmUuids.length; i++) { var vm = ctx.vmFromUuid[vmUuids[i]]; ctx.imgFromUuid[vm.image_uuid] = null; } var imgUuids = Object.keys(ctx.imgFromUuid); self.log.trace({imgUuids: imgUuids}, 'listInsts imgUuids'); vasync.forEachParallel({ inputs: imgUuids, func: function getOneImg(imgUuid, nextImg) { self.imgapi.getImage(imgUuid, function (err, img) { if (!err) { ctx.imgFromUuid[imgUuid] = img; nextImg(); } else if (err.restCode !== 'ResourceNotFound') { nextImg(new errors.SDCClientError( err, 'imgapi')); } else { nextImg(); } }); } }, next); }, function fillOutVmInsts(ctx, next) { if (opts.types && opts.types.indexOf('vm') === -1) { return next(); } // Prefer *vmFromUuid* to *sapiInstFromUuid* b/c no 'assets' svc. var uuids = Object.keys(ctx.vmFromUuid); for (var i = 0; i < uuids.length; i++) { var vm = ctx.vmFromUuid[uuids[i]]; var img = ctx.imgFromUuid[vm.image_uuid]; var inst = { type: 'vm', alias: vm.alias, version: null, instance: vm.uuid, zonename: vm.uuid, service: vm.tags.smartdc_role, image: vm.image_uuid, state: vm.state, server: null, hostname: null, server_ip: null }; if (img) { inst.version = img.version; } // A state='provisioning' VM might not yet have a // 'server_uuid'. if (vm.server_uuid) { inst.server = vm.server_uuid; inst.hostname = ctx.serverFromUuid[ vm.server_uuid].hostname; inst.server_ip = ctx.serverAdminIpFromUuid[ vm.server_uuid]; } var adminIp = vm.nics.filter(function (nic) { return nic.nic_tag === 'admin'; }).map(function (nic) { return nic.ip; })[0]; if (adminIp) { inst.ip = adminIp; } ctx.insts.push(inst); } next(); }, function findMissingInstImgs(ctx, next) { vasync.forEachParallel({ inputs: ctx.insts, func: function imgadmGetImg(inst, nextInst) { if (inst.version || !inst.server) { return nextInst(); } common.imgadmGetRemote({ img_uuid: inst.image, server: inst.server, log: self.log }, function (err, img) { if (err) { self.log.error({err: err}, 'imgadm error'); return nextInst(); } if (img && img.manifest && img.manifest.version) { inst.version = img.manifest.version; } return nextInst(); }); } }, next); } ]}, function (err) { cb(err, context.insts); }); }; /** * Gather a JSON object for each installed SDC service. * * "Services" include: SDC core vms and agents. */ SdcAdm.prototype.getServices = function getServices(opts, cb) { var self = this; assert.object(opts, 'opts'); assert.func(cb, 'cb'); var app = self.sdc; var svcs = []; vasync.pipeline({funcs: [ function getSapiSvcs(_, next) { // 'cloudapi' zones typically don't have `tags.smartdc_core=true` // so we can't filter on that. And VMAPI doesn't support filtering // on presence of a tag (e.g. `smartdc_role`.) var filters = { application_uuid: app.uuid }; if (opts.type) { filters.type = opts.type; } self.sapi.listServices(filters, function (svcsErr, svcs_) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } svcs = svcs_; var haveAssets = false; svcs.forEach(function (svc) { // TODO(trent): want SAPI to have this eventually. // TOOLS-724: new SAPI instances will have this type // member. Do not override it when already present. if (!svc.type) { svc.type = 'vm'; } if (svc.name === 'assets') { haveAssets = true; } }); // TODO: get assets service in SAPI. Hack it in for now. // Not having 'assets' service mucks up update type guessing // in 'sdcadm update assets', for example. if (!haveAssets) { svcs.push({ type: 'vm', name: 'assets' }); } next(); }); }, function getAgents(_, next) { // TODO: Remove these hardcoded values // Hardcode "known" agents for now until SAPI handles agents. // Excluding "marlin". Should we include hagfish-watcher? [ { 'name': 'cabase' }, { 'name': 'hagfish-watcher' }, { 'name': 'agents_core' }, { 'name': 'firewaller' }, { 'name': 'amon-agent' }, { 'name': 'cainstsvc' }, { 'name': 'provisioner' }, { 'name': 'amon-relay' }, { 'name': 'heartbeater' }, { 'name': 'smartlogin' }, { 'name': 'zonetracker' } ].forEach(function (agent) { var exists = svcs.filter(function (s) { return (s.name === agent.name); }).length; if (!exists) { agent.type = 'agent'; svcs.push(agent); } }); next(); } ]}, function (err) { cb(err, svcs); }); }; /** * Get the full image object for the given image UUID from either the local * IMGAPI or the updates server. * * @param opts {Object} Required. * - uuid {UUID} Required. The image uuid. * @param cb {Function} `function (err, img)` */ SdcAdm.prototype.getImage = function getImage(opts, cb) { assert.object(opts, 'opts'); assert.string(opts.uuid, 'opts.uuid'); assert.func(cb, 'cb'); var self = this; self.imgapi.getImage(opts.uuid, function (iErr, iImg) { if (iErr && iErr.body && iErr.body.code === 'ResourceNotFound') { self.updates.getImage(opts.uuid, cb); } else { cb(iErr, iImg); } }); }; /** * Get a SAPI application. * * @param opts {Object} Required. * - app {String|UUID} Required. The application name or UUID. * @param cb {Function} `function (err, app)` */ SdcAdm.prototype.getApp = function getApp(opts, cb) { assert.object(opts, 'opts'); assert.string(opts.app, 'opts.app'); assert.func(cb, 'cb'); if (opts.app === 'sdc' && this.sdc) { cb(null, this.sdc); } else if (common.UUID_RE.test(opts.app)) { this.sapi.getApplication(opts.app, errors.sdcClientErrWrap(cb, 'sapi')); } else { this.sapi.listApplications({name: opts.app}, function (err, apps) { if (err) { cb(new errors.SDCClientError(err, 'sapi')); } else if (apps.length !== 1) { cb(new errors.InternalError({ message: format('unexpected number of "%s" apps: %d', opts.app, apps.length) })); } else { cb(null, apps[0]); } }); } }; /** * Get a SAPI service. * * Dev Note: Why 'getSvc' and not 'getService'? I want to move to * app/svc/inst/img for naming in functions as well. * * @param opts {Object} Required. * - app {String|UUID} Required. The application name or UUID. * - svc {String|UUID} Required. The service name or UUID. * - allowNone {Boolean} Optional. Default false. Set `true` to return * `cb()` if there is no such service. By default an InternalError is * returned. * @param cb {Function} `function (err, svc)` */ SdcAdm.prototype.getSvc = function getSvc(opts, cb) { var self = this; assert.optionalBool(opts.allowNone, 'opts.allowNone'); self.getApp({app: opts.app}, function (appErr, app) { if (appErr) { return cb(appErr); } if (common.UUID_RE.test(opts.svc)) { self.sapi.getService(opts.svc, function (svcErr, svc) { if (svcErr) { return cb(new errors.SDCClientError(svcErr, 'sapi')); } else if (svc.application_uuid !== app.uuid) { cb(new errors.ValidationError(format( 'given svc "%s" does not belong to the "%s" app', opts.svc, opts.app))); } else { cb(null, svc); } }); } else { var filters = { application_uuid: app.uuid, name: opts.svc }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return cb(new errors.SDCClientError(svcsErr, 'sapi')); } else if (svcs.length > 1) { cb(new errors.InternalError({ message: format('unexpected number of "%s" svcs: %d', opts.svc, svcs.length) })); } else if (svcs.length === 0) { if (opts.allowNone) { cb(null); } else { cb(new errors.InternalError({ message: format('no "%s" service found', opts.svc) })); } } else { cb(null, svcs[0]); } }); } }); }; /** * Get the image version for all the active VMs of the given service. * * @type obj {Object} including: * @prop vms {Array} of VMAPI vms * @prop imgs {Array} of IMGAPI imgs (only different images, if all the * VMs are using the same image, only one image will be returned here). * * @params svc {String|UUID} Required. The service name or UUID. * @param cb {Function} `function (err, obj)` */ SdcAdm.prototype.getImgsForSvcVms = function getImgsForSvcVms(opts, cb) { var self = this; assert.object(opts, 'opts'); assert.optionalString(opts.app, 'opts.app'); assert.string(opts.svc, 'opts.svc'); assert.func(cb, 'cb'); if (!opts.app) { opts.app = 'sdc'; } var svc, vms; vasync.pipeline({funcs: [ function _getSvc(_, next) { self.getSvc(opts, function (err, service) { if (err) { return next(err); } svc = service; return next(); }); }, function _getVms(_, next) { self.vmapi.listVms({ 'tag.smartdc_role': svc.name, state: 'active' }, function (vmsErr, vms_) { if (vmsErr) { return next(vmsErr); } if (!vms_.length) { return next(new errors.SDCClientError(new Error(format( 'Unable to find %s VMs', svc.name)), 'vmapi')); } vms = vms_; return next(); }); } ]}, function pipeCb(err) { if (err) { return cb(err); } var imgs = []; var differentImgUUIDs = vms.map(function (vm) { return (vm.image_uuid); }).sort().filter(function (id, pos, ary) { // Once we've sorted out the array, we can remove any duplicates // just by looking up at the previous element. Obviously, first one // will never be removed. return (!pos || id !== ary[pos - 1]); }); vasync.forEachParallel({ func: function _getImg(id, next) { self.getImage({uuid: id}, function (er3, img) { if (er3) { return next(er3); } imgs.push(img); return next(); }); }, inputs: differentImgUUIDs }, function paraCb(err2) { if (err2) { return cb(err2); } return cb(null, {imgs: imgs, vms: vms}); }); }); }; /* * Fetch a given agent installer image (or if desired, latest), download it, * then use /usbkey/scripts/update_agents to deploy the installer to compute * nodes. */ SdcAdm.prototype.updateAgents = function updateAgents(options, callback) { assert.object(options, 'options'); assert.string(options.image, 'options.image'); assert.optionalBool(options.justDownload, 'options.justDownload'); assert.optionalBool(options.yes, 'options.yes'); assert.optionalBool(options.all, 'options.all'); assert.optionalArrayOfString(options.servers, 'options.servers'); assert.optionalArrayOfString(options.exclude, 'options.exclude'); assert.func(options.progress, 'options.progress'); var self = this; var localdir = '/var/tmp'; var deleteOnFinish = true; var filepath; var image; // The file name, to be used by ur: var fname; var progress = options.progress; var justDownload = options.justDownload; // Used by history var changes = []; var hist; // Version of (latest) local agents file: var localVersion; var localFile; // The image we are trying to download already exists on cache dir var existingImage = false; var runningServers; // All the setup servers from CNAPI: var serverRecs; // The servers we're gonna update: var assignServers = []; // We may receive errors from UR when trying to update agents into // the CNs: var errs = []; function findInstallerImageLatest(cb) { var filter = { name: 'agentsshar' }; self.updates.listImages(filter, function (err, images) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } if (Array.isArray(images) && !images.length) { return cb(new errors.UpdateError('no images found')); } common.sortArrayOfObjects(images, ['published_at']); image = images[images.length - 1]; cb(); }); return; } function findInstallerImageByUuid(cb) { self.updates.getImage(options.image, function (err, foundImage) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } image = foundImage; cb(); }); } function downloadInstallerImage(cb) { progress('Downloading agentsshar image to %s', filepath); function onImage(err) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } cb(); } self.updates.getImageFile(image.uuid, filepath, onImage); } function cleanup(cb) { fs.unlink(filepath, function (err) { if (err) { self.log.warn(err, 'unlinking %s', filepath); } cb(); }); } vasync.pipeline({funcs: [ function findImg(_, next) { if (options.image === 'latest') { findInstallerImageLatest(next); // Check if the value of the parameter `image` is a file } else if (fs.existsSync(options.image)) { filepath = options.image; deleteOnFinish = false; next(); } else { findInstallerImageByUuid(next); } }, function findLatestLocalVersion(_, next) { if (!image) { return next(); } var latestPath = '/usbkey/extra/agents/latest'; fs.exists(latestPath, function (exists) { if (!exists) { progress('Symlink to latest agents file (%s) is missing.', latestPath); return next(); } else { fs.readlink(latestPath, function (err, linkString) { if (err) { self.log.error(err, latestPath); progress('Error reading symlink to latest ' + 'agents file (%s).', latestPath); return next(); } else { localFile = '/usbkey/extra/agents/' + linkString; localVersion = path.basename(linkString, '.sh'). replace(/^agents-/, ''); progress('UUID of latest installed agents image ' + 'is: %s\n', localVersion); return next(); } }); } }); }, function localImageChecksum(_, next) { // No need to check anything if argument was a file path if (!image) { return next(); } var hash = null; var s = fs.ReadStream(localFile); hash = crypto.createHash('sha1'); s.on('data', function (d) { hash.update(d); }); s.on('end', function () { var sha1_actual = hash.digest('hex'); var sha1_expected = image.files[0].sha1; self.log.trace({ sha1_local: sha1_actual, sha1_remote: sha1_expected }, 'Image checksum'); if ((sha1_actual === sha1_expected)) { progress('The agentsshar is already in assets dir: %s', localFile); progress('Please do one of the following:'); progress('1. Specify the full path to install this ' + 'version:'); progress(common.indent( 'sdcadm experimental update-agents ' + localFile)); progress('2. Or, delete that path and re-run to ' + 're-download and install.'); return callback(); } else { return next(); } }); }, function serverList(_, next) { if (justDownload) { return next(); } self.cnapi.listServers({ setup: true }, function (err, recs) { if (err) { return next(err); } serverRecs = recs; next(); }); }, function findServersToUpdate(_, next) { if (justDownload) { return next(); } // Find the headnode and depending on the options passed in, // either a single compute node or multiple. We need the headnode // details so that we can update the booter cache on the headnode // dhcpd zone. serverRecs.forEach(function (server) { if (options.all) { assignServers.push(server); } else if (options.servers.indexOf(server.hostname) !== -1 || options.servers.indexOf(server.uuid) !== -1) { assignServers.push(server); } }); if (options.servers && !assignServers.length) { return next( new Error(format( 'server %j not found', options.servers))); } next(); }, function applyExcludeFilters(_, next) { if (justDownload) { return next(); } if (!options.exclude || !options.all) { return next(); } common.excludeServers({ servers: assignServers, exclude: options.exclude, log: self.log }, function (err, servers) { if (err) { return next(err); } assignServers = servers; progress('Selected %d servers on which to install', assignServers.length); return next(); }); }, function connectToUr(_, next) { if (justDownload) { return next(); } self.ur.once('error', function (err) { self.log.debug({err: err}, 'Ur error'); return next(new errors.InternalError({ message: 'Error Connecting to Ur' })); }); // If the connection times out, this will never be reached, and the // function above should call next self.ur.once('ready', function () { return next(); }); }, function urNodeDiscovery(_, next) { if (justDownload) { return next(); } progress('Ensuring contact with all servers'); var results = []; var nodeList = assignServers.map(function (s) { return (s.uuid); }); var disco = self.ur.discover({ timeout: 10 * 1000, exclude_headnode: false, node_list: nodeList }); function end() { self.log.debug('Ur Node Discovery complete'); results = results.map(function (res) { return (res.uuid); }); assignServers = assignServers.filter(function (srv) { return (results.indexOf(srv.uuid) !== -1); }); return next(); } function failure(err) { if (err.nodes_missing && err.nodes_missing.length) { // Cannot find all nodes self.log.info({ nodes: err.nodes_missing }, 'Ur cannot find these nodes'); progress('\nUr cannot find the following nodes: %s', err.nodes_missing.join(', ')); progress('You should fix this issue before running ' + 'this command again'); } else { self.log.error({err: err}, 'Ur Node Discovery failed'); } return next(err); } disco.on('error', failure); disco.on('server', function (server) { var msg = common.indent('- Server ' + server.uuid + ' (' + server.hostname + ') available'); self.log.debug(msg); // Too much noise for a setup with 200 servers // progress(msg); results.push(server); }); disco.on('duplicate', function (uid, hostname) { var err = new Error('duplicate host specification detected'); err.duplicate = [ uid, hostname ]; /* * We are done with this discovery session. Cancel it and * ignore future error/end events. */ disco.cancel(); failure(err); }); disco.on('end', end); }, function confirm(_, next) { var m = 'This update will make the following changes:\n'; if (filepath) { m += common.indent(format('Update agents on %d ' + 'servers using file: %s\n', assignServers.length, filepath)); } else { var word = options.justDownload ? 'Download' : 'Download and install'; m += common.indent(format('%s agentsshar ' + 'image %s\n(%s) on %d servers', word, image.uuid, image.version, assignServers.length)); } progress(''); progress(m); progress(''); if (options.yes) { return next(); } var msg = 'Would you like to continue? [y/N] '; common.promptYesNo({msg: msg, default: 'n'}, function (answer) { if (answer !== 'y') { progress('Aborting agents update'); return callback(); } progress(''); return next(); }); }, function saveChangesToHistory(_, next) { if (justDownload) { return next(); } var change = { service: { name: 'agents-shar' }, type: 'update-service', img: (image ? image : options.image) }; changes.push(change); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function prepareReRun(_, next) { if (filepath && !image) { return next(); } // We need to move the file to some other place due to // the way /usbkey/scripts/update_agents works, which // will try to re-copy the file to its original place. filepath = format('%s/agents-%s.sh', localdir, localVersion); if (existingImage && options.force) { var cmd = format('/usr/bin/mv %s %s', localFile, filepath); progress('Moving agentsshar to assets dir %s', filepath); exec(cmd, {}, function (err, stdout, stderr) { if (err) { var msg = format( 'exec error:\n' + '\tcmd: %s\n' + '\texit status: %s\n' + '\tstdout:\n%s\n' + '\tstderr:\n%s', cmd, err.code, stdout.trim(), stderr.trim()); return next(new errors.InternalError({ message: msg, cause: err }), stdout, stderr); } return next(); }); } else { return next(); } }, function downloadInstaller(_, next) { if (filepath && !image) { progress('Using agent installer file %s', filepath); next(); } else { filepath = format('%s/agents-%s.sh', localdir, image.uuid); if (fs.existsSync(filepath)) { progress('Using agent installer %s ' + 'from previous download', filepath); next(); } else { downloadInstallerImage(next); } } }, function copyFileToAssetsDir(_, next) { if (justDownload) { return next(); } var assetsdir = '/usbkey/extra/agents'; var argv = ['cp', filepath, assetsdir]; mkdirp.sync(assetsdir); common.execFilePlus({ argv: argv, log: self.log }, function (err, stderr, stdout) { self.log.trace({ cmd: argv.join(' '), err: err, stdout: stdout, stderr: stderr }, 'ran cp command'); if (err) { return next(new errors.InternalError({ message: format('error copying shar file to %s', assetsdir), cmd: argv.join(' '), stdout: stdout, stderr: stderr, cause: err })); } next(); }); }, function createLatestSymlink(_, next) { var argv = [ 'rm', '-f', '/usbkey/extra/agents/latest' ]; common.execFilePlus({ argv: argv, log: self.log }, function (err1, stdout1, stderr1) { self.log.trace({ cmd: argv.join(' '), err: err1, stdout: stdout1, stderr: stderr1 }, 'rm -f latest cmd'); if (err1) { return next(err1); } fname = path.basename(filepath); argv = ['ln', '-s', fname, 'latest']; common.execFilePlus({ argv: argv, cwd: '/usbkey/extra/agents', log: self.log }, function (err2, stdout2, stderr2) { self.log.trace({ cmd: argv.join(' '), err: err2, stdout: stdout2, stderr: stderr2 }, 'ln -s latest cmd'); if (err2) { return next(err2); } return next(); }); }); }, function runUrQueue(_, next) { if (justDownload) { deleteOnFinish = false; return next(); } progress('Running agents installer into %s servers', assignServers.length); var cmd = 'cd /var/tmp;\n' + '[ ! -d /opt/smartdc/agents/lib ] && exit 0;\n' + 'curl -kOs ' + self.config.assets_admin_ip + ':/extra/agents/' + fname + ' && \ \n' + 'bash /var/tmp/' + fname + ' </dev/null >/var/tmp/' + fname + '_install.log 2>&1 && \ \n' + 'echo \'SDC7 agent upgrade\''; self.log.trace({cmd: cmd}, 'Ur Run Queue created'); var queueOpts = { sdcadm: self, log: self.log, progress: progress, command: cmd }; if (process.stderr.isTTY) { var bar = new ProgressBar({ size: assignServers.length, bytes: false, filename: fname }); queueOpts.progbar = bar; } var rq = ur.runQueue(queueOpts, function (err, results) { if (err) { return next(err); } results.forEach(function (re) { if (re.result.exit_status !== 0) { var errMsg = format('Agents update failed in server' + '%s (%s) with error: %j', re.uuid, re.hostname, re.result); errs.push(new errors.UpdateError(errMsg)); } }); rq.close(); if (errs.length) { return next(new errors.MultiError(errs)); } return next(); }); assignServers.forEach(function (s) { rq.add_server(s); }); rq.start(); }, function closeUr(_, next) { if (justDownload) { return next(); } self.ur.close(); next(); }, function doCleanup(_, next) { if (deleteOnFinish) { cleanup(next); } else { next(); } }, // At this point we can consider the update complete. The next step // is just about providing accurate information when listing agent // instances and until we move from update agents using a shar file // to the individual agents update. function refreshSysinfo(_, next) { progress('Reloading servers sysinfo'); self.cnapi.listServers({ setup: true }, function (err, servers_) { if (err) { self.log.error({err: err}, 'CNAPI listServers'); return next(); } runningServers = servers_ || []; // Ignore any server w/o running status: runningServers = runningServers.filter(function (s) { return (s.status === 'running'); }); function upSysinfo(server, cb) { var sPath = format('/servers/%s/sysinfo-refresh', server.uuid); self.cnapi.post({ path: sPath }, {}, function cnapiCb(er2, res) { if (er2) { self.log.error({ err: er2, path: sPath }, 'CNAPI sysinfo-refresh'); } return cb(); }); } var queue = vasync.queue(upSysinfo, 10); queue.push(runningServers); // No need for per task done cb queue.close(); queue.on('end', function done() { progress('sysinfo reloaded for all the running servers'); next(); }); }); }, function refreshConfigAgents(_, next) { progress('Refresh config-agent into all the setup and running' + ' servers'); function refreshCfgAgent(server, cb) { svcadm.svcadmRefresh({ server_uuid: server.uuid, wait: false, fmri: 'config-agent', sdcadm: self, log: self.log }, cb); } var queue = vasync.queue(refreshCfgAgent, 10); queue.push(runningServers); // No need for per task done cb queue.close(); queue.on('end', function done() { progress('config-agent refresh for all the running servers'); next(); }); } ]}, function (err) { if (justDownload) { return callback(); } if (err) { if (!hist) { self.log.warn('History not saved for update-agents'); return callback(err); } hist.error = err; } if (!hist) { self.log.warn('History not saved for update-agents'); return callback(); } self.history.updateHistory(hist, function (err2) { if (err) { return callback(err); } progress('Done.'); if (err2) { return callback(err2); } else { return callback(); } }); }); }; /* * Fetch a given gz-tools tarball image (or if desired, latest), download it, * then do the following: * * - Update SDC zone tools (tools.tar.gz) * - Update GZ scripts * - Update /usbkey/default * - Update cn_tools.tar.gz on all Compute Nodes */ SdcAdm.prototype.updateGzTools = function updateGzTools(options, callback) { assert.object(options, 'options'); assert.string(options.image, 'options.image'); assert.func(options.progress, 'opts.progress'); var self = this; var localdir = '/var/tmp'; var deleteOnFinish = true; var filepath; var image; var sdcZone; var progress = options.progress; var timestamp = Math.floor(new Date().getTime() / 1000); var tmpToolsDir = format('%s/gz-tools', localdir); var justDownload = options.justDownload; // Used by sdcadm history: var changes = []; var hist; function findTarballImageLatest(cb) { var filter = { name: 'gz-tools' }; self.updates.listImages(filter, function (err, images) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } if (Array.isArray(images) && !images.length) { return cb(new errors.UpdateError('no images found')); } common.sortArrayOfObjects(images, ['published_at']); image = images[images.length - 1]; cb(); }); return; } function findTarballImageByUuid(cb) { self.updates.getImage(options.image, function (err, foundImage) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } image = foundImage; cb(); }); } function downloadTarballImage(cb) { progress('Downloading gz-tools image %s (%s) to %s', image.uuid, image.version, filepath); function onImage(err) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } cb(); } self.updates.getImageFile(image.uuid, filepath, onImage); } function updateSdcFiles(cb) { progress('Updating "sdc" zone tools'); vasync.pipeline({funcs: [ function removeSymlink(_, next) { var argv = ['rm', '-rf', '/opt/smartdc/sdc']; common.execFilePlus({argv: argv, log: self.log}, next); }, function reSymlink(_, next) { var argv = [ 'ln', '-s', '/zones/' + sdcZone.uuid + '/root/opt/smartdc/sdc', '/opt/smartdc/sdc' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function decompressTools(_, next) { // tools.tar.gz will be located at $tmpToolsDir/tools.tar.gz var argv = [ '/usr/bin/tar', 'xzof', tmpToolsDir + '/tools.tar.gz', '-C', '/opt/smartdc' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function cleanupSemverFile(_, next) { // Remove semver.js from an old sdc-clients-light version var sverFile = '/opt/smartdc/node_modules/sdc-clients/' + 'node_modules/semver.js'; if (!fs.existsSync(sverFile)) { next(); return; } fs.unlink(sverFile, function (err) { if (err) { self.log.warn(err, 'unlinking %s', sverFile); } next(); }); } ]}, function (err) { cb(err); }); } function updateScripts(cb) { progress('Updating global zone scripts'); vasync.pipeline({funcs: [ function mountUsbKey(_, next) { progress('Mounting USB key'); var argv = ['/usbkey/scripts/mount-usb.sh']; common.execFilePlus({argv: argv, log: self.log}, next); }, function backupScriptsDir(_, next) { var argv = [ 'cp', '-Rp', '/usbkey/scripts', localdir + '/pre-upgrade.scripts.' + timestamp ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function backupToolsFile(_, next) { if (!fs.existsSync('/usbkey/tools.tar.gz')) { next(); return; } var argv = [ 'cp', '/usbkey/tools.tar.gz', localdir + '/pre-upgrade.tools.' + timestamp + '.tar.gz' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function removeScriptsDir(_, next) { var argv = [ 'rm', '-rf', '/mnt/usbkey/scripts' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyScriptsToUSBKey(_, next) { var argv = [ 'cp', '-Rp', tmpToolsDir + '/scripts', '/mnt/usbkey/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyToolsToUSBKey(_, next) { var argv = [ 'cp', tmpToolsDir + '/tools.tar.gz', '/mnt/usbkey/tools.tar.gz' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyDefaultDirToUsbKey(_, next) { var cmd = ['cp', tmpToolsDir + '/default/*', '/mnt/usbkey/default']; exec(cmd.join(' '), function (err, stdout, stderr) { self.log.trace({cmd: cmd, err: err, stdout: stdout, stderr: stderr}, 'ran cp command'); if (err) { return next(new errors.InternalError({ message: 'error running cp command', cmd: cmd, stdout: stdout, stderr: stderr, cause: err })); } next(); }); }, function rsyncScriptsToCache(_, next) { var argv = [ 'rsync', '-avi', '--exclude', 'private', '--exclude', 'os', '/mnt/usbkey/', '/usbkey/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyJoysetup(_, next) { var argv = [ 'cp', tmpToolsDir + '/scripts/joysetup.sh', '/usbkey/extra/joysetup/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyAgentSetup(_, next) { var argv = [ 'cp', tmpToolsDir + '/scripts/agentsetup.sh', '/usbkey/extra/joysetup/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function unmountUsbKey(_, next) { progress('Unmounting USB key'); var argv = ['/usr/sbin/umount', '/mnt/usbkey']; common.execFilePlus({argv: argv, log: self.log}, next); } ]}, function (err) { cb(err); }); } function updateCnTools(cb) { progress('Updating cn_tools on all compute nodes'); var argv = [ '/usbkey/scripts/update_cn_tools', '-f', tmpToolsDir + '/cn_tools.tar.gz' ]; common.execFilePlus({argv: argv, log: self.log}, cb); } function cleanup(cb) { progress('Cleaning up gz-tools tarball'); fs.unlink(filepath, function (err) { if (err) { self.log.warn(err, 'unlinking %s', filepath); } cb(); }); } vasync.pipeline({funcs: [ function findImage(_, next) { if (options.image === 'latest') { findTarballImageLatest(next); // Check if the value of the parameter `image` is a file } else if (fs.existsSync(options.image)) { filepath = options.image; deleteOnFinish = false; next(); } else { findTarballImageByUuid(next); } }, function ensureSdcInstance(_, next) { var filters = { state: 'active', owner_uuid: self.config.ufds_admin_uuid, 'tag.smartdc_role': 'sdc' }; self.vmapi.listVms(filters, function (vmsErr, vms) { if (vmsErr) { return next(vmsErr); } if (Array.isArray(vms) && !vms.length) { return next(new errors.UpdateError('no "sdc" VM ' + 'instance found')); } sdcZone = vms[0]; return next(); }); }, function saveHistory(_, next) { if (justDownload) { return next(); } changes.push({ service: { name: 'gz-tools' }, type: 'update-service', img: (image ? image : options.image) }); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function downloadTarball(_, next) { if (filepath) { progress('Using gz-tools tarball file %s', filepath); next(); } else { if (image.name !== 'gz-tools' && !options.force) { callback(new errors.UsageError( 'name of image by given uuid is not \'gz-tools\'')); } filepath = format('%s/gz-tools-%s.tgz', localdir, image.uuid); if (fs.existsSync(filepath)) { progress('Using gz-tools tarball file %s ' + 'from previous download', filepath); next(); } else { downloadTarballImage(next); } } }, function decompressTarball(_, next) { if (justDownload) { deleteOnFinish = false; return next(); } var argv = [ '/usr/bin/tar', 'xzvof', filepath, '-C', localdir ]; progress('Decompressing gz-tools tarball'); common.execFilePlus({argv: argv, log: self.log}, next); }, function (_, next) { if (justDownload) { return next(); } updateSdcFiles(next); }, function (_, next) { if (justDownload) { return next(); } updateScripts(next); }, function (_, next) { if (justDownload) { return next(); } updateCnTools(next); }, function (_, next) { if (deleteOnFinish) { cleanup(next); } else { next(); } } ]}, function (err) { if (justDownload) { callback(err); } else if (hist) { if (err) { if (!hist) { self.log.warn('History not saved for update-gz-tools'); return callback(err); } hist.error = err; } if (!hist) { self.log.warn('History not saved for update-gz-tools'); return callback(); } self.history.updateHistory(hist, function (err2) { if (err) { callback(err); } else if (err2) { callback(err2); } else { callback(); } }); } else { callback(err); } }); }; /** * Return an array of candidate images (the full image objects) for a * give service update. If available, the oldest current instance image is * included. * * TODO: support this for a particular instance as well by passing in `inst`. * * @param options {Object} Required. * - service {Object} Required. The service object as from `getServices()`. * - insts {Array} Required. Current DC instances as from `listInsts()`. * @param cb {Function} `function (err, img)` */ SdcAdm.prototype.getCandidateImages = function getCandidateImages(opts, cb) { assert.object(opts, 'opts'); assert.object(opts.service, 'opts.service'); assert.arrayOfObject(opts.insts, 'opts.insts'); assert.func(cb, 'cb'); var self = this; var currImgs = []; var imgs; vasync.pipeline({funcs: [ function getCurrImgs(_, next) { var currImgUuids = {}; opts.insts.forEach(function (inst) { if (inst.service === opts.service.name) { currImgUuids[inst.image] = true; } }); currImgUuids = Object.keys(currImgUuids); if (currImgUuids.length === 0) { // No insts -> use the image_uuid set on the service. assert.ok(opts.service.params.image_uuid, 'service object has no "params.image_uuid": ' + JSON.stringify(opts.service)); currImgUuids.push(opts.service.params.image_uuid); } self.log.debug({currImgUuids: currImgUuids}, 'getCandidateImages: getCurrImgs'); vasync.forEachParallel({inputs: currImgUuids, func: function getImg(imgUuid, nextImg) { self.getImage({uuid: imgUuid}, function (iErr, img) { if (iErr && iErr.body && iErr.body.code === 'ResourceNotFound') { /** * Don't error out for those weird cases where * (a) the image was removed from local imgapi; and * (b) is so old it isn't in the updates server. */ nextImg(); } else if (iErr) { nextImg(iErr); } else { currImgs.push(img); nextImg(); } }); } }, next); }, function getCandidates(_, next) { /** * Which images to consider for an update? Consider a service with * 3 instances at image versions A, A and C. (Note that * `published_at` is the field used to order images with the * same name.) * * Ideally we allow 'B', 'C' and anything after 'C' as candidate * updates. So we'll look for images published after 'A' * (including 'A' to allow same-image updates for dev/testing). */ common.sortArrayOfObjects(currImgs, ['published_at']); var name = self.config.imgNameFromSvcName[opts.service.name]; if (!name) { return next(new errors.InternalError({ message: format('do not know image name for service "%s"', opts.service.name) })); } var filter = { name: name, marker: (currImgs.length > 0 ? currImgs[0].published_at : undefined) }; self.log.debug({filter: filter}, 'getCandidateImages: getCandidates'); self.updates.listImages(filter, function (uErr, followingImgs) { if (uErr) { return next(uErr); } // TOOLS-745: Validate that the name of the retrieved images // matches the name of the service we're trying to update: followingImgs = followingImgs.filter(function (i) { return (i.name === self.config.imgNameFromSvcName[opts.service.name]); }); if (currImgs.length > 0) { // TODO this is wrong, I think we can drop it now // with marker=published_at imgs = [currImgs[0]].concat(followingImgs); } else { imgs = followingImgs; } next(); }); } ]}, function done(err) { cb(err, imgs); }); }; SdcAdm.prototype.acquireLock = function acquireLock(opts, cb) { assert.object(opts, 'opts'); assert.func(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var self = this; var log = self.log; var acquireLogTimeout = setTimeout(function () { opts.progress('Waiting for sdcadm lock'); }, 1000); log.debug({lockPath: self._lockPath}, 'acquire lock'); lock(self._lockPath, function (lockErr, unlock) { if (acquireLogTimeout) { clearTimeout(acquireLogTimeout); } if (lockErr) { cb(new errors.InternalError({ message: 'error acquiring lock', lockPath: self._lockPath, cause: lockErr })); return; } log.debug({lockPath: self._lockPath}, 'acquired lock'); cb(null, unlock); }); }; SdcAdm.prototype.releaseLock = function releaseLock(opts, cb) { assert.object(opts, 'opts'); assert.func(opts.unlock, 'opts.unlock'); assert.func(cb, 'cb'); var self = this; var log = this.log; if (!opts.unlock) { return cb(); } log.debug({lockPath: self._lockPath}, 'releasing lock'); opts.unlock(function (unlockErr) { if (unlockErr) { cb(new errors.InternalError({ message: 'error releasing lock', lockPath: self._lockPath, cause: unlockErr })); return; } log.debug({lockPath: self._lockPath}, 'released lock'); cb(); }); }; /** * Generate an update plan according to the given changes. * The caller should be holding a `<SdcAdm>.acquireLock()`. * * `changes` is an array of objects of the following form: * * 1. create-instance: 'type:create-instance' and 'service' and 'server' * 2. agent delete-instance: * 'type:delete-instance' and 'service' and 'server' * or * 'type:delete-instance' and 'instance' * Where 'instance' for an agent is '$server/$service', e.g. * 'c26c3aba-405b-d04b-b51d-5a68d8f950d7/provisioner'. * 3. vm delete-instance: 'type:delete' and 'instance' (the VM uuid or alias) * 4. delete-service: 'type:delete-service' and 'service' * 5. vm update-instance: 'instance', optional 'type:update-instance' * 6. agent update-instance: * 'service' and 'server' * or * 'instance' * with optional 'type:update-instance'. * 7. update-service: 'service', optional 'type:update-service'. * * Except for 'delete-service', 'image' is optional for all, otherwise the * latest available image is implied. * * @param options {Object} Required. * - changes {Array} Required. The update spec array of objects. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * - forceDataPath {Boolean} Optional. Allows data path components to be * updated. Currently: portolan. * - forceRabbitmq {Boolean} Optional. Allow rabbitmq to be updated, as it * will not be by default * - forceSameImage {Boolean} Optional. Allow an update to proceed even * if the target image is the same as that of the current instance(s). * - skipHACheck {Boolean} Optional. Allow instance creation even * if the service is not supossed to have more than one instance * - justImages {Boolean} Optional. Generate a plan that just imports * the images. Default false. * - updateAll {Boolean} Optional. genUpdatePlan will produce a less noisy * output when updating all existing instances. Default false. * @param cb {Function} Callback of the form `function (err, plan)`. */ SdcAdm.prototype.genUpdatePlan = function genUpdatePlan(options, cb) { assert.object(options, 'options'); assert.arrayOfObject(options.changes, 'options.changes'); assert.optionalFunc(options.progress, 'options.progress'); assert.optionalBool(options.justImages, 'options.justImages'); assert.optionalBool(options.updateAll, 'options.updateAll'); assert.optionalBool(options.forceDataPath, 'opts.forceDataPath'); assert.optionalBool(options.forceRabbitmq, 'options.forceRabbitmq'); assert.optionalBool(options.forceSameImage, 'options.forceSameImage'); assert.optionalString(options.uuid, 'options.uuid'); assert.optionalBool(options.keepAllImages, 'options.keepAllImages'); assert.optionalBool(options.noVerbose, 'options.noVerbose'); // Create instance: assert.optionalBool(options.skipHACheck, 'options.skipHACheck'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var justImages = Boolean(options.justImages); var updateAll = Boolean(options.updateAll); var changes = common.deepObjCopy(options.changes); var servers; var serverFromUuidOrHostname; var svcs; var svcFromName; var insts; var plan; vasync.pipeline({funcs: [ /** * Basic validation of keys of the changes. Validation of values is * later. */ function validateChanges(_, next) { var errs = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; var repr = JSON.stringify(change); if (change.image) { validateString(change.image, '"image" in ' + repr); } if (change.type === 'create') { // 1. create-instance validateString(change.service, '"service" in ' + repr); validateString(change.server, '"server" in ' + repr); validateKeys(['type', 'server', 'service', 'image'], change, repr); } else if (change.type === 'delete' && change.service && change.server) { // 2. agent delete-instance validateString(change.service, '"service" in ' + repr); validateString(change.server, '"server" in ' + repr); validateKeys(['type', 'server', 'service', 'image'], change, repr); } else if (change.type === 'delete') { // 2. agent delete-instance // 3. vm delete-instance validateString(change.instance, '"instance" in ' + repr); validateKeys(['type', 'instance', 'image'], change, repr); } else if (change.type === 'delete-service') { // 4. delete-service validateString(change.service, '"service" in ' + repr); validateKeys(['type', 'service'], change, repr); } else if (change.service && change.server) { // 6. agent update-instance if (change.type && change.type !== 'update-instance') { errs.push(new errors.ValidationError( 'invalid type "update-instance" change in ' + repr)); } else { change.type = 'update-instance'; } validateString(change.service, '"service" in ' + repr); validateString(change.server, '"server" in ' + repr); validateKeys(['type', 'server', 'service', 'image'], change, repr); } else if (change.instance) { // 5. vm update-instance // 6. agent update-instance if (change.type && change.type !== 'update-instance') { errs.push(new errors.ValidationError( 'invalid type "update-instance" change in ' + repr)); } else { change.type = 'update-instance'; } validateString(change.instance, '"instance" in ' + repr); validateKeys(['type', 'instance', 'image'], change, repr); } else if (change.service) { // 7. update-service if (change.type && change.type !== 'update-service') { errs.push(new errors.ValidationError( 'invalid type "update-service" change in ' + repr)); } else { change.type = 'update-service'; } validateString(change.service, '"service" in ' + repr); validateKeys(['type', 'service', 'image'], change, repr); } else { errs.push(new errors.ValidationError( 'invalid change: ' + repr)); } } if (errs.length === 1) { next(errs[0]); } else if (errs.length > 1) { next(new errors.MultiError(errs)); } else { next(); } function validateString(value, msg) { if (typeof (value) !== 'string') { errs.push(new errors.ValidationError( msg + ' (string) is required')); } } function validateKeys(allowed, change_, repr_) { var extraKeys = Object.keys(change_).filter(function (k) { return !~allowed.indexOf(k); }); if (extraKeys.length) { errs.push(new errors.ValidationError(format( 'invalid extra fields "%s" in %s', extraKeys.join('", "'), repr_))); } } }, function getServers(_, next) { self.cnapi.listServers({ agents: true }, function (err, servers_) { servers = servers_ || []; serverFromUuidOrHostname = {}; for (var i = 0; i < servers.length; i++) { serverFromUuidOrHostname[servers[i].uuid] = servers[i]; serverFromUuidOrHostname[servers[i].hostname] = servers[i]; } next(err); }); }, function getSvcs(_, next) { self.getServices({}, function (err, svcs_) { svcs = svcs_ || []; svcFromName = {}; for (var i = 0; i < svcs.length; i++) { svcFromName[svcs[i].name] = svcs[i]; } next(err); }); }, function getInsts(_, next) { self.listInsts(function (err, insts_) { insts = insts_; next(err); }); }, /** * Normalize fields in each change in the `changes` array from the * convenience inputs (e.g. service="imgapi") to full details * (e.g. service=<the full imgapi SAPI service object>). */ function normalizeChanges(_, next) { if (updateAll) { var serviceNames = changes.map(function (ch) { return ch.service; }).join(', '); if (!options.noVerbose) { progress('Finding candidate update images for %s ' + 'services (%s).', changes.length, serviceNames); } } vasync.forEachParallel({inputs: changes, func: function resolveChange(ch, nextChange) { var changeRepr = JSON.stringify(ch); var i, found; if (ch.service) { if (!svcFromName[ch.service]) { return nextChange(new errors.UpdateError(format( 'unknown service "%s" from %s', ch.service, changeRepr))); } else { ch.service = svcFromName[ch.service]; } } if (ch.uuid) { found = false; for (i = 0; i < insts.length; i++) { if (insts[i].uuid === ch.uuid) { ch.instance = insts[i]; found = true; break; } } if (!found) { return nextChange(new errors.UpdateError(format( 'unknown SDC instance uuid "%s" from %s', ch.uuid, changeRepr))); } } else if (ch.alias) { found = false; for (i = 0; i < insts.length; i++) { if (insts[i].alias === ch.alias) { ch.instance = insts[i]; found = true; break; } } if (!found) { return nextChange(new errors.UpdateError(format( 'unknown SDC instance alias "%s" from %s', ch.alias, changeRepr))); } } if (!ch.service) { p('TODO instance (what is service?):', ch.instance, ch); throw new Error('TODO'); // ch.server = TODO; } if (ch.server) { found = false; for (i = 0; i < servers.length; i++) { if (servers[i].uuid === ch.server || servers[i].hostname === ch.server) { found = true; break; } } if (!found) { return nextChange(new errors.UpdateError(format( 'unknown SDC server "%s" from %s', ch.server, changeRepr))); } } // All candidate images to `ch.images`. Just the single // image if one was specified. if (ch.image) { self.getImage({uuid: ch.image}, function (iErr, img) { if (iErr) { return nextChange(new errors.UpdateError( iErr, format('unknown image "%s" from %s', ch.image, changeRepr))); } ch.images = [img]; delete ch.image; nextChange(); }); } else { if (!updateAll && !options.noVerbose) { progress('Finding candidate update images ' + 'for the "%s" service.', ch.service.name); } self.getCandidateImages({ service: ch.service, insts: insts }, function (iErr, imgs) { if (iErr) { return nextChange(iErr); } ch.images = imgs; log.debug({serviceName: ch.service.name}, '%d candidate images (including current)', imgs.length); nextChange(); }); } } }, next); }, /** * Kinds of conflicts: * - action on a service *and* an instance of the same service * - two actions on the same service * - two actions on the same instance */ function checkForConflictingChanges(_, next) { function reprFromChange(ch_) { return JSON.stringify({ type: ch_.type, service: ch_.service.name, instance: ch_.instance && ch_.instance.instance }); } var changeFromSvc = {}; var changeFromInst = {}; var i, ch, typeTarg, svc; for (i = 0; i < changes.length; i++) { ch = changes[i]; // e.g. 'update-service' -> 'service' // (Some instance changes like 'delete' or 'create' do not // include the two pieces). typeTarg = ch.type.split('-')[1] || 'instance'; if (typeTarg === 'service') { svc = ch.service.name; if (changeFromSvc[svc]) { return next(new errors.UpdateError(format( 'conflict: cannot make multiple changes to the ' + 'same service: %s and %s', reprFromChange(ch), reprFromChange(changeFromSvc[svc])))); } changeFromSvc[svc] = ch; } else { assert.equal(typeTarg, 'instance'); var inst = (ch.instance) ? ch.instance.instance : null; if (changeFromInst[inst]) { return next(new errors.UpdateError(format( 'conflict: cannot make multiple changes to the ' + 'same instance: %s and %s', reprFromChange(ch), reprFromChange(changeFromInst[inst])))); } changeFromInst[inst] = ch; } } for (i = 0; i < changes.length; i++) { ch = changes[i]; typeTarg = ch.type.split('-')[1] || 'instance'; if (typeTarg === 'instance') { svc = ch.service.name; if (changeFromSvc[svc]) { return next(new errors.UpdateError(format( 'conflict: cannot make changes to a service and ' + 'an instance of that service: %s and %s', reprFromChange(ch), reprFromChange(changeFromSvc[svc])))); } } } next(); }, /** * Drop service or inst updates that have no available update * candidates. */ function dropNoops(_, next) { changes = changes.filter(function (ch) { if (ch.type === 'update-service' || ch.type === 'update-instance') { if (ch.images.length === 0) { // No available update candidates were found. log.debug({change: ch}, 'dropNoop: no update candidates'); return false; } // Exclude update to the same image as all current insts, // unless --force-same-image. if (!options.forceSameImage) { var currImgUuids = {}; insts.forEach(function (inst) { if (inst.service === ch.service.name) { currImgUuids[inst.image] = true; } }); currImgUuids = Object.keys(currImgUuids); if (currImgUuids.length === 0) { // No insts -> use the image_uuid set on the // service. assert.ok(ch.service.params.image_uuid, 'service object has no "params.image_uuid": ' + JSON.stringify(ch.service)); currImgUuids.push(ch.service.params.image_uuid); } if (currImgUuids.length === 1) { var sansCurr = ch.images.filter(function (img) { return (img.uuid !== currImgUuids[0]); }); if (sansCurr.length === 0) { log.debug( {change: ch, currImgUuids: currImgUuids}, 'dropNoop: same image as all insts'); return false; } } } } return true; }); next(); }, /** * This is where we use inter-image dependencies to (a) resolve * candidate `images` for each change down to a single `image`, and * (b) add additional updates if required. * * We don't yet support deps (see: sdc-update project M9), so the * only step here is to select the latest candidate image. */ function resolveDeps(_, next) { log.debug({changes: changes}, 'resolveDeps'); for (var i = 0; i < changes.length; i++) { var ch = changes[i]; if (!ch.image && ch.images.length) { assert.arrayOfObject(ch.images, 'changes['+i+'].images'); // Assuming that `ch.images` is already sorted by // `published_at`. ch.images.sort(function (a, b) { return common.cmp(a.published_at, b.published_at); }); ch.image = ch.images[ch.images.length - 1]; } if (!options.keepAllImages) { delete ch.images; } } next(); }, function disallowRabbitmqUpdates(_, next) { for (var i = 0; i < changes.length; i++) { var ch = changes[i]; if (ch.service && ch.service.name === 'rabbitmq' && !options.forceRabbitmq) { var changeRepr = JSON.stringify({ type: ch.type, service: ch.service.name, instance: ch.instance && ch.instance.instance }); return next(new errors.UpdateError(format( 'rabbitmq updates are locked: %s ' + '(use --force-rabbitmq flag)', changeRepr))); } } next(); }, function disallowDataPathUpdates(_, next) { var dataPath = ['portolan']; for (var i = 0; i < changes.length; i++) { var ch = changes[i]; if (ch.service && dataPath.indexOf(ch.service.name) !== -1 && !options.forceDataPath) { var changeRepr = JSON.stringify({ type: ch.type, service: ch.service.name, instance: ch.inst && ch.instance.instance }); return next(new errors.UpdateError(format( '%s updates are locked: %s ' + '(use --force-data-path flag)', ch.service.name, changeRepr))); } } next(); }, function ensureVmMinPlatform(_, next) { var ch, server; var errs = []; for (var i = 0; i < changes.length; i++) { ch = changes[i]; if (ch.service.type !== 'vm') { continue; } if (ch.type === 'update-service') { for (var j = 0; j < insts.length; j++) { var inst = insts[j]; if (inst.service === ch.service.name) { server = serverFromUuidOrHostname[inst.server]; if (server.current_platform < self.config.vmMinPlatform) { errs.push(new errors.UpdateError(format( 'insufficient platform for service "%s" ' + 'instance "%s" on server "%s" (current ' + 'platform is "%s", require minimum "%s")', inst.service, inst.instance, inst.server, server.current_platform, self.config.vmMinPlatform))); } } } } else if (ch.type === 'update-instance') { throw new Error('TODO'); } else if (ch.type === 'create-instance') { server = serverFromUuidOrHostname[ch.server]; throw new Error('TODO'); } } if (errs.length) { var er = (errs.length === 1) ? errs[0] : new errors.MultiError(errs); next(er); } else { next(); } }, function minImageBuildDateFromSvcName(_, next) { if (options.forceBypassMinImage) { return next(); } var ch, server; var errs = []; for (var i = 0; i < changes.length; i++) { ch = changes[i]; if (ch.service.type !== 'vm') { continue; } if (ch.type === 'update-service') { for (var j = 0; j < insts.length; j++) { var inst = insts[j]; if (inst.service !== ch.service.name) { continue; } if (!self.config.svcMinImages[inst.service]) { continue; } var minImg = self.config.svcMinImages[inst.service]; if (!inst.version) { var msg = format('Unknown image ' + 'version for service "%s". Cannot evaluate ' + 'if minimal requirements for update are met ' + 'by the current image. This can be fixed ' + 'by re-importing the image into the DC via:' + '\n\n\tsdc-imgadm '+ 'import %s -s https://updates.joyent.com?' + 'channel=*', inst.service, inst.image); errs.push(new errors.UpdateError(msg)); continue; } var parts = inst.version.split('-'); var curImg = parts[parts.length - 2]; if (minImg > curImg) { errs.push(new errors.UpdateError(format( 'image for service "%s" is too old for ' + 'sdcadm update (min image build date ' + 'is "%s" current image build date is "%s")', inst.service, minImg, curImg ))); } } } else if (ch.type === 'update-instance') { throw new Error('TODO'); } else if (ch.type === 'create-instance') { server = serverFromUuidOrHostname[ch.server]; console.log(server); // shut make check up about unused var throw new Error('TODO'); } } if (errs.length) { var er = (errs.length === 1) ? errs[0] : new errors.MultiError(errs); next(er); } else { next(); } }, function createPlan(_, next) { log.debug({changes: changes}, 'createPlan'); var targ = common.deepObjCopy(insts); for (var i = 0; i < changes.length; i++) { var ch = changes[i]; switch (ch.type) { case 'update-service': for (var j = 0; j < targ.length; j++) { var inst = targ[j]; if (inst.service === ch.service.name) { inst.image = ch.image.uuid; inst.version = ch.image.version; } } break; case 'create': // Create instance for an existing service: if (options.skipHACheck) { ch.force = true; } break; // TODO: other change types default: return next(new errors.InternalError({ message: 'unknown ch.type: ' + ch.type })); } } plan = new UpdatePlan({ curr: insts, targ: targ, changes: changes, justImages: justImages }); next(); }, function determineProcedures(_, next) { procedures.coordinatePlan({ plan: plan, sdcadm: self, serverFromUuidOrHostname: serverFromUuidOrHostname, log: log, progress: progress, noVerbose: options.noVerbose }, function (err, procs_) { plan.procs = procs_; next(err); }); } ]}, function finishUp(err) { cb(err, plan); }); }; SdcAdm.prototype.summarizePlan = function summarizePlan(options) { assert.object(options, 'options'); assert.object(options.plan, 'options.plan'); assert.optionalFunc(options.progress, 'options.progress'); var summary = options.plan.procs.map( function (proc) { return proc.summarize(); }).join('\n'); options.progress(common.indent(summary)); }; /** * Execute an update plan. * The caller should be holding a `<SdcAdm>.acquireLock()`. * * @param options {Object} Required. * - plan {Object} Required. The update plan as returned by * `genUpdatePlan`. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * - dryRun {Boolean} Optional. Default false. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.execUpdatePlan = function execUpdatePlan(options, cb) { assert.object(options, 'options'); assert.object(options.plan, 'options.plan'); assert.optionalFunc(options.progress, 'options.progress'); assert.optionalBool(options.dryRun, 'options.dryRun'); assert.optionalString(options.uuid, 'options.uuid'); // We need a pointer to the update directory when we're trying to rollback: assert.optionalString(options.upDir, 'options.upDir'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var plan = options.plan; var rollback = plan.rollback || false; var start = new Date(); var wrkDir; var hist; vasync.pipeline({funcs: [ function createWrkDir(_, next) { var stamp = sprintf('%d%02d%02dT%02d%02d%02dZ', start.getUTCFullYear(), start.getUTCMonth()+1, start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds()); wrkDir = (rollback ? '/var/sdcadm/rollbacks/' : '/var/sdcadm/updates/' ) + stamp; progress('Create work dir: ' + wrkDir); if (options.dryRun) { return next(); } mkdirp(wrkDir, function (err) { if (err) { next(new errors.InternalError({ message: 'error creating work dir: ' + wrkDir, cause: err })); return; } next(); }); }, function savePlan(_, next) { if (options.dryRun) { return next(); } var planFile = path.resolve(wrkDir, 'plan.json'); fs.writeFile(planFile, plan.serialize(), 'utf8', function (err) { if (err) { return next(new errors.InternalError({ cause: err, message: 'error saving update plan: ' + planFile })); } next(); }); }, function saveBeginningToHistory(_, next) { if (options.dryRun || options.justImages) { return next(); } var obj = { changes: plan.changes }; if (options.uuid) { obj.uuid = options.uuid; } if (options.dryRun) { return next(); } self.history.saveHistory(obj, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function execProcedures(_, next) { if (options.dryRun) { return next(); } vasync.forEachPipeline({ inputs: plan.procs, func: function execProc(proc, nextProc) { log.debug({summary: proc.summarize()}, 'execProc'); proc.execute({ sdcadm: self, plan: plan, progress: progress, log: log, wrkDir: wrkDir, upDir: options.upDir }, nextProc); } }, next); } ]}, function (err) { if (options.dryRun || options.justImages) { return cb(err); } // Add error to history in case the update execution failed: if (err) { // TOOLS-879: sdcadm update should tell user about the error: progress('Update error: %j', err); if (!hist) { self.log.warn('History not saved for update'); return cb(err); } hist.error = err; } if (!hist) { self.log.warn('History not saved for update'); return cb(); } // No need to add `history.finished` here, History instance will handle self.history.updateHistory(hist, function (err2, hist2) { if (err) { cb(err); } else if (err2) { cb(err2); } else { cb(); } }); }); }; /** * Update to the latest available sdcadm package. * * TODO: * - support passing in a package UUID to which to update * * @param options {Object} Required. * - allowMajorUpdate {Boolean} Optional. Default false. By default * self-update will only consider versions of the same major version. * - dryRun {Boolean} Optional. Default false. Go through the motions * without actually updating. * - progress {Function} Optional. A function that is called * with progress messages. Called as `progress(<string>)`. E.g. passing * console.log is legal. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.selfUpdate = function selfUpdate(options, cb) { assert.object(options, 'options'); assert.optionalBool(options.allowMajorUpdate, 'options.allowMajorUpdate'); assert.optionalBool(options.dryRun, 'options.dryRun'); assert.optionalFunc(options.progress, 'options.progress'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var unlock; var dryRunPrefix = (options.dryRun ? '[dry-run] ' : ''); var currVer = pkg.version; var currBuildtime; var updateManifest; var installerPath; var start; var wrkDir; var hist; var changes = [ { type: 'service', service: { type: 'service', name: 'sdcadm', version: currVer } }]; vasync.pipeline({funcs: [ function getLock(_, next) { if (options.dryRun) { return next(); } self.acquireLock({progress: progress}, function (lockErr, unlock_) { unlock = unlock_; next(lockErr); }); }, function setStart(_, next) { // Set start time after getting lock to avoid collisions in wrkDir. start = new Date(); next(); }, function getCurrBuildtime(_, next) { // SDC buildstamps are '$branch-$buildtime-g$sha'. The '$branch' // can have hyphens in it. var buildstampPath = path.resolve(__dirname, '..', 'etc', 'buildstamp'); fs.readFile(buildstampPath, 'utf8', function (err, data) { if (err) { next(new errors.InternalError({ message: 'error getting current buildstamp', path: buildstampPath, cause: err })); return; } var parts = data.trim().split(/-/g); // Drop possible '-dirty' on the buildstamp. if (parts[parts.length - 1] === 'dirty') { parts.pop(); } currBuildtime = parts[parts.length - 2]; changes[0].service.build = data.trim(); next(); }); }, function findLatestSdcAdm(_, next) { var filters = { name: 'sdcadm' }; self.updates.listImages(filters, function (err, candidates) { if (err) { return next(new errors.SDCClientError(err, 'updates')); } // Filter out versions before the current. candidates = candidates.filter(function dropLowerVer(c) { if (semver.lt(c.version, currVer)) { //log.trace({candidate: c, currVer: currVer}, // 'drop sdcadm candidate (lower ver)'); return false; } return true; }); // Unless `allowMajorUpdate`, filter out major updates (and // warn). if (!options.allowMajorUpdate) { var currMajor = currVer.split(/\./)[0] + '.x'; var droppedVers = []; candidates = candidates.filter(function dropMajor(c) { var drop = !semver.satisfies(c.version, currMajor); if (drop) { droppedVers.push(c.version); log.trace({candidate: c, currMajor: currMajor}, 'drop sdcadm candidate (major update)'); } return !drop; }); if (droppedVers.length) { droppedVers.sort(semver.compare); progress('Skipping available major sdcadm ' + 'update, version %s (use --allow-major-update ' + 'to allow)', droppedVers[droppedVers.length - 1]); } } // Filter out buildstamps <= the current (to exclude // earlier builds at the same `version`). candidates = candidates.filter(function dropLowerStamp(c) { var buildtime = c.tags.buildstamp.split(/-/g) .slice(-2, -1)[0]; if (buildtime <= currBuildtime) { log.trace({candidate: c, buildtime: buildtime, currBuildtime: currBuildtime}, 'drop sdcadm candidate (<= buildtime)'); return false; } return true; }); // Sort by (version, publish date) and select the latest if (candidates.length) { candidates.sort(function (a, b) { var ver = semver.compare(a.version, b.version); if (ver) { return ver; } var aParts = a.tags.buildstamp.split('-'); var bParts = b.tags.buildstamp.split('-'); var aStamp = aParts[aParts.length - 2]; var bStamp = bParts[bParts.length - 2]; if (aStamp > bStamp) { return 1; } else if (aStamp < bStamp) { return -1; } else { return 0; } }); updateManifest = candidates[candidates.length - 1]; changes[0].image = updateManifest; progress('%sUpdate to sdcadm %s (%s)', dryRunPrefix, updateManifest.version, updateManifest.tags.buildstamp); } else { var ch = self.updates.channel; progress('Already up-to-date (using %s update channel).', ch ? '"'+ch+'"' : 'default'); } next(); }); }, function saveChangesToHistory(_, next) { if (!updateManifest || options.dryRun) { return next(); } self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function downloadInstaller(_, next) { if (!updateManifest) { return next(); } progress('%sDownload update from %s', dryRunPrefix, self.config.updatesServerUrl); if (options.dryRun) { return next(); } // TODO progress bar on this installerPath = '/var/tmp/sdcadm-' + updateManifest.uuid; self.updates.getImageFile(updateManifest.uuid, installerPath, function (downloadErr) { if (downloadErr) { next(new errors.InternalError({ message: 'error downloading sdcadm package', updatesServerUrl: self.config.updatesServerUrl, uuid: updateManifest.uuid, cause: downloadErr })); return; } fs.chmod(installerPath, 0755, function (chmodErr) { if (chmodErr) { next(new errors.InternalError({ message: 'error chmoding sdcadm installer', path: installerPath, cause: chmodErr })); return; } next(); }); }); }, function createWrkDir(_, next) { if (!updateManifest) { return next(); } var stamp = sprintf('%d%02d%02dT%02d%02d%02dZ', start.getUTCFullYear(), start.getUTCMonth()+1, start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds()); wrkDir = '/var/sdcadm/self-updates/' + stamp; mkdirp(wrkDir, function (err) { if (err) { next(new errors.InternalError({ message: 'error creating work dir: ' + wrkDir, cause: err })); return; } next(); }); }, function runInstaller(_, next) { if (!updateManifest) { return next(); } progress('%sRun sdcadm installer (log at %s/install.log)', dryRunPrefix, wrkDir); if (options.dryRun) { return next(); } var cmd = format('%s >%s/install.log 2>&1', installerPath, wrkDir); var env = common.objCopy(process.env); env.TRACE = '1'; env.SDCADM_LOGDIR = wrkDir; // bwcompat for sdcadm <1.2.0 installers env.SDCADM_WRKDIR = wrkDir; var execOpts = {env: env}; log.trace({cmd: cmd}, 'run sdcadm installer'); exec(cmd, execOpts, function (err, stdout, stderr) { log.trace({cmd: cmd, err: err, stdout: stdout, stderr: stderr}, 'ran sdcadm installer'); if (err) { // TODO: The installer *does* typically restore the old one // on failure. There is a swap (two `mv`s) during which a // crash will leave in inconsistent state. We could check // for that here and cleanup, or just warn about the // situation. return next(new errors.InternalError({ message: 'error running sdcadm installer', cmd: cmd, stdout: stdout, stderr: stderr, cause: err })); } next(); }); } ]}, function finishUp(err) { vasync.pipeline({funcs: [ function dropLock(_, next) { if (options.dryRun) { return next(); } self.releaseLock({unlock: unlock}, next); }, function updateHist(_, next) { if (!updateManifest || options.dryRun) { return next(); } // Add error to history in case the update execution failed: if (err) { if (!hist) { self.log.warn('History not set for self-update'); return next(err); } hist.error = err; } if (!hist) { self.log.warn('History not set for self-update'); return next(); } // No need to add `history.finished` here: self.history.updateHistory(hist, function (err2, hist2) { if (err2) { next(err2); } else { next(); } }); }, function noteCompletion(_, next) { if (!updateManifest || err) { return next(); } progress('%sUpdated to sdcadm %s (%s, elapsed %ss)', dryRunPrefix, updateManifest.version, updateManifest.tags.buildstamp, Math.floor((Date.now() - start) / 1000)); next(); } ]}, function done(finishUpErr) { // We shouldn't ever get a `finishUpErr`. Let's be loud if we do. if (finishUpErr) { log.fatal({err: finishUpErr}, 'unexpected error finishing up self-update'); } cb(err || finishUpErr); }); }); }; SdcAdm.prototype._dcMaintInfoPath = '/var/sdcadm/dc-maint.json'; /** * Maintenance mode current status. * * @param cb {Function} Callback of the form `function (err, status)`. * where `status` is an object like the following: * {maint: false} // not in maint mode * {maint: true} // in maint mode, don't have start time * {maint: true, startTime: <date>} */ SdcAdm.prototype.dcMaintStatus = function dcMaintStatus(cb) { assert.func(cb, 'cb'); var self = this; var log = self.log; var sdcApp = self.sdc; var services = {}; var maint = false; var cloudapiMaint; var dockerMaint; var startTime; vasync.pipeline({funcs: [ function getCloudapiSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'cloudapi' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } else if (!svcs || svcs.length !== 1) { return next(); } services.cloudapi = svcs[0]; next(); }); }, function getDockerSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'docker' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } else if (!svcs || svcs.length !== 1) { return next(); } services.docker = svcs[0]; next(); }); }, function checkIfInMaint(_, next) { cloudapiMaint = services.cloudapi && services.cloudapi.metadata && services.cloudapi.metadata.CLOUDAPI_READONLY; dockerMaint = services.docker && services.docker.metadata && services.docker.metadata.DOCKER_READONLY; log.debug({cloudapi_maint: cloudapiMaint}, 'maint mode from CLOUDAPI_READONLY'); log.debug({docker_maint: dockerMaint}, 'maint mode from DOCKER_READONLY'); next(); }, /** * Showing the start time is strictly a convenience. */ function loadStartTime(_, next) { if (!cloudapiMaint || !dockerMaint) { return next(); } else { maint = true; } fs.readFile(self._dcMaintInfoPath, 'utf8', function (err, content) { if (err) { // This is a convenience step. Just note this. log.warn({dcMaintInfoPath: self._dcMaintInfoPath, err: err}, 'could not loading dc-maint info file'); } else { try { startTime = JSON.parse(content).startTime; } catch (parseErr) { log.warn(parseErr, 'could not parse dc-maint info file'); } } next(); }); } ]}, function (err) { if (err) { cb(err); } else { var status = {maint: maint}; if (startTime) { status.startTime = startTime; } cb(null, status); } }); }; /** * Enter maintenance mode. * * @param opts {Object} Required. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.dcMaintStart = function dcMaintStart(opts, cb) { assert.object(opts, 'opts'); assert.optionalFunc(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var self = this; var progress = opts.progress || function () {}; var sdcApp = self.sdc; var services = {}; var headnode; var putCloudapiIntoMaint = false; var putDockerIntoMaint = false; var startTime; vasync.pipeline({funcs: [ function getHeadnode(_, next) { self.cnapi.listServers({ headnode: true }, function (err, servers) { if (err) { return next(new errors.SDCClientError(err, 'cnapi')); } headnode = servers[0]; return next(); }); }, function getCloudapiSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'cloudapi' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.cloudapi = svcs && svcs.length && svcs[0]; next(); }); }, function getDockerSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'docker' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.docker = svcs && svcs.length && svcs[0]; next(); }); }, function getSapiInstances(_, next) { progress('Getting SDC\'s sapi instances from SAPI'); var keys = Object.keys(services); vasync.forEachParallel({ inputs: keys, func: function (key, feNext) { var serviceUuid = services[key].uuid; self.sapi.listInstances({ service_uuid: serviceUuid }, function (instErr, insts) { if (instErr) { return feNext(instErr); } if (!insts.length) { progress('No ' + key + ' instances to update'); delete services[key]; feNext(); return; } services[key].zone = insts[0]; return feNext(); }); }}, function (err) { next(err); }); }, function checkIfCloudapiInMaint(_, next) { if (services.cloudapi) { if (services.cloudapi.metadata.CLOUDAPI_READONLY === true) { progress('Cloudapi service already in read-only mode'); } else { putCloudapiIntoMaint = true; } } next(); }, function checkIfDockerInMaint(_, next) { if (services.docker) { if (services.docker.metadata.DOCKER_READONLY === true) { progress('Docker service already in read-only mode'); } else { putDockerIntoMaint = true; } } next(); }, function setCloudapiReadonly(_, next) { if (!putCloudapiIntoMaint) { return next(); } progress('Putting cloudapi in read-only mode'); startTime = new Date(); self.sapi.updateService( services.cloudapi.uuid, { metadata: {CLOUDAPI_READONLY: true } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function setDockerReadonly(_, next) { if (!putDockerIntoMaint) { return next(); } progress('Putting docker in read-only mode'); startTime = new Date(); self.sapi.updateService( services.docker.uuid, { metadata: { DOCKER_READONLY: true } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function maybeRefreshCloudapiConfigAgent(_, next) { var zone = services.cloudapi && services.cloudapi.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, function maybeRefreshDockerConfigAgent(_, next) { var zone = services.docker && services.docker.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, /** * TODO: add readonly status to /--ping on cloudapi and watch for that. */ function saveStartTime(_, next) { if (!putCloudapiIntoMaint && !putDockerIntoMaint) { return next(); } var info = JSON.stringify({ 'startTime': startTime }, null, 4); fs.writeFile(self._dcMaintInfoPath, info, 'utf8', next); }, function waitForWorkflowDrain(_, next) { progress('Waiting up to 5 minutes for workflow jobs to drain'); var remaining = 60; var MAX_ERRS = 3; var numErrs = 0; setTimeout(pollJobs, 5000); function pollJobs() { remaining--; if (remaining <= 0) { return next(new errors.InternalError({ message: 'timeout waiting for workflow jobs to drain' })); } self.wfapi.listJobs({execution: 'running', limit: 10}, function (rErr, rJobs) { if (rErr) { numErrs++; self.log.error(rErr, 'error listing running jobs'); if (numErrs >= MAX_ERRS) { return next(rErr); } } else if (rJobs.length > 0) { self.log.debug({numJobs: rJobs.length}, 'running jobs'); return setTimeout(pollJobs, 5000); } self.wfapi.listJobs({execution: 'queued', limit: 10}, function (qErr, qJobs) { if (qErr) { numErrs++; self.log.error(qErr, 'error listing queued jobs'); if (numErrs >= MAX_ERRS) { return next(qErr); } } else if (qJobs.length > 0) { self.log.debug({numJobs: qJobs.length}, 'queued jobs'); return setTimeout(pollJobs, 5000); } progress('Workflow cleared of running and queued jobs'); next(); }); }); } } ]}, cb); }; /** * Leave maintenance mode. * * @param opts {Object} Required. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.dcMaintStop = function dcMaintStop(opts, cb) { assert.object(opts, 'opts'); assert.optionalFunc(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = opts.progress || function () {}; var headnode; var sdcApp = self.sdc; var services = {}; var disableCloudapiMaint = false; var disableDockerMaint = false; vasync.pipeline({funcs: [ function getHeadnode(_, next) { self.cnapi.listServers({ headnode: true }, function (err, servers) { if (err) { return next(new errors.SDCClientError(err, 'cnapi')); } headnode = servers[0]; return next(); }); }, function getCloudapiSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'cloudapi' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.cloudapi = svcs && svcs.length && svcs[0]; next(); }); }, function getDockerSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'docker' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.docker = svcs && svcs.length && svcs[0]; next(); }); }, function getSapiInstances(_, next) { progress('Getting SDC\'s sapi instances from SAPI'); var keys = Object.keys(services); vasync.forEachParallel({ inputs: keys, func: function (key, feNext) { var serviceUuid = services[key].uuid; self.sapi.listInstances({ service_uuid: serviceUuid }, function (instErr, insts) { if (instErr) { return feNext(instErr); } if (!insts.length) { progress('No ' + key + ' instances to update'); delete services[key]; feNext(); return; } services[key].zone = insts[0]; return feNext(); }); }}, function (err) { next(err); }); }, function checkIfCloudapiInMaint(_, next) { if (services.cloudapi) { if (services.cloudapi.metadata.CLOUDAPI_READONLY !== true) { progress('Cloudapi service is not in read-only mode'); } else { disableCloudapiMaint = true; } } next(); }, function checkIfDockerInMaint(_, next) { if (services.docker) { if (services.docker.metadata.DOCKER_READONLY !== true) { progress('Docker service is not in read-only mode'); } else { disableDockerMaint = true; } } next(); }, function setCloudapiWriteable(_, next) { if (!disableCloudapiMaint) { return next(); } progress('Taking cloudapi out of read-only mode'); self.sapi.updateService( services.cloudapi.uuid, { metadata: { CLOUDAPI_READONLY: false } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function setDockerWriteable(_, next) { if (!disableDockerMaint) { return next(); } progress('Taking docker out of read-only mode'); self.sapi.updateService( services.docker.uuid, { metadata: { DOCKER_READONLY: false } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function maybeRefreshCloudapiConfigAgent(_, next) { var zone = services.cloudapi && services.cloudapi.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, function maybeRefreshDockerConfigAgent(_, next) { var zone = services.docker && services.docker.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, /** * Note: We aren't waiting for config-agent in the cloudapi instance(s) * to effect this change. TODO: add readonly status to /--ping on * cloudapi and watch for that. ... on all instances? */ function rmInfoFile(_, next) { if (!disableCloudapiMaint && !disableDockerMaint) { return next(); } fs.unlink(self._dcMaintInfoPath, function (err) { if (err) { // The info file is sugar. Don't fail if it isn't there. log.warn({dcMaintInfoPath: self._dcMaintInfoPath, err: err}, 'could not remove dc-maint info file'); } next(); }); } ]}, cb); }; /** * Check SAPI config against system "reality" and print out inconsistencies * * @param cb {Function} Callback of the form `function (err, result)`. */ SdcAdm.prototype.checkConfig = function (opts, cb) { var self = this; // SAPI values for sdc application: var sdc = self.sdc.metadata; // Name of SAPI services for VMs: var services; // Headnode sysinfo: var sysinfo; // External and admin networks: var admin; var external; // Errors: var errs = []; function getSysinfo(_, next) { self.cnapi.listServers({ headnode: true, extras: 'sysinfo' }, function (err, res) { if (err) { return next(err); } sysinfo = (res && res.length > 0 ? res[0].sysinfo : null); Object.keys(sysinfo['Network Interfaces']).filter(function (k) { return (sysinfo['Network Interfaces'][k]['NIC Names'][0] === 'admin'); }).map(function (k) { if (sysinfo['Network Interfaces'][k]['MAC Address'] !== sdc.admin_nic) { errs.push('SAPI sdc admin_nic did not match with GZ ' + 'Admin MAC Address'); } if (sysinfo['Network Interfaces'][k].ip4addr !== sdc.admin_ip) { errs.push('SAPI sdc admin_ip did not match with GZ ' + 'Admin IPv4 Address'); } }); Object.keys(sysinfo['Virtual Network Interfaces']). filter(function (k) { return (k === 'external0'); }).map(function (k) { if (sysinfo['Virtual Network Interfaces'][k].ip4addr !== sdc.external_ip) { errs.push('SAPI sdc external_ip did not match with GZ ' + 'External IPv4 Address'); } }); return next(); }); } function getNetworks(_, next) { self.napi.listNetworks({name: 'admin'}, function (err, res) { if (err) { return next(err); } admin = (res && res.length > 0 ? res[0] : null); if (admin.subnet.split('/')[0] !== sdc.admin_network) { errs.push('SAPI sdc admin_network did not match with value '+ 'defined in NAPI'); } if (admin.netmask !== sdc.admin_netmask) { errs.push('SAPI sdc admin_netmask did not match with value '+ 'defined in NAPI'); } // PEDRO: Note we should stop assuming external network will always // exist and, therefore, shouldn't return error on the next NAPI // call: self.napi.listNetworks({name: 'external'}, function (err2, res2) { if (err2) { return next(err2); } external = (res2 && res2.length > 0 ? res2[0] : null); if (external.subnet && external.subnet.split('/')[0] !== sdc.external_network) { errs.push('SAPI sdc external_network did not match with '+ 'value defined in NAPI'); } if (external.netmask !== sdc.external_netmask) { errs.push('SAPI sdc external_netmask did not match with '+ 'value defined in NAPI'); } if (external.gateway !== sdc.external_gateway) { errs.push('SAPI sdc external_gateway did not match with '+ 'value defined in NAPI'); } if (external.provision_start_ip !== sdc.external_provisionable_start) { errs.push('SAPI sdc external_provisionable_start did not '+ 'match with value defined in NAPI'); } if (external.provision_end_ip !== sdc.external_provisionable_end) { errs.push('SAPI sdc external_provisionable_end did not '+ 'match with value defined in NAPI'); } return next(); }); }); } function getDcFromUfds(_, next) { self.ufds.search('o=smartdc', { scope: 'sub', filter: sprintf('(&(objectclass=datacenter)(datacenter=%s))', self.config.datacenter_name) }, function (err, res) { if (err) { return next(err); } if (!res) { errs.push('No DC information found in UFDS'); return next(); } res.forEach(function (r) { if (r.region !== sdc.region_name) { errs.push(sprintf( 'region did not match with region_name for entry ' + 'with DN: %s', r.dn)); } if (r.datacenter !== sdc.datacenter_name) { errs.push(sprintf( 'data center did not match with datacenter_name for ' + 'entry with DN: %s', r.dn)); } // company_name and location are not required for anything to // work properly, therefore, skipping them here }); return next(); }); } function getUfdsAdmin(_, next) { self.ufds.search('o=smartdc', { scope: 'sub', filter: sprintf('(&(objectclass=sdcperson)(uuid=%s))', self.config.ufds_admin_uuid) }, function (err, res) { if (err) { return next(err); } var ufdsAdmin = (res && res.length > 0 ? res[0] : null); if (!ufdsAdmin) { errs.push('Cannot find UFDS admin user'); } if (ufdsAdmin.login !== sdc.ufds_admin_login) { errs.push('UFDS admin login did not match SAPI ' + 'ufds_admin_login'); } if (ufdsAdmin.email !== sdc.ufds_admin_email) { errs.push('UFDS admin email did not match SAPI ' + 'ufds_admin_email'); } self.ufds.search(sprintf('uuid=%s, ou=users, o=smartdc', self.config.ufds_admin_uuid), { scope: 'sub', filter: sprintf('(objectclass=sdckey)', self.config.ufds_admin_key_fp) }, function (err2, res2) { if (err2) { return next(err2); } if (!res2.length) { errs.push('Cannot find UFDS admin key'); return next(); } var sdcKey = res2.filter(function (k) { return (k.fingerprint === sdc.ufds_admin_key_fingerprint); })[0]; if (!sdcKey) { errs.push('Cannot find UFDS admin key'); return next(); } if (sdcKey.openssh !== sdc.ufds_admin_key_openssh.trim()) { errs.push('UFDS Admin key did not match with SAPI '+ 'ufds_admin_key_openssh'); } return next(); }); }); } // PEDRO: Shall we really care about core zone Admin IP addresses here?: // (Ignoring for now) function getVmsIps(_, next) { var filters = { query: sprintf('(&(tags=*-smartdc_type=core-*)' + '(|(state=running)(state=provisioning)(state=stopped))' + '(owner_uuid=%s))', self.config.ufds_admin_uuid) }; self.vmapi.listVms(filters, function (vmsErr, _vms) { if (vmsErr) { return next(vmsErr); } return next(); }); } self.sapi.listServices({ application_uuid: sdc.uuid }, function (err2, res2) { if (err2) { return cb(err2); } if (!res2.length) { return cb('Cannot find SDC services in SAPI'); } services = res2.filter(function (s) { return (s.type === 'vm'); }).map(function (s) { return (s.name); }); vasync.pipeline({ funcs: [ getSysinfo, getNetworks, getDcFromUfds, getUfdsAdmin, getVmsIps ] }, function (err4, _res) { if (err4) { return cb(err4); } // PEDRO: Note the exceptions listed below. I bet we could // remove most of these variables anyway, and left a single // value for *_pw. services.forEach(function (s) { if (!sdc[s + '_root_pw'] && s !== 'manta' && s !== 'sapi') { errs.push(sprintf('Missing %s_root_pw in SAPI', s)); } if (!sdc[s + '_admin_ips'] && s !== 'cloudapi' && s !== 'manta' && s !== 'sdcsso') { errs.push(sprintf('Missing %s_admin_ips in SAPI', s)); } if (s !== 'manatee' && s !== 'binder' && s !== 'manta' && s !== 'cloudapi') { if (!sdc[s + '_domain']) { errs.push(sprintf('Missing %s_domain in SAPI', s)); } if (!sdc[s.toUpperCase() + '_SERVICE']) { errs.push(sprintf('Missing %s_SERVICE in SAPI', s.toUpperCase())); } } }); // Check that ufds_remote_ip is present if this is not master: if (!sdc.ufds_is_master || sdc.ufds_is_master === 'false') { if (!sdc.ufds_remote_ip) { errs.push('Missing SAPI variable "ufds_remote_ip"'); } } return self.ufds.close(function (err3) { return cb(null, errs); }); }); }); }; /** * Check health of given SAPI instances. * * @param opts {Object} Required. * - insts {Array} Optional. Instance objects as returned by listInsts. * When given, `uuids` will be ignored. * - uuids {Array} Optional. SAPI instance (or service) UUIDs to check. * If not given and insts isn't present, then all SDC instances are * checked. * @param cb {Function} Callback of the form `function (err, results)`. */ SdcAdm.prototype.checkHealth = function checkHealth(opts, cb) { var self = this; assert.object(opts, 'opts'); assert.optionalArrayOfString(opts.uuids, 'opts.uuids'); assert.optionalArrayOfObject(opts.insts, 'opts.insts'); assert.optionalString(opts.type, 'opts.type'); assert.optionalArrayOfString(opts.servers, 'opts.servers'); assert.func(cb, 'cb'); var svcLookup = {}; var uuidLookup; var insts; var headnode; if (opts.insts) { insts = opts.insts; } else if (opts.uuids) { uuidLookup = {}; opts.uuids.forEach(function (id) { uuidLookup[id] = true; }); } // No need to keep these variables global to the whole sdcadm module: var pingPaths = { // vms amon: '/ping', cloudapi: '/--ping', cnapi: '/ping', fwapi: '/ping', imgapi: '/ping', napi: '/ping', papi: '/ping', sapi: '/ping', vmapi: '/ping', workflow: '/ping', // agents firewaller: '/status' }; var pingPorts = { cloudapi: 443, firewaller: 2021 }; // We can ping instances either when we checked for svcs health using // Ur client or when we did straight at the Headnode cmd. Shared code // by these two functions: function _pingInstance(inst, next) { var pingPath = pingPaths[inst.service]; if (!pingPath) { inst.healthy = true; return next(null, inst); } var port = pingPorts[inst.service] || 80; var httpClient = (port === 443 ? https : http); httpClient.get({ hostname: (inst.ip || inst.server_ip), port: port, path: pingPath, agent: false, rejectUnauthorized: false }, function (res) { self.log.debug({ http_response: res.statusCode }, 'HTTP result for ' + inst.instance); inst.healthy = (res.statusCode === 200); if (!inst.healthy) { inst.health_errors = [ { message: 'ping check to ' + inst.ip + ' failed with ' + 'HTTP code ' + res.statusCode } ]; } return next(null, inst); }).once('error', function (e) { inst.healthy = false; inst.health_errors = [ { message: 'ping check to ' + inst.ip + ' failed: ' + e.message } ]; return next(null, inst); }); } function connectToUr(_, next) { // Will wait, at least, for the 5000 msecs we gave to ur client // as connect timeout before we call it and move into the "no-ur" // branch: var t = setTimeout(function () { if (self.urConnTimedOut) { self.log.error('Error connecting to Ur Agent'); return next(); } }, 5500); // Note this timeout is intentionally longer than Ur // client connect timeout. // If the connection times out, this will never be reached, and the // function above should call next if (!self.urConnTimedOut) { self.ur.once('ready', function () { clearTimeout(t); return next(); }); } } function lookupServices(_, next) { if (opts.insts) { return next(); } var svcOpts = {}; if (opts.type) { svcOpts.type = opts.type; } self.getServices(svcOpts, function (err, svcs) { if (err) { if (!err.message) { // TODO(trentm): why this?! err = new Error(err); } return next(err); } self.log.debug({ services: svcs }, 'Look up services'); if (uuidLookup) { svcs = svcs.filter(function (svc) { var found = uuidLookup[svc.uuid]; if (found) { delete uuidLookup[svc.uuid]; } return found; }); } svcs.forEach(function (svc) { if (svc.type === 'vm' || svc.type === 'agent') { svcLookup[svc.name] = true; } }); return next(); }); } function lookupInstances(_, next) { if (opts.insts) { return next(); } var svcOpts = {}; if (opts.type) { svcOpts.types = [opts.type]; } self.listInsts(svcOpts, function (err, insts_) { if (err) { if (!err.message) { err = new Error(err); } return next(err); } self.log.debug({ instances: insts_ }, 'Look up instances'); insts = insts_.filter(function (inst) { if (inst.type !== 'vm' && inst.type !== 'agent') { return false; } if (!svcLookup[inst.service] && !(uuidLookup && uuidLookup[inst.instance])) { return false; } if (uuidLookup) { delete uuidLookup[inst.instance]; } if (inst.type === 'vm' && !inst.ip && inst.service !== 'hostvolume') { self.log.error(inst.instance, 'VM has no admin IP, skip!'); return false; } return true; }); if (uuidLookup && Object.keys(uuidLookup).length > 0) { var msg = 'unrecognized service or instances: ' + Object.keys(uuidLookup).join(', '); return next(new Error(msg)); } return next(); }); } function checkInst(inst, next) { if (inst.server === headnode.UUID) { return checkHeadnodeInst(inst, next); } if (!self.urConnTimedOut) { return checkUrInst(inst, next); } // Do nothing, since it's not a local instance, and we cannot // connect to Ur to query remote instances status return next(); } function checkUrInst(inst, next) { var script; if (inst.type === 'vm') { script = 'svcs -vxz ' + inst.instance; } else if (inst.type === 'agent') { script = 'svcs -vx ' + inst.service; } else if (inst.alias === 'global') { script = 'svcs -vx'; } else { return next(); } // there are a couple agents which don't actually have SMF services, // so skip them if (inst.service.match(/(agents_core|cabase)$/)) { return next(); } self.ur.exec({ script: script, server_uuid: inst.server, timeout: 5000 }, function (err, result) { if (err) { inst.health_errors = [ { message: err.message }]; return next(null, inst); } self.log.debug({ ur_response: result }, 'Ur result for ' + inst.instance); if (result.exit_status !== 0 || result.stderr !== '' || !(result.stdout === '' || result.stdout.match(/State\: online/))) { inst.healthy = false; var errs = []; if (result.exit_status !== 0) { errs.push('svcs returned ' + result.exit_status); } if (result.stderr) { errs.push('stderr: ' + result.stderr.replace(/\n+$/, '')); } if (!(result.stdout === '' || result.stdout.match(/State\: online/))) { errs.push('stdout: ' + result.stdout.replace(/\n+$/, '')); } if (errs.length > 0) { inst.health_errors = errs.map(function (error) { return { message: 'SMF svcs check failed: ' + error }; }); } return next(null, inst); } return _pingInstance(inst, next); }); } // Used only when cannot stablish a connection to the AMQP server: function checkHeadnodeInst(inst, next) { var argv; if (inst.type === 'vm') { argv = ['/usr/bin/svcs', '-vxz', inst.instance]; } else if (inst.type === 'agent') { argv = ['/usr/bin/svcs', '-vx', inst.service]; } else if (inst.alias === 'global') { argv = ['/usr/bin/svcs', '-vx']; } else { return next(); } // there are a couple agents which don't actually have SMF services, // so skip them if (inst.service.match(/(agents_core|cabase)$/)) { return next(); } common.execFilePlus({ argv: argv, log: self.log }, function (err, stdout, stderr) { var errs = []; if (err) { errs.push(err); } if (stderr) { errs.push('stderr: ' + stderr.replace(/\n+$/, '')); } if (!(stdout === '' || stdout.match(/State\: online/))) { errs.push('stdout: ' + stdout.replace(/\n+$/, '')); } if (errs.length > 0) { inst.healthy = false; inst.health_errors = errs.map(function (error) { return { message: 'SMF svcs check failed: ' + error }; }); return next(null, inst); } return _pingInstance(inst, next); }); } // Intentionally not dealing into CNAPI here, since we may also need // to rely into sysinfo to know the name of installed agents: function getHeadnodeSysinfo(_, next) { var argv = ['/usr/bin/sysinfo']; common.execFilePlus({ argv: argv, log: self.log }, function (err, stdout, stderr) { if (err) { return next(err); } try { headnode = JSON.parse(stdout.trim()); if (!opts.insts) { insts.push({ type: 'global', instance: headnode.UUID, alias: 'global', service: 'global', hostname: 'headnode', server: headnode.UUID }); } } catch (e) { return next(e); } return next(); }); } vasync.pipeline({ funcs: [ connectToUr, lookupServices, lookupInstances, getHeadnodeSysinfo ]}, function (err) { if (err) { self.log.error({err: err}, 'checkHealth pipeline cb'); return cb(err); } // If servers to lookup were given as arguments, ignore whatever // not into these servers: if (opts.servers && opts.servers.length) { insts = insts.filter(function (ins) { return (opts.servers.indexOf(ins.server) !== -1 || opts.servers.indexOf(ins.hostname) !== -1); }); } vasync.forEachParallel({ inputs: insts, func: checkInst }, function (err2, results) { self.ur.close(); // Might need to re-user ur latest, need to reset it in order // to be able to re-connect: delete self._ur; if (err2) { self.log.error({err: err2}, 'checkHealth parallel cb'); return cb(new errors.InternalError(new Error(err2))); } var healthResults = results.successes.filter(function (res) { return res; }); // Notify about results being fetched locally and AMQP down: if (self.urConnTimedOut) { healthResults.push({ type: 'service', instance: '00000000-0000-0000-0000-000000000000', alias: 'rabbitmq0', service: 'rabbitmq', hostname: 'headnode', healthy: false, health_errors: [ { message: 'Ur Client cannot connect to AMQP server.\n' + 'Providing results only for vms/agents running ' + 'into Headnode' }] }); } return cb(null, healthResults); }); }); }; SdcAdm.prototype.createCloudapiInstance = function createCloudapiInstance(opts, callback) { var self = this; var sapi = self.sapi; assert.func(opts.progress, 'opts.progress'); var networks; var progress = opts.progress; var cloudapisvc; var changes = []; var img, history, headnode; // find cloudapi service, get service uuid // use sapi.createInstance to create the service vasync.pipeline({ funcs: [ function (_, next) { sapi.listServices({ name: 'cloudapi' }, function (err, svcs) { if (err) { return next(err); } if (svcs.length !== 1) { return next(new Error( 'expected 1 cloudapi service, found %d', svcs.length)); } cloudapisvc = svcs[0]; next(); }); }, function (_, next) { getNetworksAdminExternal({}, function (err, nets) { if (err) { return next(err); } networks = nets; next(); }); }, function (_, next) { self.updates.listImages({ name: 'cloudapi' }, function (err, images) { if (err) { next(err); } else if (images && images.length) { img = images[images.length - 1]; //XXX presuming sorted next(); } else { next(new errors.UpdateError('no "cloudapi" image found')); } }); }, function (_, next) { changes.push({ image: img, service: cloudapisvc, type: 'add-instance', inst: { type: 'vm', alias: opts.alias, version: img.version, service: 'cloudapi', image: img.uuid } }); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } history = hst; return next(); }); }, function getHeadnode(_, next) { self.cnapi.listServers({ headnode: true }, function (err, servers) { if (err) { return next(new errors.SDCClientError(err, 'cnapi')); } headnode = servers[0]; return next(); }); }, function (_, next) { var cOpts = { params: { server_uuid: headnode.uuid, alias: opts.alias, networks: [ { uuid: networks.admin.uuid }, { primary: true, uuid: networks.external.uuid } ] } }; sapi.createInstance(cloudapisvc.uuid, cOpts, function (err, inst) { if (err) { return next(err); } changes[0].inst.zonename = changes[0].inst.uuid = inst.uuid; next(); }); }, function hupHermes(_, next) { svcadm.restartHermes({ sdcadm: self, log: self.log, progress: progress }, next); } ] }, function (err) { if (!history) { self.log.warn('History not set for post-setup cloudapi'); return callback(err); } history.changes = changes; if (err) { history.error = err; } // No need to add `history.finished` here, History instance will do self.history.updateHistory(history, function (err2, hist2) { if (err) { callback(err); } else if (err2) { callback(err2); } else { progress('cloudapi0 zone created'); callback(); } }); }); function getNetworksAdminExternal(err, cb) { var napi = self.napi; var foundnets = {}; napi.listNetworks({ name: ['admin', 'external'] }, function (listerr, nets) { if (listerr) { return cb(err); } if (!nets.length) { return cb(new Error('Couldn\'t find admin network in NAPI')); } for (var i in nets) { foundnets[nets[i].name] = nets[i]; } cb(null, foundnets); }); } }; // Extracted from setupCommonExternalNics b/c it's also used by DownloadImages // to check if the reason for an IMGAPI failure could be the lack of external // nic into imgapi zone SdcAdm.prototype.checkMissingExternalNics = function checkMissingExternalNics(opts, cb) { var self = this; assert.func(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var sapi = self.sapi; var napi = self.napi; var svcadminui; var svcimgapi; var doadminui = true; var doimgapi = true; var netexternal; function getInstance(svcname, callback) { sapi.listServices({ name: svcname }, onServices); function onServices(err, svcs) { if (err) { return cb(err); } if (!svcs.length) { return cb(new Error( 'Couldn\'t find imgapi SAPI service')); } sapi.listInstances({ service_uuid: svcs[0].uuid }, function (listerr, inst) { if (listerr) { return cb(listerr); } callback(null, inst[0]); }); } } vasync.pipeline({ funcs: [ // Look up details for the adminui, imgapi instances. function (_, next) { getInstance('adminui', function (err, inst) { if (err) { return cb(err); } svcadminui = inst; next(); }); }, function (_, next) { getInstance('imgapi', function (err, inst) { if (err) { return cb(err); } svcimgapi = inst; next(); }); }, // Grab the external network details. function (_, next) { var listOpts = { name: 'external' }; napi.listNetworks(listOpts, function (err, nets) { if (err) { return cb(err); } if (!nets.length) { return cb(new Error( 'Couldn\'t find external network in NAPI')); } netexternal = nets[0]; next(); }); }, // Check what NICS the imgapi and adminui zones currently have. Only do // work for those which do not yet have an external nic. function (_, next) { var listOpts = { belongs_to_type: 'zone', belongs_to_uuid: [ svcimgapi.uuid, svcadminui.uuid ] }; napi.listNics(listOpts, function (err, nics) { if (err) { return cb(err); } if (!nics.length) { return cb(new Error( 'Couldn\'t find NICs for imgapi or adminui')); } for (var i = 0, nic; i < nics.length; i++) { nic = nics[i]; if (nic.belongs_to_uuid === svcadminui.uuid && nic.nic_tag === 'external') { doadminui = false; } else if (nic.belongs_to_uuid === svcimgapi.uuid && nic.nic_tag === 'external') { doimgapi = false; } } next(); }); } ]}, function (err) { if (err) { cb(err); } else { cb(null, { doimgapi: doimgapi, doadminui: doadminui, svcadminui: svcadminui, svcimgapi: svcimgapi, netexternal: netexternal }); } }); }; SdcAdm.prototype.setupCommonExternalNics = function setupCommonExternalNics(opts, cb) { var self = this; assert.func(opts.progress, 'options.progress'); var progress = opts.progress; var svcadminui; var svcimgapi; var doadminui = true; var doimgapi = true; var netexternal; var changes = []; var history; var napisvc; function addExternaNicToZone(svcobj, subcb) { var addparams = { uuid: svcobj.uuid, networks: [ { 'uuid': netexternal.uuid, primary: true } ] }; self.vmapi.addNicsAndWait(addparams, subcb); } vasync.pipeline({ funcs: [ function (_, next) { self.checkMissingExternalNics(opts, function (err, res) { if (err) { return next(err); } doimgapi = res.doimgapi; doadminui = res.doadminui; svcadminui = res.svcadminui; svcimgapi = res.svcimgapi; netexternal = res.netexternal; next(); }); }, function (_, next) { if (!doadminui && !doimgapi) { return next(); } self.sapi.listServices({ name: 'napi' }, function (err, svcs) { if (err) { return next(err); } if (svcs.length !== 1) { return next(new Error( 'expected 1 napi service, found %d', svcs.length)); } napisvc = svcs[0]; next(); }); }, function (_, next) { if (!doadminui && !doimgapi) { return next(); } changes.push({ service: napisvc, type: 'add-nics', inst: { network: netexternal.uuid, adminui: doadminui, imgapi: doimgapi } }); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } history = hst; return next(); }); }, function (_, next) { if (!doadminui) { progress('AdminUI already has an external nic'); return next(); } addExternaNicToZone(svcadminui, function (err) { if (err) { return next(err); } progress('Added external nic to adminui'); next(); }); }, function (_, next) { if (!doimgapi) { progress('IMGAPI already has an external nic'); return next(); } addExternaNicToZone(svcimgapi, function (err) { if (err) { return next(err); } progress('Added external nic to imgapi'); next(); }); } ]}, function (err) { if (!history) { self.log.info( 'History not set for post-setup common-external-nics'); return cb(err); } history.changes = changes; if (err) { history.error = err; } self.history.updateHistory(history, function (err2, hist2) { if (err) { cb(err); } else if (err2) { cb(err2); } else { cb(); } }); }); }; /* * Generate a rollback plan from the contents of the given update plan. * * @param options {Object} Required. * - updatePlan {Object} Required. The update plan. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * @param cb {Function} Callback of the form `function (err, plan)`. */ SdcAdm.prototype.genRollbackPlan = function genRollbackPlan(options, cb) { assert.object(options, 'options'); assert.object(options.updatePlan, 'options.updatePlan'); assert.optionalFunc(options.progress, 'options.progress'); assert.optionalString(options.uuid, 'options.uuid'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var serverFromUuidOrHostname; var rbPlan = {}; var upPlan = options.updatePlan; var svcs; var svcFromName; var insts; var changes; var plan; var servers; vasync.pipeline({funcs: [ function getServers(_, next) { self.cnapi.listServers(function (err, servers_) { servers = servers_ || []; serverFromUuidOrHostname = {}; for (var i = 0; i < servers.length; i++) { serverFromUuidOrHostname[servers[i].uuid] = servers[i]; serverFromUuidOrHostname[servers[i].hostname] = servers[i]; } next(err); }); }, function getSvcs(_, next) { self.getServices({}, function (err, svcs_) { svcs = svcs_ || []; svcFromName = {}; for (var i = 0; i < svcs.length; i++) { svcFromName[svcs[i].name] = svcs[i]; } next(err); }); }, function getInsts(_, next) { self.listInsts(function (err, insts_) { insts = insts_; next(err); }); }, function genRbSpecFromUpdate(_, next) { rbPlan.changes = []; upPlan.changes.forEach(function (change) { var chg = { service: change.service, type: (change.type === 'update-service') ? 'rollback-service' : 'unknown' }; if (change.service.type === 'vm') { if (change.service.name === 'assets') { chg.rb_img = change.inst.image; } else { chg.rb_img = change.service.params.image_uuid; } } rbPlan.changes.push(chg); }); next(); }, function getImgs(_, next) { var _changes = []; vasync.forEachParallel({ inputs: rbPlan.changes, func: function (chg, next_) { if (chg.service.type === 'vm') { self.getImage({ uuid: chg.rb_img }, function (e, img) { if (e) { return next_(e); } chg.image = img; delete chg.rb_img; _changes.push(chg); return next_(); }); } else { _changes.push(chg); return next_(); } } }, function (err) { rbPlan.changes = _changes; next(err); }); }, function createPlan(_, next) { changes = rbPlan.changes; var targ = common.deepObjCopy(insts); for (var i = 0; i < changes.length; i++) { var ch = changes[i]; for (var j = 0; j < targ.length; j++) { var inst = targ[j]; if (inst.service === ch.service.name) { inst.image = ch.image.uuid; inst.version = ch.image.version; } } } plan = new UpdatePlan({ curr: insts, targ: targ, changes: changes, rollback: true, justImages: false }); next(); }, function determineProcedures(_, next) { procedures.coordinatePlan({ plan: plan, sdcadm: self, serverFromUuidOrHostname: serverFromUuidOrHostname, log: log, progress: progress }, function (err, procs_) { plan.procs = procs_; next(err); }); } ]}, function finishRb(err) { cb(err, plan); }); }; //---- exports module.exports = SdcAdm;
lib/sdcadm.js
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ /* * Core SdcAdm class. */ var assert = require('assert-plus'); var child_process = require('child_process'), spawn = child_process.spawn, exec = child_process.exec; var util = require('util'), format = util.format; var fs = require('fs'); var http = require('http'); var https = require('https'); var p = console.log; var path = require('path'); var crypto = require('crypto'); var mkdirp = require('mkdirp'); var sdcClients = require('sdc-clients'); var semver = require('semver'); var sprintf = require('extsprintf').sprintf; var urclient = require('urclient'); var vasync = require('vasync'); var WfClient = require('wf-client'); var uuid = require('node-uuid'); var ProgressBar = require('progbar').ProgressBar; var common = require('./common'); var svcadm = require('./svcadm'); var errors = require('./errors'); var lock = require('./locker').lock; var pkg = require('../package.json'); var procedures = require('./procedures'); var History = require('./history').History; var ur = require('./ur'); var UA = format('%s/%s (node/%s; openssl/%s)', pkg.name, pkg.version, process.versions.node, process.versions.openssl); var UPDATE_PLAN_FORMAT_VER = 1; //---- UpdatePlan class // A light data object with some conveninence functions. function UpdatePlan(options) { assert.object(options, 'options'); assert.arrayOfObject(options.curr, 'options.curr'); assert.arrayOfObject(options.targ, 'options.targ'); assert.arrayOfObject(options.changes, 'options.changes'); assert.bool(options.justImages, 'options.justImages'); assert.optionalBool(options.rollback, 'options.rollback'); this.v = UPDATE_PLAN_FORMAT_VER; this.curr = options.curr; this.targ = options.targ; this.changes = options.changes; this.justImages = options.justImages; this.rollback = options.rollback || false; } UpdatePlan.prototype.serialize = function serialize() { return JSON.stringify({ v: this.v, targ: this.targ, changes: this.changes, justImages: this.justImages }, null, 4); }; //---- SdcAdm class /** * Create a SdcAdm. * * @param options {Object} * - log {Bunyan Logger} */ function SdcAdm(options) { assert.object(options, 'options'); assert.object(options.log, 'options.log'); // A unique UUID for this sdcadm run -- used for client req_id's below, // and for sdcadm history entries. if (!options.uuid) { options.uuid = uuid(); } if (!options.username) { options.username = process.env.USER; } var self = this; this.log = options.log; this.uuid = options.uuid; this.username = options.username; self._lockPath = '/var/run/sdcadm.lock'; self.userAgent = UA; Object.defineProperty(this, 'sapi', { get: function () { if (self._sapi === undefined) { self._sapi = new sdcClients.SAPI({ url: self.config.sapi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._sapi; } }); Object.defineProperty(this, 'cnapi', { get: function () { if (self._cnapi === undefined) { self._cnapi = new sdcClients.CNAPI({ url: self.config.cnapi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._cnapi; } }); Object.defineProperty(this, 'papi', { get: function () { if (self._papi === undefined) { self._papi = new sdcClients.PAPI({ url: self.config.papi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._papi; } }); Object.defineProperty(this, 'vmapi', { get: function () { if (self._vmapi === undefined) { self._vmapi = new sdcClients.VMAPI({ url: self.config.vmapi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._vmapi; } }); Object.defineProperty(this, 'imgapi', { get: function () { if (self._imgapi === undefined) { var opts = { url: self.config.imgapi.url, agent: false, userAgent: self.userAgent, /* * Don't *need* API version 2 and doing so breaks GetImage * with an old IMGAPI before: * commit de5c9bea58c934273b7efc7caa4ff46eeea380f6 * Date: Fri Aug 1 22:50:32 2014 -0700 * which currently is possible with the svcMinImages.imgapi * config in defaults.json. */ // version: '~2', log: self.log, headers: { 'x-request-id': self.uuid } }; self._imgapi = new sdcClients.IMGAPI(opts); } return self._imgapi; } }); Object.defineProperty(this, 'updates', { get: function () { if (self._updates === undefined) { var opts = { url: self.config.updatesServerUrl, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }; if (self.sdc.metadata.update_channel) { opts.channel = self.sdc.metadata.update_channel; } self._updates = new sdcClients.IMGAPI(opts); } return self._updates; } }); Object.defineProperty(this, 'imagesJo', { get: function () { if (self._imagesJo === undefined) { var opts = { url: 'https://images.joyent.com', agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }; self._imagesJo = new sdcClients.IMGAPI(opts); } return self._imagesJo; } }); Object.defineProperty(this, 'napi', { get: function () { if (self._napi === undefined) { self._napi = new sdcClients.NAPI({ url: self.config.napi.url, agent: false, userAgent: self.userAgent, log: self.log, headers: { 'x-request-id': self.uuid } }); } return self._napi; } }); Object.defineProperty(this, 'wfapi', { get: function () { if (self._wfapi === undefined) { self._wfapi = new WfClient({ url: self.config.wfapi.url, agent: false, path: './not/used/because/we/do/not/loadWorkflows', // TODO: Get wf-client to take `userAgent`. //userAgent: self.userAgent, log: self.log.child({client: 'wfapi'}, true), headers: { 'x-request-id': self.uuid } }); } return self._wfapi; } }); // NOTE: A method using self.ufds should take care of // calling self._ufds.close(function (err) {}); Yuck. Object.defineProperty(this, 'ufds', { get: function () { if (self._ufds === undefined) { self._ufds = new sdcClients.UFDS({ url: self.config.ufds.url, bindDN: self.config.ufds.bindDN, bindPassword: self.config.ufds.bindPassword, maxConnections: 1, retry: { initialDelay: 1000 }, clientTimeout: 120000, tlsOptions: { rejectUnauthorized: false }, log: self.log }); self._ufds.once('error', function (err) { throw err; }); self._ufds.once('connect', function () { self._ufds.removeAllListeners('error'); self._ufds.on('error', function (err) { self.log.info('UFDS disconnected'); }); self._ufds.on('connect', function () { self.log.info('UFDS reconnected'); }); self._ufds.on('timeout', function (msg) { self.log.error(msg); self._ufds.client.socket.destroy(); }); }); } return self._ufds; } }); this.urConnTimedOut = false; Object.defineProperty(this, 'ur', { get: function () { if (self._ur === undefined && !self.urConnTimedOut) { self._ur = urclient.create_ur_client({ connect_timeout: 5000, // in ms enable_http: false, amqp_config: self.config.amqp, log: self.log.child({client: 'ur'}, true) }); // Handle connection errors: self._ur.ur_urconn.on('error', function urErr(err) { self.log.error({ err: err }, 'Ur Connection Error'); self.urConnTimedOut = true; }); } return self._ur; } }); } // This function defines the sdcadm properties which require async callbacks // to be used: 'config', 'history' and 'sdc' application. SdcAdm.prototype.init = function init(cb) { var self = this; common.loadConfig({log: self.log}, function (err, config) { if (err) { return cb(err); } self.config = config; if (self.config.serverUuid) { self.userAgent += ' server=' + self.config.serverUuid; } self.history = new History({sdcadm: self}); self.getApp({app: 'sdc'}, function (appErr, app) { if (appErr) { // Couple known issues we can help operators with a friendly // message instead of the default "ENO..." errors: if (appErr.message) { if (appErr.message.match(/getaddrinfo ENOTFOUND/)) { console.log('Binder service seems to be down. ' + 'Please review it before proceeding'); } else if (appErr.message.match(/connect ECONNREFUSED/)) { console.log('Sapi service seems to be down. ' + 'Please review it before proceeding'); } } return cb(appErr); } self.sdc = app; return self.history.init(cb); }); }); }; /** * Gather a JSON object for every (or specified subset of) installed SDC * service instance. * * "Services" include: SDC core vms and agents. * * All types will have these fields: * type type of service, one of 'vm' or 'agent' * instance (Note: Agents don't current have a instance UUID * exposed.) * service name of service, e.g. 'vmapi, 'provisioner' * image image UUID (Note: Agents aren't * currently distributed as separate "images" in * updates.joyent.com. Until they are `image === null`.) * version version string, e.g. '1.2.3' * server server uuid (if available) * hostname server hostname (if available) * server_ip 'admin' network IP for the server (if available) * * Other fields for type=vm instances: * ip 'admin' network IP (for type=vm instances) * state the VM state from VMAPI, e.g. 'running', 'provisioning' * zonename * * @param opts {Object} Optional * - types {Array} instance types to which to limit results. Valid values * are 'vm' or 'agent'. * - svcs {Array} service names to which to limit results. * @param cb {Function} `function (err, insts)` */ SdcAdm.prototype.listInsts = function listInsts(opts, cb) { var self = this; if (cb === undefined) { cb = opts; opts = {}; } assert.object(opts, 'opts'); assert.optionalArrayOfString(opts.types, 'opts.types'); assert.optionalArrayOfString(opts.svcs, 'opts.svcs'); assert.func(cb, 'cb'); var isWantedSvc = null; if (opts.svcs) { isWantedSvc = {}; for (var j = 0; j < opts.svcs.length; j++) { isWantedSvc[opts.svcs[j]] = true; } } var context = { insts: [] }; vasync.pipeline({arg: context, funcs: [ function getServers(ctx, next) { ctx.serverFromUuid = {}; ctx.serverAdminIpFromUuid = {}; var serverOpts = { extras: 'sysinfo,agents' }; self.cnapi.listServers(serverOpts, function (serversErr, servers) { if (serversErr) { return next(new errors.SDCClientError(serversErr, 'cnapi')); } for (var i = 0; i < servers.length; i++) { var server = servers[i]; ctx.serverFromUuid[server.uuid] = server; var nics = server.sysinfo['Network Interfaces'] || {}; var adminIp = Object.keys(nics).map(function (nicName) { return nics[nicName]; }).filter(function (nic) { return nic['NIC Names'].indexOf('admin') !== -1; }).map(function (nic) { return nic.ip4addr; })[0]; ctx.serverAdminIpFromUuid[server.uuid] = adminIp; } next(); }); }, /* * Right now we don't have a way to match an agent inst in SAPI to * the server on which it lives. That's kind of lame. However a * proper answer should eventually come with sdc-update M10 work * to get agents individually managed. */ function fillOutAgentInsts(ctx, next) { if (opts.types && opts.types.indexOf('agent') === -1) { return next(); } var serverUuids = Object.keys(ctx.serverFromUuid); for (var i = 0; i < serverUuids.length; i++) { var server = ctx.serverFromUuid[serverUuids[i]]; (server.agents || server.sysinfo['SDC Agents'] || []).forEach( function (agent) { if (!isWantedSvc || isWantedSvc[agent.name]) { var inst = { type: 'agent', service: agent.name, instance: agent.uuid, version: agent.version, image: agent.image_uuid, server: server.uuid, hostname: server.hostname, server_ip: ctx.serverAdminIpFromUuid[server.uuid] }; ctx.insts.push(inst); } }); } next(); }, /* * Note: For *now* we gather for VMs that aren't listed as SAPI * instances because, e.g., SDC doesn't add an "assets" service. * It should. * * As a result, instead of SAPI being the authority on insts, it is * instead a VMAPI query for admin-owned VMs with `tags.smartdc_role`. */ function getVmInfo(ctx, next) { if (opts.types && opts.types.indexOf('vm') === -1) { return next(); } ctx.vmFromUuid = {}; /** * Instead of getting each VM (there could be up to dozens), * lets get all of admin's VMs in one req and filter those. * * 'cloudapi' zones typically don't have * `tags.smartdc_core=true` so we can't filter on that. And * VMAPI doesn't support filtering on presence of a tag * (e.g. `smartdc_role`). */ var filters = { state: 'active', owner_uuid: self.config.ufds_admin_uuid }; self.vmapi.listVms(filters, function (err, vms) { if (err) { return next(new errors.SDCClientError(err, 'vmapi')); } for (var i = 0; i < vms.length; i++) { var vm = vms[i]; if (vm.tags && vm.tags.smartdc_role) { if (!isWantedSvc || isWantedSvc[vm.tags.smartdc_role]) { ctx.vmFromUuid[vm.uuid] = vm; } } } next(); }); }, function getImgs(ctx, next) { if (opts.types && opts.types.indexOf('vm') === -1) { return next(); } ctx.imgFromUuid = {}; // Prefer *vmFromUuid* to *sapiInstFromUuid* b/c no 'assets' svc. var vmUuids = Object.keys(ctx.vmFromUuid); for (var i = 0; i < vmUuids.length; i++) { var vm = ctx.vmFromUuid[vmUuids[i]]; ctx.imgFromUuid[vm.image_uuid] = null; } var imgUuids = Object.keys(ctx.imgFromUuid); self.log.trace({imgUuids: imgUuids}, 'listInsts imgUuids'); vasync.forEachParallel({ inputs: imgUuids, func: function getOneImg(imgUuid, nextImg) { self.imgapi.getImage(imgUuid, function (err, img) { if (!err) { ctx.imgFromUuid[imgUuid] = img; nextImg(); } else if (err.restCode !== 'ResourceNotFound') { nextImg(new errors.SDCClientError( err, 'imgapi')); } else { nextImg(); } }); } }, next); }, function fillOutVmInsts(ctx, next) { if (opts.types && opts.types.indexOf('vm') === -1) { return next(); } // Prefer *vmFromUuid* to *sapiInstFromUuid* b/c no 'assets' svc. var uuids = Object.keys(ctx.vmFromUuid); for (var i = 0; i < uuids.length; i++) { var vm = ctx.vmFromUuid[uuids[i]]; var img = ctx.imgFromUuid[vm.image_uuid]; var inst = { type: 'vm', alias: vm.alias, version: null, instance: vm.uuid, zonename: vm.uuid, service: vm.tags.smartdc_role, image: vm.image_uuid, state: vm.state, server: null, hostname: null, server_ip: null }; if (img) { inst.version = img.version; } // A state='provisioning' VM might not yet have a // 'server_uuid'. if (vm.server_uuid) { inst.server = vm.server_uuid; inst.hostname = ctx.serverFromUuid[ vm.server_uuid].hostname; inst.server_ip = ctx.serverAdminIpFromUuid[ vm.server_uuid]; } var adminIp = vm.nics.filter(function (nic) { return nic.nic_tag === 'admin'; }).map(function (nic) { return nic.ip; })[0]; if (adminIp) { inst.ip = adminIp; } ctx.insts.push(inst); } next(); }, function findMissingInstImgs(ctx, next) { vasync.forEachParallel({ inputs: ctx.insts, func: function imgadmGetImg(inst, nextInst) { if (inst.version || !inst.server) { return nextInst(); } common.imgadmGetRemote({ img_uuid: inst.image, server: inst.server, log: self.log }, function (err, img) { if (err) { self.log.error({err: err}, 'imgadm error'); return nextInst(); } if (img && img.manifest && img.manifest.version) { inst.version = img.manifest.version; } return nextInst(); }); } }, next); } ]}, function (err) { cb(err, context.insts); }); }; /** * Gather a JSON object for each installed SDC service. * * "Services" include: SDC core vms and agents. */ SdcAdm.prototype.getServices = function getServices(opts, cb) { var self = this; assert.object(opts, 'opts'); assert.func(cb, 'cb'); var app = self.sdc; var svcs = []; vasync.pipeline({funcs: [ function getSapiSvcs(_, next) { // 'cloudapi' zones typically don't have `tags.smartdc_core=true` // so we can't filter on that. And VMAPI doesn't support filtering // on presence of a tag (e.g. `smartdc_role`.) var filters = { application_uuid: app.uuid }; if (opts.type) { filters.type = opts.type; } self.sapi.listServices(filters, function (svcsErr, svcs_) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } svcs = svcs_; var haveAssets = false; svcs.forEach(function (svc) { // TODO(trent): want SAPI to have this eventually. // TOOLS-724: new SAPI instances will have this type // member. Do not override it when already present. if (!svc.type) { svc.type = 'vm'; } if (svc.name === 'assets') { haveAssets = true; } }); // TODO: get assets service in SAPI. Hack it in for now. // Not having 'assets' service mucks up update type guessing // in 'sdcadm update assets', for example. if (!haveAssets) { svcs.push({ type: 'vm', name: 'assets' }); } next(); }); }, function getAgents(_, next) { // TODO: Remove these hardcoded values // Hardcode "known" agents for now until SAPI handles agents. // Excluding "marlin". Should we include hagfish-watcher? [ { 'name': 'cabase' }, { 'name': 'hagfish-watcher' }, { 'name': 'agents_core' }, { 'name': 'firewaller' }, { 'name': 'amon-agent' }, { 'name': 'cainstsvc' }, { 'name': 'provisioner' }, { 'name': 'amon-relay' }, { 'name': 'heartbeater' }, { 'name': 'smartlogin' }, { 'name': 'zonetracker' } ].forEach(function (agent) { var exists = svcs.filter(function (s) { return (s.name === agent.name); }).length; if (!exists) { agent.type = 'agent'; svcs.push(agent); } }); next(); } ]}, function (err) { cb(err, svcs); }); }; /** * Get the full image object for the given image UUID from either the local * IMGAPI or the updates server. * * @param opts {Object} Required. * - uuid {UUID} Required. The image uuid. * @param cb {Function} `function (err, img)` */ SdcAdm.prototype.getImage = function getImage(opts, cb) { assert.object(opts, 'opts'); assert.string(opts.uuid, 'opts.uuid'); assert.func(cb, 'cb'); var self = this; self.imgapi.getImage(opts.uuid, function (iErr, iImg) { if (iErr && iErr.body && iErr.body.code === 'ResourceNotFound') { self.updates.getImage(opts.uuid, cb); } else { cb(iErr, iImg); } }); }; /** * Get a SAPI application. * * @param opts {Object} Required. * - app {String|UUID} Required. The application name or UUID. * @param cb {Function} `function (err, app)` */ SdcAdm.prototype.getApp = function getApp(opts, cb) { assert.object(opts, 'opts'); assert.string(opts.app, 'opts.app'); assert.func(cb, 'cb'); if (opts.app === 'sdc' && this.sdc) { cb(null, this.sdc); } else if (common.UUID_RE.test(opts.app)) { this.sapi.getApplication(opts.app, errors.sdcClientErrWrap(cb, 'sapi')); } else { this.sapi.listApplications({name: opts.app}, function (err, apps) { if (err) { cb(new errors.SDCClientError(err, 'sapi')); } else if (apps.length !== 1) { cb(new errors.InternalError({ message: format('unexpected number of "%s" apps: %d', opts.app, apps.length) })); } else { cb(null, apps[0]); } }); } }; /** * Get a SAPI service. * * Dev Note: Why 'getSvc' and not 'getService'? I want to move to * app/svc/inst/img for naming in functions as well. * * @param opts {Object} Required. * - app {String|UUID} Required. The application name or UUID. * - svc {String|UUID} Required. The service name or UUID. * - allowNone {Boolean} Optional. Default false. Set `true` to return * `cb()` if there is no such service. By default an InternalError is * returned. * @param cb {Function} `function (err, svc)` */ SdcAdm.prototype.getSvc = function getSvc(opts, cb) { var self = this; assert.optionalBool(opts.allowNone, 'opts.allowNone'); self.getApp({app: opts.app}, function (appErr, app) { if (appErr) { return cb(appErr); } if (common.UUID_RE.test(opts.svc)) { self.sapi.getService(opts.svc, function (svcErr, svc) { if (svcErr) { return cb(new errors.SDCClientError(svcErr, 'sapi')); } else if (svc.application_uuid !== app.uuid) { cb(new errors.ValidationError(format( 'given svc "%s" does not belong to the "%s" app', opts.svc, opts.app))); } else { cb(null, svc); } }); } else { var filters = { application_uuid: app.uuid, name: opts.svc }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return cb(new errors.SDCClientError(svcsErr, 'sapi')); } else if (svcs.length > 1) { cb(new errors.InternalError({ message: format('unexpected number of "%s" svcs: %d', opts.svc, svcs.length) })); } else if (svcs.length === 0) { if (opts.allowNone) { cb(null); } else { cb(new errors.InternalError({ message: format('no "%s" service found', opts.svc) })); } } else { cb(null, svcs[0]); } }); } }); }; /** * Get the image version for all the active VMs of the given service. * * @type obj {Object} including: * @prop vms {Array} of VMAPI vms * @prop imgs {Array} of IMGAPI imgs (only different images, if all the * VMs are using the same image, only one image will be returned here). * * @params svc {String|UUID} Required. The service name or UUID. * @param cb {Function} `function (err, obj)` */ SdcAdm.prototype.getImgsForSvcVms = function getImgsForSvcVms(opts, cb) { var self = this; assert.object(opts, 'opts'); assert.optionalString(opts.app, 'opts.app'); assert.string(opts.svc, 'opts.svc'); assert.func(cb, 'cb'); if (!opts.app) { opts.app = 'sdc'; } var svc, vms; vasync.pipeline({funcs: [ function _getSvc(_, next) { self.getSvc(opts, function (err, service) { if (err) { return next(err); } svc = service; return next(); }); }, function _getVms(_, next) { self.vmapi.listVms({ 'tag.smartdc_role': svc.name, state: 'active' }, function (vmsErr, vms_) { if (vmsErr) { return next(vmsErr); } if (!vms_.length) { return next(new errors.SDCClientError(new Error(format( 'Unable to find %s VMs', svc.name)), 'vmapi')); } vms = vms_; return next(); }); } ]}, function pipeCb(err) { if (err) { return cb(err); } var imgs = []; var differentImgUUIDs = vms.map(function (vm) { return (vm.image_uuid); }).sort().filter(function (id, pos, ary) { // Once we've sorted out the array, we can remove any duplicates // just by looking up at the previous element. Obviously, first one // will never be removed. return (!pos || id !== ary[pos - 1]); }); vasync.forEachParallel({ func: function _getImg(id, next) { self.getImage({uuid: id}, function (er3, img) { if (er3) { return next(er3); } imgs.push(img); return next(); }); }, inputs: differentImgUUIDs }, function paraCb(err2) { if (err2) { return cb(err2); } return cb(null, {imgs: imgs, vms: vms}); }); }); }; /* * Fetch a given agent installer image (or if desired, latest), download it, * then use /usbkey/scripts/update_agents to deploy the installer to compute * nodes. */ SdcAdm.prototype.updateAgents = function updateAgents(options, callback) { assert.object(options, 'options'); assert.string(options.image, 'options.image'); assert.optionalBool(options.justDownload, 'options.justDownload'); assert.optionalBool(options.yes, 'options.yes'); assert.optionalBool(options.all, 'options.all'); assert.optionalArrayOfString(options.servers, 'options.servers'); assert.optionalArrayOfString(options.exclude, 'options.exclude'); assert.func(options.progress, 'options.progress'); var self = this; var localdir = '/var/tmp'; var deleteOnFinish = true; var filepath; var image; // The file name, to be used by ur: var fname; var progress = options.progress; var justDownload = options.justDownload; // Used by history var changes = []; var hist; // Version of (latest) local agents file: var localVersion; var localFile; // The image we are trying to download already exists on cache dir var existingImage = false; var runningServers; // All the setup servers from CNAPI: var serverRecs; // The servers we're gonna update: var assignServers = []; // We may receive errors from UR when trying to update agents into // the CNs: var errs = []; function findInstallerImageLatest(cb) { var filter = { name: 'agentsshar' }; self.updates.listImages(filter, function (err, images) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } if (Array.isArray(images) && !images.length) { return cb(new errors.UpdateError('no images found')); } common.sortArrayOfObjects(images, ['published_at']); image = images[images.length - 1]; cb(); }); return; } function findInstallerImageByUuid(cb) { self.updates.getImage(options.image, function (err, foundImage) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } image = foundImage; cb(); }); } function downloadInstallerImage(cb) { progress('Downloading agentsshar image to %s', filepath); function onImage(err) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } cb(); } self.updates.getImageFile(image.uuid, filepath, onImage); } function cleanup(cb) { fs.unlink(filepath, function (err) { if (err) { self.log.warn(err, 'unlinking %s', filepath); } cb(); }); } vasync.pipeline({funcs: [ function findImg(_, next) { if (options.image === 'latest') { findInstallerImageLatest(next); // Check if the value of the parameter `image` is a file } else if (fs.existsSync(options.image)) { filepath = options.image; deleteOnFinish = false; next(); } else { findInstallerImageByUuid(next); } }, function findLatestLocalVersion(_, next) { if (!image) { return next(); } var latestPath = '/usbkey/extra/agents/latest'; fs.exists(latestPath, function (exists) { if (!exists) { progress('Symlink to latest agents file (%s) is missing.', latestPath); return next(); } else { fs.readlink(latestPath, function (err, linkString) { if (err) { self.log.error(err, latestPath); progress('Error reading symlink to latest ' + 'agents file (%s).', latestPath); return next(); } else { localFile = '/usbkey/extra/agents/' + linkString; localVersion = path.basename(linkString, '.sh'). replace(/^agents-/, ''); progress('UUID of latest installed agents image ' + 'is: %s\n', localVersion); return next(); } }); } }); }, function localImageChecksum(_, next) { // No need to check anything if argument was a file path if (!image) { return next(); } var hash = null; var s = fs.ReadStream(localFile); hash = crypto.createHash('sha1'); s.on('data', function (d) { hash.update(d); }); s.on('end', function () { var sha1_actual = hash.digest('hex'); var sha1_expected = image.files[0].sha1; self.log.trace({ sha1_local: sha1_actual, sha1_remote: sha1_expected }, 'Image checksum'); if ((sha1_actual === sha1_expected)) { progress('The agentsshar is already in assets dir: %s', localFile); progress('Please do one of the following:'); progress('1. Specify the full path to install this ' + 'version:'); progress(common.indent( 'sdcadm experimental update-agents ' + localFile)); progress('2. Or, delete that path and re-run to ' + 're-download and install.'); return callback(); } else { return next(); } }); }, function serverList(_, next) { if (justDownload) { return next(); } self.cnapi.listServers({ setup: true }, function (err, recs) { if (err) { return next(err); } serverRecs = recs; next(); }); }, function findServersToUpdate(_, next) { if (justDownload) { return next(); } // Find the headnode and depending on the options passed in, // either a single compute node or multiple. We need the headnode // details so that we can update the booter cache on the headnode // dhcpd zone. serverRecs.forEach(function (server) { if (options.all) { assignServers.push(server); } else if (options.servers.indexOf(server.hostname) !== -1 || options.servers.indexOf(server.uuid) !== -1) { assignServers.push(server); } }); if (options.servers && !assignServers.length) { return next( new Error(format( 'server %j not found', options.servers))); } next(); }, function applyExcludeFilters(_, next) { if (justDownload) { return next(); } if (!options.exclude || !options.all) { return next(); } common.excludeServers({ servers: assignServers, exclude: options.exclude, log: self.log }, function (err, servers) { if (err) { return next(err); } assignServers = servers; progress('Selected %d servers on which to install', assignServers.length); return next(); }); }, function connectToUr(_, next) { if (justDownload) { return next(); } self.ur.once('error', function (err) { self.log.debug({err: err}, 'Ur error'); return next(new errors.InternalError({ message: 'Error Connecting to Ur' })); }); // If the connection times out, this will never be reached, and the // function above should call next self.ur.once('ready', function () { return next(); }); }, function urNodeDiscovery(_, next) { if (justDownload) { return next(); } progress('Ensuring contact with all servers'); var results = []; var nodeList = assignServers.map(function (s) { return (s.uuid); }); var disco = self.ur.discover({ timeout: 10 * 1000, exclude_headnode: false, node_list: nodeList }); function end() { self.log.debug('Ur Node Discovery complete'); results = results.map(function (res) { return (res.uuid); }); assignServers = assignServers.filter(function (srv) { return (results.indexOf(srv.uuid) !== -1); }); return next(); } function failure(err) { if (err.nodes_missing && err.nodes_missing.length) { // Cannot find all nodes self.log.info({ nodes: err.nodes_missing }, 'Ur cannot find these nodes'); progress('\nUr cannot find the following nodes: %s', err.nodes_missing.join(', ')); progress('You should fix this issue before running ' + 'this command again'); } else { self.log.error({err: err}, 'Ur Node Discovery failed'); } return next(err); } disco.on('error', failure); disco.on('server', function (server) { var msg = common.indent('- Server ' + server.uuid + ' (' + server.hostname + ') available'); self.log.debug(msg); // Too much noise for a setup with 200 servers // progress(msg); results.push(server); }); disco.on('duplicate', function (uid, hostname) { var err = new Error('duplicate host specification detected'); err.duplicate = [ uid, hostname ]; /* * We are done with this discovery session. Cancel it and * ignore future error/end events. */ disco.removeAllListeners(); disco.cancel(); failure(err); }); disco.on('end', end); }, function confirm(_, next) { var m = 'This update will make the following changes:\n'; if (filepath) { m += common.indent(format('Update agents on %d ' + 'servers using file: %s\n', assignServers.length, filepath)); } else { var word = options.justDownload ? 'Download' : 'Download and install'; m += common.indent(format('%s agentsshar ' + 'image %s\n(%s) on %d servers', word, image.uuid, image.version, assignServers.length)); } progress(''); progress(m); progress(''); if (options.yes) { return next(); } var msg = 'Would you like to continue? [y/N] '; common.promptYesNo({msg: msg, default: 'n'}, function (answer) { if (answer !== 'y') { progress('Aborting agents update'); return callback(); } progress(''); return next(); }); }, function saveChangesToHistory(_, next) { if (justDownload) { return next(); } var change = { service: { name: 'agents-shar' }, type: 'update-service', img: (image ? image : options.image) }; changes.push(change); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function prepareReRun(_, next) { if (filepath && !image) { return next(); } // We need to move the file to some other place due to // the way /usbkey/scripts/update_agents works, which // will try to re-copy the file to its original place. filepath = format('%s/agents-%s.sh', localdir, localVersion); if (existingImage && options.force) { var cmd = format('/usr/bin/mv %s %s', localFile, filepath); progress('Moving agentsshar to assets dir %s', filepath); exec(cmd, {}, function (err, stdout, stderr) { if (err) { var msg = format( 'exec error:\n' + '\tcmd: %s\n' + '\texit status: %s\n' + '\tstdout:\n%s\n' + '\tstderr:\n%s', cmd, err.code, stdout.trim(), stderr.trim()); return next(new errors.InternalError({ message: msg, cause: err }), stdout, stderr); } return next(); }); } else { return next(); } }, function downloadInstaller(_, next) { if (filepath && !image) { progress('Using agent installer file %s', filepath); next(); } else { filepath = format('%s/agents-%s.sh', localdir, image.uuid); if (fs.existsSync(filepath)) { progress('Using agent installer %s ' + 'from previous download', filepath); next(); } else { downloadInstallerImage(next); } } }, function copyFileToAssetsDir(_, next) { if (justDownload) { return next(); } var assetsdir = '/usbkey/extra/agents'; var argv = ['cp', filepath, assetsdir]; mkdirp.sync(assetsdir); common.execFilePlus({ argv: argv, log: self.log }, function (err, stderr, stdout) { self.log.trace({ cmd: argv.join(' '), err: err, stdout: stdout, stderr: stderr }, 'ran cp command'); if (err) { return next(new errors.InternalError({ message: format('error copying shar file to %s', assetsdir), cmd: argv.join(' '), stdout: stdout, stderr: stderr, cause: err })); } next(); }); }, function createLatestSymlink(_, next) { var argv = [ 'rm', '-f', '/usbkey/extra/agents/latest' ]; common.execFilePlus({ argv: argv, log: self.log }, function (err1, stdout1, stderr1) { self.log.trace({ cmd: argv.join(' '), err: err1, stdout: stdout1, stderr: stderr1 }, 'rm -f latest cmd'); if (err1) { return next(err1); } fname = path.basename(filepath); argv = ['ln', '-s', fname, 'latest']; common.execFilePlus({ argv: argv, cwd: '/usbkey/extra/agents', log: self.log }, function (err2, stdout2, stderr2) { self.log.trace({ cmd: argv.join(' '), err: err2, stdout: stdout2, stderr: stderr2 }, 'ln -s latest cmd'); if (err2) { return next(err2); } return next(); }); }); }, function runUrQueue(_, next) { if (justDownload) { deleteOnFinish = false; return next(); } progress('Running agents installer into %s servers', assignServers.length); var cmd = 'cd /var/tmp;\n' + '[ ! -d /opt/smartdc/agents/lib ] && exit 0;\n' + 'curl -kOs ' + self.config.assets_admin_ip + ':/extra/agents/' + fname + ' && \ \n' + 'bash /var/tmp/' + fname + ' </dev/null >/var/tmp/' + fname + '_install.log 2>&1 && \ \n' + 'echo \'SDC7 agent upgrade\''; self.log.trace({cmd: cmd}, 'Ur Run Queue created'); var queueOpts = { sdcadm: self, log: self.log, progress: progress, command: cmd }; if (process.stderr.isTTY) { var bar = new ProgressBar({ size: assignServers.length, bytes: false, filename: fname }); queueOpts.progbar = bar; } var rq = ur.runQueue(queueOpts, function (err, results) { if (err) { return next(err); } results.forEach(function (re) { if (re.result.exit_status !== 0) { var errMsg = format('Agents update failed in server' + '%s (%s) with error: %j', re.uuid, re.hostname, re.result); errs.push(new errors.UpdateError(errMsg)); } }); rq.close(); if (errs.length) { return next(new errors.MultiError(errs)); } return next(); }); assignServers.forEach(function (s) { rq.add_server(s); }); rq.start(); }, function closeUr(_, next) { if (justDownload) { return next(); } self.ur.close(); next(); }, function doCleanup(_, next) { if (deleteOnFinish) { cleanup(next); } else { next(); } }, // At this point we can consider the update complete. The next step // is just about providing accurate information when listing agent // instances and until we move from update agents using a shar file // to the individual agents update. function refreshSysinfo(_, next) { progress('Reloading servers sysinfo'); self.cnapi.listServers({ setup: true }, function (err, servers_) { if (err) { self.log.error({err: err}, 'CNAPI listServers'); return next(); } runningServers = servers_ || []; // Ignore any server w/o running status: runningServers = runningServers.filter(function (s) { return (s.status === 'running'); }); function upSysinfo(server, cb) { var sPath = format('/servers/%s/sysinfo-refresh', server.uuid); self.cnapi.post({ path: sPath }, {}, function cnapiCb(er2, res) { if (er2) { self.log.error({ err: er2, path: sPath }, 'CNAPI sysinfo-refresh'); } return cb(); }); } var queue = vasync.queue(upSysinfo, 10); queue.push(runningServers); // No need for per task done cb queue.close(); queue.on('end', function done() { progress('sysinfo reloaded for all the running servers'); next(); }); }); }, function refreshConfigAgents(_, next) { progress('Refresh config-agent into all the setup and running' + ' servers'); function refreshCfgAgent(server, cb) { svcadm.svcadmRefresh({ server_uuid: server.uuid, wait: false, fmri: 'config-agent', sdcadm: self, log: self.log }, cb); } var queue = vasync.queue(refreshCfgAgent, 10); queue.push(runningServers); // No need for per task done cb queue.close(); queue.on('end', function done() { progress('config-agent refresh for all the running servers'); next(); }); } ]}, function (err) { if (justDownload) { return callback(); } if (err) { if (!hist) { self.log.warn('History not saved for update-agents'); return callback(err); } hist.error = err; } if (!hist) { self.log.warn('History not saved for update-agents'); return callback(); } self.history.updateHistory(hist, function (err2) { if (err) { return callback(err); } progress('Done.'); if (err2) { return callback(err2); } else { return callback(); } }); }); }; /* * Fetch a given gz-tools tarball image (or if desired, latest), download it, * then do the following: * * - Update SDC zone tools (tools.tar.gz) * - Update GZ scripts * - Update /usbkey/default * - Update cn_tools.tar.gz on all Compute Nodes */ SdcAdm.prototype.updateGzTools = function updateGzTools(options, callback) { assert.object(options, 'options'); assert.string(options.image, 'options.image'); assert.func(options.progress, 'opts.progress'); var self = this; var localdir = '/var/tmp'; var deleteOnFinish = true; var filepath; var image; var sdcZone; var progress = options.progress; var timestamp = Math.floor(new Date().getTime() / 1000); var tmpToolsDir = format('%s/gz-tools', localdir); var justDownload = options.justDownload; // Used by sdcadm history: var changes = []; var hist; function findTarballImageLatest(cb) { var filter = { name: 'gz-tools' }; self.updates.listImages(filter, function (err, images) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } if (Array.isArray(images) && !images.length) { return cb(new errors.UpdateError('no images found')); } common.sortArrayOfObjects(images, ['published_at']); image = images[images.length - 1]; cb(); }); return; } function findTarballImageByUuid(cb) { self.updates.getImage(options.image, function (err, foundImage) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } image = foundImage; cb(); }); } function downloadTarballImage(cb) { progress('Downloading gz-tools image %s (%s) to %s', image.uuid, image.version, filepath); function onImage(err) { if (err) { cb(new errors.SDCClientError(err, 'updates')); return; } cb(); } self.updates.getImageFile(image.uuid, filepath, onImage); } function updateSdcFiles(cb) { progress('Updating "sdc" zone tools'); vasync.pipeline({funcs: [ function removeSymlink(_, next) { var argv = ['rm', '-rf', '/opt/smartdc/sdc']; common.execFilePlus({argv: argv, log: self.log}, next); }, function reSymlink(_, next) { var argv = [ 'ln', '-s', '/zones/' + sdcZone.uuid + '/root/opt/smartdc/sdc', '/opt/smartdc/sdc' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function decompressTools(_, next) { // tools.tar.gz will be located at $tmpToolsDir/tools.tar.gz var argv = [ '/usr/bin/tar', 'xzof', tmpToolsDir + '/tools.tar.gz', '-C', '/opt/smartdc' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function cleanupSemverFile(_, next) { // Remove semver.js from an old sdc-clients-light version var sverFile = '/opt/smartdc/node_modules/sdc-clients/' + 'node_modules/semver.js'; if (!fs.existsSync(sverFile)) { next(); return; } fs.unlink(sverFile, function (err) { if (err) { self.log.warn(err, 'unlinking %s', sverFile); } next(); }); } ]}, function (err) { cb(err); }); } function updateScripts(cb) { progress('Updating global zone scripts'); vasync.pipeline({funcs: [ function mountUsbKey(_, next) { progress('Mounting USB key'); var argv = ['/usbkey/scripts/mount-usb.sh']; common.execFilePlus({argv: argv, log: self.log}, next); }, function backupScriptsDir(_, next) { var argv = [ 'cp', '-Rp', '/usbkey/scripts', localdir + '/pre-upgrade.scripts.' + timestamp ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function backupToolsFile(_, next) { if (!fs.existsSync('/usbkey/tools.tar.gz')) { next(); return; } var argv = [ 'cp', '/usbkey/tools.tar.gz', localdir + '/pre-upgrade.tools.' + timestamp + '.tar.gz' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function removeScriptsDir(_, next) { var argv = [ 'rm', '-rf', '/mnt/usbkey/scripts' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyScriptsToUSBKey(_, next) { var argv = [ 'cp', '-Rp', tmpToolsDir + '/scripts', '/mnt/usbkey/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyToolsToUSBKey(_, next) { var argv = [ 'cp', tmpToolsDir + '/tools.tar.gz', '/mnt/usbkey/tools.tar.gz' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyDefaultDirToUsbKey(_, next) { var cmd = ['cp', tmpToolsDir + '/default/*', '/mnt/usbkey/default']; exec(cmd.join(' '), function (err, stdout, stderr) { self.log.trace({cmd: cmd, err: err, stdout: stdout, stderr: stderr}, 'ran cp command'); if (err) { return next(new errors.InternalError({ message: 'error running cp command', cmd: cmd, stdout: stdout, stderr: stderr, cause: err })); } next(); }); }, function rsyncScriptsToCache(_, next) { var argv = [ 'rsync', '-avi', '--exclude', 'private', '--exclude', 'os', '/mnt/usbkey/', '/usbkey/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyJoysetup(_, next) { var argv = [ 'cp', tmpToolsDir + '/scripts/joysetup.sh', '/usbkey/extra/joysetup/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function copyAgentSetup(_, next) { var argv = [ 'cp', tmpToolsDir + '/scripts/agentsetup.sh', '/usbkey/extra/joysetup/' ]; common.execFilePlus({argv: argv, log: self.log}, next); }, function unmountUsbKey(_, next) { progress('Unmounting USB key'); var argv = ['/usr/sbin/umount', '/mnt/usbkey']; common.execFilePlus({argv: argv, log: self.log}, next); } ]}, function (err) { cb(err); }); } function updateCnTools(cb) { progress('Updating cn_tools on all compute nodes'); var argv = [ '/usbkey/scripts/update_cn_tools', '-f', tmpToolsDir + '/cn_tools.tar.gz' ]; common.execFilePlus({argv: argv, log: self.log}, cb); } function cleanup(cb) { progress('Cleaning up gz-tools tarball'); fs.unlink(filepath, function (err) { if (err) { self.log.warn(err, 'unlinking %s', filepath); } cb(); }); } vasync.pipeline({funcs: [ function findImage(_, next) { if (options.image === 'latest') { findTarballImageLatest(next); // Check if the value of the parameter `image` is a file } else if (fs.existsSync(options.image)) { filepath = options.image; deleteOnFinish = false; next(); } else { findTarballImageByUuid(next); } }, function ensureSdcInstance(_, next) { var filters = { state: 'active', owner_uuid: self.config.ufds_admin_uuid, 'tag.smartdc_role': 'sdc' }; self.vmapi.listVms(filters, function (vmsErr, vms) { if (vmsErr) { return next(vmsErr); } if (Array.isArray(vms) && !vms.length) { return next(new errors.UpdateError('no "sdc" VM ' + 'instance found')); } sdcZone = vms[0]; return next(); }); }, function saveHistory(_, next) { if (justDownload) { return next(); } changes.push({ service: { name: 'gz-tools' }, type: 'update-service', img: (image ? image : options.image) }); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function downloadTarball(_, next) { if (filepath) { progress('Using gz-tools tarball file %s', filepath); next(); } else { if (image.name !== 'gz-tools' && !options.force) { callback(new errors.UsageError( 'name of image by given uuid is not \'gz-tools\'')); } filepath = format('%s/gz-tools-%s.tgz', localdir, image.uuid); if (fs.existsSync(filepath)) { progress('Using gz-tools tarball file %s ' + 'from previous download', filepath); next(); } else { downloadTarballImage(next); } } }, function decompressTarball(_, next) { if (justDownload) { deleteOnFinish = false; return next(); } var argv = [ '/usr/bin/tar', 'xzvof', filepath, '-C', localdir ]; progress('Decompressing gz-tools tarball'); common.execFilePlus({argv: argv, log: self.log}, next); }, function (_, next) { if (justDownload) { return next(); } updateSdcFiles(next); }, function (_, next) { if (justDownload) { return next(); } updateScripts(next); }, function (_, next) { if (justDownload) { return next(); } updateCnTools(next); }, function (_, next) { if (deleteOnFinish) { cleanup(next); } else { next(); } } ]}, function (err) { if (justDownload) { callback(err); } else if (hist) { if (err) { if (!hist) { self.log.warn('History not saved for update-gz-tools'); return callback(err); } hist.error = err; } if (!hist) { self.log.warn('History not saved for update-gz-tools'); return callback(); } self.history.updateHistory(hist, function (err2) { if (err) { callback(err); } else if (err2) { callback(err2); } else { callback(); } }); } else { callback(err); } }); }; /** * Return an array of candidate images (the full image objects) for a * give service update. If available, the oldest current instance image is * included. * * TODO: support this for a particular instance as well by passing in `inst`. * * @param options {Object} Required. * - service {Object} Required. The service object as from `getServices()`. * - insts {Array} Required. Current DC instances as from `listInsts()`. * @param cb {Function} `function (err, img)` */ SdcAdm.prototype.getCandidateImages = function getCandidateImages(opts, cb) { assert.object(opts, 'opts'); assert.object(opts.service, 'opts.service'); assert.arrayOfObject(opts.insts, 'opts.insts'); assert.func(cb, 'cb'); var self = this; var currImgs = []; var imgs; vasync.pipeline({funcs: [ function getCurrImgs(_, next) { var currImgUuids = {}; opts.insts.forEach(function (inst) { if (inst.service === opts.service.name) { currImgUuids[inst.image] = true; } }); currImgUuids = Object.keys(currImgUuids); if (currImgUuids.length === 0) { // No insts -> use the image_uuid set on the service. assert.ok(opts.service.params.image_uuid, 'service object has no "params.image_uuid": ' + JSON.stringify(opts.service)); currImgUuids.push(opts.service.params.image_uuid); } self.log.debug({currImgUuids: currImgUuids}, 'getCandidateImages: getCurrImgs'); vasync.forEachParallel({inputs: currImgUuids, func: function getImg(imgUuid, nextImg) { self.getImage({uuid: imgUuid}, function (iErr, img) { if (iErr && iErr.body && iErr.body.code === 'ResourceNotFound') { /** * Don't error out for those weird cases where * (a) the image was removed from local imgapi; and * (b) is so old it isn't in the updates server. */ nextImg(); } else if (iErr) { nextImg(iErr); } else { currImgs.push(img); nextImg(); } }); } }, next); }, function getCandidates(_, next) { /** * Which images to consider for an update? Consider a service with * 3 instances at image versions A, A and C. (Note that * `published_at` is the field used to order images with the * same name.) * * Ideally we allow 'B', 'C' and anything after 'C' as candidate * updates. So we'll look for images published after 'A' * (including 'A' to allow same-image updates for dev/testing). */ common.sortArrayOfObjects(currImgs, ['published_at']); var name = self.config.imgNameFromSvcName[opts.service.name]; if (!name) { return next(new errors.InternalError({ message: format('do not know image name for service "%s"', opts.service.name) })); } var filter = { name: name, marker: (currImgs.length > 0 ? currImgs[0].published_at : undefined) }; self.log.debug({filter: filter}, 'getCandidateImages: getCandidates'); self.updates.listImages(filter, function (uErr, followingImgs) { if (uErr) { return next(uErr); } // TOOLS-745: Validate that the name of the retrieved images // matches the name of the service we're trying to update: followingImgs = followingImgs.filter(function (i) { return (i.name === self.config.imgNameFromSvcName[opts.service.name]); }); if (currImgs.length > 0) { // TODO this is wrong, I think we can drop it now // with marker=published_at imgs = [currImgs[0]].concat(followingImgs); } else { imgs = followingImgs; } next(); }); } ]}, function done(err) { cb(err, imgs); }); }; SdcAdm.prototype.acquireLock = function acquireLock(opts, cb) { assert.object(opts, 'opts'); assert.func(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var self = this; var log = self.log; var acquireLogTimeout = setTimeout(function () { opts.progress('Waiting for sdcadm lock'); }, 1000); log.debug({lockPath: self._lockPath}, 'acquire lock'); lock(self._lockPath, function (lockErr, unlock) { if (acquireLogTimeout) { clearTimeout(acquireLogTimeout); } if (lockErr) { cb(new errors.InternalError({ message: 'error acquiring lock', lockPath: self._lockPath, cause: lockErr })); return; } log.debug({lockPath: self._lockPath}, 'acquired lock'); cb(null, unlock); }); }; SdcAdm.prototype.releaseLock = function releaseLock(opts, cb) { assert.object(opts, 'opts'); assert.func(opts.unlock, 'opts.unlock'); assert.func(cb, 'cb'); var self = this; var log = this.log; if (!opts.unlock) { return cb(); } log.debug({lockPath: self._lockPath}, 'releasing lock'); opts.unlock(function (unlockErr) { if (unlockErr) { cb(new errors.InternalError({ message: 'error releasing lock', lockPath: self._lockPath, cause: unlockErr })); return; } log.debug({lockPath: self._lockPath}, 'released lock'); cb(); }); }; /** * Generate an update plan according to the given changes. * The caller should be holding a `<SdcAdm>.acquireLock()`. * * `changes` is an array of objects of the following form: * * 1. create-instance: 'type:create-instance' and 'service' and 'server' * 2. agent delete-instance: * 'type:delete-instance' and 'service' and 'server' * or * 'type:delete-instance' and 'instance' * Where 'instance' for an agent is '$server/$service', e.g. * 'c26c3aba-405b-d04b-b51d-5a68d8f950d7/provisioner'. * 3. vm delete-instance: 'type:delete' and 'instance' (the VM uuid or alias) * 4. delete-service: 'type:delete-service' and 'service' * 5. vm update-instance: 'instance', optional 'type:update-instance' * 6. agent update-instance: * 'service' and 'server' * or * 'instance' * with optional 'type:update-instance'. * 7. update-service: 'service', optional 'type:update-service'. * * Except for 'delete-service', 'image' is optional for all, otherwise the * latest available image is implied. * * @param options {Object} Required. * - changes {Array} Required. The update spec array of objects. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * - forceDataPath {Boolean} Optional. Allows data path components to be * updated. Currently: portolan. * - forceRabbitmq {Boolean} Optional. Allow rabbitmq to be updated, as it * will not be by default * - forceSameImage {Boolean} Optional. Allow an update to proceed even * if the target image is the same as that of the current instance(s). * - skipHACheck {Boolean} Optional. Allow instance creation even * if the service is not supossed to have more than one instance * - justImages {Boolean} Optional. Generate a plan that just imports * the images. Default false. * - updateAll {Boolean} Optional. genUpdatePlan will produce a less noisy * output when updating all existing instances. Default false. * @param cb {Function} Callback of the form `function (err, plan)`. */ SdcAdm.prototype.genUpdatePlan = function genUpdatePlan(options, cb) { assert.object(options, 'options'); assert.arrayOfObject(options.changes, 'options.changes'); assert.optionalFunc(options.progress, 'options.progress'); assert.optionalBool(options.justImages, 'options.justImages'); assert.optionalBool(options.updateAll, 'options.updateAll'); assert.optionalBool(options.forceDataPath, 'opts.forceDataPath'); assert.optionalBool(options.forceRabbitmq, 'options.forceRabbitmq'); assert.optionalBool(options.forceSameImage, 'options.forceSameImage'); assert.optionalString(options.uuid, 'options.uuid'); assert.optionalBool(options.keepAllImages, 'options.keepAllImages'); assert.optionalBool(options.noVerbose, 'options.noVerbose'); // Create instance: assert.optionalBool(options.skipHACheck, 'options.skipHACheck'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var justImages = Boolean(options.justImages); var updateAll = Boolean(options.updateAll); var changes = common.deepObjCopy(options.changes); var servers; var serverFromUuidOrHostname; var svcs; var svcFromName; var insts; var plan; vasync.pipeline({funcs: [ /** * Basic validation of keys of the changes. Validation of values is * later. */ function validateChanges(_, next) { var errs = []; for (var i = 0; i < changes.length; i++) { var change = changes[i]; var repr = JSON.stringify(change); if (change.image) { validateString(change.image, '"image" in ' + repr); } if (change.type === 'create') { // 1. create-instance validateString(change.service, '"service" in ' + repr); validateString(change.server, '"server" in ' + repr); validateKeys(['type', 'server', 'service', 'image'], change, repr); } else if (change.type === 'delete' && change.service && change.server) { // 2. agent delete-instance validateString(change.service, '"service" in ' + repr); validateString(change.server, '"server" in ' + repr); validateKeys(['type', 'server', 'service', 'image'], change, repr); } else if (change.type === 'delete') { // 2. agent delete-instance // 3. vm delete-instance validateString(change.instance, '"instance" in ' + repr); validateKeys(['type', 'instance', 'image'], change, repr); } else if (change.type === 'delete-service') { // 4. delete-service validateString(change.service, '"service" in ' + repr); validateKeys(['type', 'service'], change, repr); } else if (change.service && change.server) { // 6. agent update-instance if (change.type && change.type !== 'update-instance') { errs.push(new errors.ValidationError( 'invalid type "update-instance" change in ' + repr)); } else { change.type = 'update-instance'; } validateString(change.service, '"service" in ' + repr); validateString(change.server, '"server" in ' + repr); validateKeys(['type', 'server', 'service', 'image'], change, repr); } else if (change.instance) { // 5. vm update-instance // 6. agent update-instance if (change.type && change.type !== 'update-instance') { errs.push(new errors.ValidationError( 'invalid type "update-instance" change in ' + repr)); } else { change.type = 'update-instance'; } validateString(change.instance, '"instance" in ' + repr); validateKeys(['type', 'instance', 'image'], change, repr); } else if (change.service) { // 7. update-service if (change.type && change.type !== 'update-service') { errs.push(new errors.ValidationError( 'invalid type "update-service" change in ' + repr)); } else { change.type = 'update-service'; } validateString(change.service, '"service" in ' + repr); validateKeys(['type', 'service', 'image'], change, repr); } else { errs.push(new errors.ValidationError( 'invalid change: ' + repr)); } } if (errs.length === 1) { next(errs[0]); } else if (errs.length > 1) { next(new errors.MultiError(errs)); } else { next(); } function validateString(value, msg) { if (typeof (value) !== 'string') { errs.push(new errors.ValidationError( msg + ' (string) is required')); } } function validateKeys(allowed, change_, repr_) { var extraKeys = Object.keys(change_).filter(function (k) { return !~allowed.indexOf(k); }); if (extraKeys.length) { errs.push(new errors.ValidationError(format( 'invalid extra fields "%s" in %s', extraKeys.join('", "'), repr_))); } } }, function getServers(_, next) { self.cnapi.listServers({ agents: true }, function (err, servers_) { servers = servers_ || []; serverFromUuidOrHostname = {}; for (var i = 0; i < servers.length; i++) { serverFromUuidOrHostname[servers[i].uuid] = servers[i]; serverFromUuidOrHostname[servers[i].hostname] = servers[i]; } next(err); }); }, function getSvcs(_, next) { self.getServices({}, function (err, svcs_) { svcs = svcs_ || []; svcFromName = {}; for (var i = 0; i < svcs.length; i++) { svcFromName[svcs[i].name] = svcs[i]; } next(err); }); }, function getInsts(_, next) { self.listInsts(function (err, insts_) { insts = insts_; next(err); }); }, /** * Normalize fields in each change in the `changes` array from the * convenience inputs (e.g. service="imgapi") to full details * (e.g. service=<the full imgapi SAPI service object>). */ function normalizeChanges(_, next) { if (updateAll) { var serviceNames = changes.map(function (ch) { return ch.service; }).join(', '); if (!options.noVerbose) { progress('Finding candidate update images for %s ' + 'services (%s).', changes.length, serviceNames); } } vasync.forEachParallel({inputs: changes, func: function resolveChange(ch, nextChange) { var changeRepr = JSON.stringify(ch); var i, found; if (ch.service) { if (!svcFromName[ch.service]) { return nextChange(new errors.UpdateError(format( 'unknown service "%s" from %s', ch.service, changeRepr))); } else { ch.service = svcFromName[ch.service]; } } if (ch.uuid) { found = false; for (i = 0; i < insts.length; i++) { if (insts[i].uuid === ch.uuid) { ch.instance = insts[i]; found = true; break; } } if (!found) { return nextChange(new errors.UpdateError(format( 'unknown SDC instance uuid "%s" from %s', ch.uuid, changeRepr))); } } else if (ch.alias) { found = false; for (i = 0; i < insts.length; i++) { if (insts[i].alias === ch.alias) { ch.instance = insts[i]; found = true; break; } } if (!found) { return nextChange(new errors.UpdateError(format( 'unknown SDC instance alias "%s" from %s', ch.alias, changeRepr))); } } if (!ch.service) { p('TODO instance (what is service?):', ch.instance, ch); throw new Error('TODO'); // ch.server = TODO; } if (ch.server) { found = false; for (i = 0; i < servers.length; i++) { if (servers[i].uuid === ch.server || servers[i].hostname === ch.server) { found = true; break; } } if (!found) { return nextChange(new errors.UpdateError(format( 'unknown SDC server "%s" from %s', ch.server, changeRepr))); } } // All candidate images to `ch.images`. Just the single // image if one was specified. if (ch.image) { self.getImage({uuid: ch.image}, function (iErr, img) { if (iErr) { return nextChange(new errors.UpdateError( iErr, format('unknown image "%s" from %s', ch.image, changeRepr))); } ch.images = [img]; delete ch.image; nextChange(); }); } else { if (!updateAll && !options.noVerbose) { progress('Finding candidate update images ' + 'for the "%s" service.', ch.service.name); } self.getCandidateImages({ service: ch.service, insts: insts }, function (iErr, imgs) { if (iErr) { return nextChange(iErr); } ch.images = imgs; log.debug({serviceName: ch.service.name}, '%d candidate images (including current)', imgs.length); nextChange(); }); } } }, next); }, /** * Kinds of conflicts: * - action on a service *and* an instance of the same service * - two actions on the same service * - two actions on the same instance */ function checkForConflictingChanges(_, next) { function reprFromChange(ch_) { return JSON.stringify({ type: ch_.type, service: ch_.service.name, instance: ch_.instance && ch_.instance.instance }); } var changeFromSvc = {}; var changeFromInst = {}; var i, ch, typeTarg, svc; for (i = 0; i < changes.length; i++) { ch = changes[i]; // e.g. 'update-service' -> 'service' // (Some instance changes like 'delete' or 'create' do not // include the two pieces). typeTarg = ch.type.split('-')[1] || 'instance'; if (typeTarg === 'service') { svc = ch.service.name; if (changeFromSvc[svc]) { return next(new errors.UpdateError(format( 'conflict: cannot make multiple changes to the ' + 'same service: %s and %s', reprFromChange(ch), reprFromChange(changeFromSvc[svc])))); } changeFromSvc[svc] = ch; } else { assert.equal(typeTarg, 'instance'); var inst = (ch.instance) ? ch.instance.instance : null; if (changeFromInst[inst]) { return next(new errors.UpdateError(format( 'conflict: cannot make multiple changes to the ' + 'same instance: %s and %s', reprFromChange(ch), reprFromChange(changeFromInst[inst])))); } changeFromInst[inst] = ch; } } for (i = 0; i < changes.length; i++) { ch = changes[i]; typeTarg = ch.type.split('-')[1] || 'instance'; if (typeTarg === 'instance') { svc = ch.service.name; if (changeFromSvc[svc]) { return next(new errors.UpdateError(format( 'conflict: cannot make changes to a service and ' + 'an instance of that service: %s and %s', reprFromChange(ch), reprFromChange(changeFromSvc[svc])))); } } } next(); }, /** * Drop service or inst updates that have no available update * candidates. */ function dropNoops(_, next) { changes = changes.filter(function (ch) { if (ch.type === 'update-service' || ch.type === 'update-instance') { if (ch.images.length === 0) { // No available update candidates were found. log.debug({change: ch}, 'dropNoop: no update candidates'); return false; } // Exclude update to the same image as all current insts, // unless --force-same-image. if (!options.forceSameImage) { var currImgUuids = {}; insts.forEach(function (inst) { if (inst.service === ch.service.name) { currImgUuids[inst.image] = true; } }); currImgUuids = Object.keys(currImgUuids); if (currImgUuids.length === 0) { // No insts -> use the image_uuid set on the // service. assert.ok(ch.service.params.image_uuid, 'service object has no "params.image_uuid": ' + JSON.stringify(ch.service)); currImgUuids.push(ch.service.params.image_uuid); } if (currImgUuids.length === 1) { var sansCurr = ch.images.filter(function (img) { return (img.uuid !== currImgUuids[0]); }); if (sansCurr.length === 0) { log.debug( {change: ch, currImgUuids: currImgUuids}, 'dropNoop: same image as all insts'); return false; } } } } return true; }); next(); }, /** * This is where we use inter-image dependencies to (a) resolve * candidate `images` for each change down to a single `image`, and * (b) add additional updates if required. * * We don't yet support deps (see: sdc-update project M9), so the * only step here is to select the latest candidate image. */ function resolveDeps(_, next) { log.debug({changes: changes}, 'resolveDeps'); for (var i = 0; i < changes.length; i++) { var ch = changes[i]; if (!ch.image && ch.images.length) { assert.arrayOfObject(ch.images, 'changes['+i+'].images'); // Assuming that `ch.images` is already sorted by // `published_at`. ch.images.sort(function (a, b) { return common.cmp(a.published_at, b.published_at); }); ch.image = ch.images[ch.images.length - 1]; } if (!options.keepAllImages) { delete ch.images; } } next(); }, function disallowRabbitmqUpdates(_, next) { for (var i = 0; i < changes.length; i++) { var ch = changes[i]; if (ch.service && ch.service.name === 'rabbitmq' && !options.forceRabbitmq) { var changeRepr = JSON.stringify({ type: ch.type, service: ch.service.name, instance: ch.instance && ch.instance.instance }); return next(new errors.UpdateError(format( 'rabbitmq updates are locked: %s ' + '(use --force-rabbitmq flag)', changeRepr))); } } next(); }, function disallowDataPathUpdates(_, next) { var dataPath = ['portolan']; for (var i = 0; i < changes.length; i++) { var ch = changes[i]; if (ch.service && dataPath.indexOf(ch.service.name) !== -1 && !options.forceDataPath) { var changeRepr = JSON.stringify({ type: ch.type, service: ch.service.name, instance: ch.inst && ch.instance.instance }); return next(new errors.UpdateError(format( '%s updates are locked: %s ' + '(use --force-data-path flag)', ch.service.name, changeRepr))); } } next(); }, function ensureVmMinPlatform(_, next) { var ch, server; var errs = []; for (var i = 0; i < changes.length; i++) { ch = changes[i]; if (ch.service.type !== 'vm') { continue; } if (ch.type === 'update-service') { for (var j = 0; j < insts.length; j++) { var inst = insts[j]; if (inst.service === ch.service.name) { server = serverFromUuidOrHostname[inst.server]; if (server.current_platform < self.config.vmMinPlatform) { errs.push(new errors.UpdateError(format( 'insufficient platform for service "%s" ' + 'instance "%s" on server "%s" (current ' + 'platform is "%s", require minimum "%s")', inst.service, inst.instance, inst.server, server.current_platform, self.config.vmMinPlatform))); } } } } else if (ch.type === 'update-instance') { throw new Error('TODO'); } else if (ch.type === 'create-instance') { server = serverFromUuidOrHostname[ch.server]; throw new Error('TODO'); } } if (errs.length) { var er = (errs.length === 1) ? errs[0] : new errors.MultiError(errs); next(er); } else { next(); } }, function minImageBuildDateFromSvcName(_, next) { if (options.forceBypassMinImage) { return next(); } var ch, server; var errs = []; for (var i = 0; i < changes.length; i++) { ch = changes[i]; if (ch.service.type !== 'vm') { continue; } if (ch.type === 'update-service') { for (var j = 0; j < insts.length; j++) { var inst = insts[j]; if (inst.service !== ch.service.name) { continue; } if (!self.config.svcMinImages[inst.service]) { continue; } var minImg = self.config.svcMinImages[inst.service]; if (!inst.version) { var msg = format('Unknown image ' + 'version for service "%s". Cannot evaluate ' + 'if minimal requirements for update are met ' + 'by the current image. This can be fixed ' + 'by re-importing the image into the DC via:' + '\n\n\tsdc-imgadm '+ 'import %s -s https://updates.joyent.com?' + 'channel=*', inst.service, inst.image); errs.push(new errors.UpdateError(msg)); continue; } var parts = inst.version.split('-'); var curImg = parts[parts.length - 2]; if (minImg > curImg) { errs.push(new errors.UpdateError(format( 'image for service "%s" is too old for ' + 'sdcadm update (min image build date ' + 'is "%s" current image build date is "%s")', inst.service, minImg, curImg ))); } } } else if (ch.type === 'update-instance') { throw new Error('TODO'); } else if (ch.type === 'create-instance') { server = serverFromUuidOrHostname[ch.server]; console.log(server); // shut make check up about unused var throw new Error('TODO'); } } if (errs.length) { var er = (errs.length === 1) ? errs[0] : new errors.MultiError(errs); next(er); } else { next(); } }, function createPlan(_, next) { log.debug({changes: changes}, 'createPlan'); var targ = common.deepObjCopy(insts); for (var i = 0; i < changes.length; i++) { var ch = changes[i]; switch (ch.type) { case 'update-service': for (var j = 0; j < targ.length; j++) { var inst = targ[j]; if (inst.service === ch.service.name) { inst.image = ch.image.uuid; inst.version = ch.image.version; } } break; case 'create': // Create instance for an existing service: if (options.skipHACheck) { ch.force = true; } break; // TODO: other change types default: return next(new errors.InternalError({ message: 'unknown ch.type: ' + ch.type })); } } plan = new UpdatePlan({ curr: insts, targ: targ, changes: changes, justImages: justImages }); next(); }, function determineProcedures(_, next) { procedures.coordinatePlan({ plan: plan, sdcadm: self, serverFromUuidOrHostname: serverFromUuidOrHostname, log: log, progress: progress, noVerbose: options.noVerbose }, function (err, procs_) { plan.procs = procs_; next(err); }); } ]}, function finishUp(err) { cb(err, plan); }); }; SdcAdm.prototype.summarizePlan = function summarizePlan(options) { assert.object(options, 'options'); assert.object(options.plan, 'options.plan'); assert.optionalFunc(options.progress, 'options.progress'); var summary = options.plan.procs.map( function (proc) { return proc.summarize(); }).join('\n'); options.progress(common.indent(summary)); }; /** * Execute an update plan. * The caller should be holding a `<SdcAdm>.acquireLock()`. * * @param options {Object} Required. * - plan {Object} Required. The update plan as returned by * `genUpdatePlan`. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * - dryRun {Boolean} Optional. Default false. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.execUpdatePlan = function execUpdatePlan(options, cb) { assert.object(options, 'options'); assert.object(options.plan, 'options.plan'); assert.optionalFunc(options.progress, 'options.progress'); assert.optionalBool(options.dryRun, 'options.dryRun'); assert.optionalString(options.uuid, 'options.uuid'); // We need a pointer to the update directory when we're trying to rollback: assert.optionalString(options.upDir, 'options.upDir'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var plan = options.plan; var rollback = plan.rollback || false; var start = new Date(); var wrkDir; var hist; vasync.pipeline({funcs: [ function createWrkDir(_, next) { var stamp = sprintf('%d%02d%02dT%02d%02d%02dZ', start.getUTCFullYear(), start.getUTCMonth()+1, start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds()); wrkDir = (rollback ? '/var/sdcadm/rollbacks/' : '/var/sdcadm/updates/' ) + stamp; progress('Create work dir: ' + wrkDir); if (options.dryRun) { return next(); } mkdirp(wrkDir, function (err) { if (err) { next(new errors.InternalError({ message: 'error creating work dir: ' + wrkDir, cause: err })); return; } next(); }); }, function savePlan(_, next) { if (options.dryRun) { return next(); } var planFile = path.resolve(wrkDir, 'plan.json'); fs.writeFile(planFile, plan.serialize(), 'utf8', function (err) { if (err) { return next(new errors.InternalError({ cause: err, message: 'error saving update plan: ' + planFile })); } next(); }); }, function saveBeginningToHistory(_, next) { if (options.dryRun || options.justImages) { return next(); } var obj = { changes: plan.changes }; if (options.uuid) { obj.uuid = options.uuid; } if (options.dryRun) { return next(); } self.history.saveHistory(obj, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function execProcedures(_, next) { if (options.dryRun) { return next(); } vasync.forEachPipeline({ inputs: plan.procs, func: function execProc(proc, nextProc) { log.debug({summary: proc.summarize()}, 'execProc'); proc.execute({ sdcadm: self, plan: plan, progress: progress, log: log, wrkDir: wrkDir, upDir: options.upDir }, nextProc); } }, next); } ]}, function (err) { if (options.dryRun || options.justImages) { return cb(err); } // Add error to history in case the update execution failed: if (err) { // TOOLS-879: sdcadm update should tell user about the error: progress('Update error: %j', err); if (!hist) { self.log.warn('History not saved for update'); return cb(err); } hist.error = err; } if (!hist) { self.log.warn('History not saved for update'); return cb(); } // No need to add `history.finished` here, History instance will handle self.history.updateHistory(hist, function (err2, hist2) { if (err) { cb(err); } else if (err2) { cb(err2); } else { cb(); } }); }); }; /** * Update to the latest available sdcadm package. * * TODO: * - support passing in a package UUID to which to update * * @param options {Object} Required. * - allowMajorUpdate {Boolean} Optional. Default false. By default * self-update will only consider versions of the same major version. * - dryRun {Boolean} Optional. Default false. Go through the motions * without actually updating. * - progress {Function} Optional. A function that is called * with progress messages. Called as `progress(<string>)`. E.g. passing * console.log is legal. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.selfUpdate = function selfUpdate(options, cb) { assert.object(options, 'options'); assert.optionalBool(options.allowMajorUpdate, 'options.allowMajorUpdate'); assert.optionalBool(options.dryRun, 'options.dryRun'); assert.optionalFunc(options.progress, 'options.progress'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var unlock; var dryRunPrefix = (options.dryRun ? '[dry-run] ' : ''); var currVer = pkg.version; var currBuildtime; var updateManifest; var installerPath; var start; var wrkDir; var hist; var changes = [ { type: 'service', service: { type: 'service', name: 'sdcadm', version: currVer } }]; vasync.pipeline({funcs: [ function getLock(_, next) { if (options.dryRun) { return next(); } self.acquireLock({progress: progress}, function (lockErr, unlock_) { unlock = unlock_; next(lockErr); }); }, function setStart(_, next) { // Set start time after getting lock to avoid collisions in wrkDir. start = new Date(); next(); }, function getCurrBuildtime(_, next) { // SDC buildstamps are '$branch-$buildtime-g$sha'. The '$branch' // can have hyphens in it. var buildstampPath = path.resolve(__dirname, '..', 'etc', 'buildstamp'); fs.readFile(buildstampPath, 'utf8', function (err, data) { if (err) { next(new errors.InternalError({ message: 'error getting current buildstamp', path: buildstampPath, cause: err })); return; } var parts = data.trim().split(/-/g); // Drop possible '-dirty' on the buildstamp. if (parts[parts.length - 1] === 'dirty') { parts.pop(); } currBuildtime = parts[parts.length - 2]; changes[0].service.build = data.trim(); next(); }); }, function findLatestSdcAdm(_, next) { var filters = { name: 'sdcadm' }; self.updates.listImages(filters, function (err, candidates) { if (err) { return next(new errors.SDCClientError(err, 'updates')); } // Filter out versions before the current. candidates = candidates.filter(function dropLowerVer(c) { if (semver.lt(c.version, currVer)) { //log.trace({candidate: c, currVer: currVer}, // 'drop sdcadm candidate (lower ver)'); return false; } return true; }); // Unless `allowMajorUpdate`, filter out major updates (and // warn). if (!options.allowMajorUpdate) { var currMajor = currVer.split(/\./)[0] + '.x'; var droppedVers = []; candidates = candidates.filter(function dropMajor(c) { var drop = !semver.satisfies(c.version, currMajor); if (drop) { droppedVers.push(c.version); log.trace({candidate: c, currMajor: currMajor}, 'drop sdcadm candidate (major update)'); } return !drop; }); if (droppedVers.length) { droppedVers.sort(semver.compare); progress('Skipping available major sdcadm ' + 'update, version %s (use --allow-major-update ' + 'to allow)', droppedVers[droppedVers.length - 1]); } } // Filter out buildstamps <= the current (to exclude // earlier builds at the same `version`). candidates = candidates.filter(function dropLowerStamp(c) { var buildtime = c.tags.buildstamp.split(/-/g) .slice(-2, -1)[0]; if (buildtime <= currBuildtime) { log.trace({candidate: c, buildtime: buildtime, currBuildtime: currBuildtime}, 'drop sdcadm candidate (<= buildtime)'); return false; } return true; }); // Sort by (version, publish date) and select the latest if (candidates.length) { candidates.sort(function (a, b) { var ver = semver.compare(a.version, b.version); if (ver) { return ver; } var aParts = a.tags.buildstamp.split('-'); var bParts = b.tags.buildstamp.split('-'); var aStamp = aParts[aParts.length - 2]; var bStamp = bParts[bParts.length - 2]; if (aStamp > bStamp) { return 1; } else if (aStamp < bStamp) { return -1; } else { return 0; } }); updateManifest = candidates[candidates.length - 1]; changes[0].image = updateManifest; progress('%sUpdate to sdcadm %s (%s)', dryRunPrefix, updateManifest.version, updateManifest.tags.buildstamp); } else { var ch = self.updates.channel; progress('Already up-to-date (using %s update channel).', ch ? '"'+ch+'"' : 'default'); } next(); }); }, function saveChangesToHistory(_, next) { if (!updateManifest || options.dryRun) { return next(); } self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } hist = hst; return next(); }); }, function downloadInstaller(_, next) { if (!updateManifest) { return next(); } progress('%sDownload update from %s', dryRunPrefix, self.config.updatesServerUrl); if (options.dryRun) { return next(); } // TODO progress bar on this installerPath = '/var/tmp/sdcadm-' + updateManifest.uuid; self.updates.getImageFile(updateManifest.uuid, installerPath, function (downloadErr) { if (downloadErr) { next(new errors.InternalError({ message: 'error downloading sdcadm package', updatesServerUrl: self.config.updatesServerUrl, uuid: updateManifest.uuid, cause: downloadErr })); return; } fs.chmod(installerPath, 0755, function (chmodErr) { if (chmodErr) { next(new errors.InternalError({ message: 'error chmoding sdcadm installer', path: installerPath, cause: chmodErr })); return; } next(); }); }); }, function createWrkDir(_, next) { if (!updateManifest) { return next(); } var stamp = sprintf('%d%02d%02dT%02d%02d%02dZ', start.getUTCFullYear(), start.getUTCMonth()+1, start.getUTCDate(), start.getUTCHours(), start.getUTCMinutes(), start.getUTCSeconds()); wrkDir = '/var/sdcadm/self-updates/' + stamp; mkdirp(wrkDir, function (err) { if (err) { next(new errors.InternalError({ message: 'error creating work dir: ' + wrkDir, cause: err })); return; } next(); }); }, function runInstaller(_, next) { if (!updateManifest) { return next(); } progress('%sRun sdcadm installer (log at %s/install.log)', dryRunPrefix, wrkDir); if (options.dryRun) { return next(); } var cmd = format('%s >%s/install.log 2>&1', installerPath, wrkDir); var env = common.objCopy(process.env); env.TRACE = '1'; env.SDCADM_LOGDIR = wrkDir; // bwcompat for sdcadm <1.2.0 installers env.SDCADM_WRKDIR = wrkDir; var execOpts = {env: env}; log.trace({cmd: cmd}, 'run sdcadm installer'); exec(cmd, execOpts, function (err, stdout, stderr) { log.trace({cmd: cmd, err: err, stdout: stdout, stderr: stderr}, 'ran sdcadm installer'); if (err) { // TODO: The installer *does* typically restore the old one // on failure. There is a swap (two `mv`s) during which a // crash will leave in inconsistent state. We could check // for that here and cleanup, or just warn about the // situation. return next(new errors.InternalError({ message: 'error running sdcadm installer', cmd: cmd, stdout: stdout, stderr: stderr, cause: err })); } next(); }); } ]}, function finishUp(err) { vasync.pipeline({funcs: [ function dropLock(_, next) { if (options.dryRun) { return next(); } self.releaseLock({unlock: unlock}, next); }, function updateHist(_, next) { if (!updateManifest || options.dryRun) { return next(); } // Add error to history in case the update execution failed: if (err) { if (!hist) { self.log.warn('History not set for self-update'); return next(err); } hist.error = err; } if (!hist) { self.log.warn('History not set for self-update'); return next(); } // No need to add `history.finished` here: self.history.updateHistory(hist, function (err2, hist2) { if (err2) { next(err2); } else { next(); } }); }, function noteCompletion(_, next) { if (!updateManifest || err) { return next(); } progress('%sUpdated to sdcadm %s (%s, elapsed %ss)', dryRunPrefix, updateManifest.version, updateManifest.tags.buildstamp, Math.floor((Date.now() - start) / 1000)); next(); } ]}, function done(finishUpErr) { // We shouldn't ever get a `finishUpErr`. Let's be loud if we do. if (finishUpErr) { log.fatal({err: finishUpErr}, 'unexpected error finishing up self-update'); } cb(err || finishUpErr); }); }); }; SdcAdm.prototype._dcMaintInfoPath = '/var/sdcadm/dc-maint.json'; /** * Maintenance mode current status. * * @param cb {Function} Callback of the form `function (err, status)`. * where `status` is an object like the following: * {maint: false} // not in maint mode * {maint: true} // in maint mode, don't have start time * {maint: true, startTime: <date>} */ SdcAdm.prototype.dcMaintStatus = function dcMaintStatus(cb) { assert.func(cb, 'cb'); var self = this; var log = self.log; var sdcApp = self.sdc; var services = {}; var maint = false; var cloudapiMaint; var dockerMaint; var startTime; vasync.pipeline({funcs: [ function getCloudapiSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'cloudapi' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } else if (!svcs || svcs.length !== 1) { return next(); } services.cloudapi = svcs[0]; next(); }); }, function getDockerSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'docker' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } else if (!svcs || svcs.length !== 1) { return next(); } services.docker = svcs[0]; next(); }); }, function checkIfInMaint(_, next) { cloudapiMaint = services.cloudapi && services.cloudapi.metadata && services.cloudapi.metadata.CLOUDAPI_READONLY; dockerMaint = services.docker && services.docker.metadata && services.docker.metadata.DOCKER_READONLY; log.debug({cloudapi_maint: cloudapiMaint}, 'maint mode from CLOUDAPI_READONLY'); log.debug({docker_maint: dockerMaint}, 'maint mode from DOCKER_READONLY'); next(); }, /** * Showing the start time is strictly a convenience. */ function loadStartTime(_, next) { if (!cloudapiMaint || !dockerMaint) { return next(); } else { maint = true; } fs.readFile(self._dcMaintInfoPath, 'utf8', function (err, content) { if (err) { // This is a convenience step. Just note this. log.warn({dcMaintInfoPath: self._dcMaintInfoPath, err: err}, 'could not loading dc-maint info file'); } else { try { startTime = JSON.parse(content).startTime; } catch (parseErr) { log.warn(parseErr, 'could not parse dc-maint info file'); } } next(); }); } ]}, function (err) { if (err) { cb(err); } else { var status = {maint: maint}; if (startTime) { status.startTime = startTime; } cb(null, status); } }); }; /** * Enter maintenance mode. * * @param opts {Object} Required. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.dcMaintStart = function dcMaintStart(opts, cb) { assert.object(opts, 'opts'); assert.optionalFunc(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var self = this; var progress = opts.progress || function () {}; var sdcApp = self.sdc; var services = {}; var headnode; var putCloudapiIntoMaint = false; var putDockerIntoMaint = false; var startTime; vasync.pipeline({funcs: [ function getHeadnode(_, next) { self.cnapi.listServers({ headnode: true }, function (err, servers) { if (err) { return next(new errors.SDCClientError(err, 'cnapi')); } headnode = servers[0]; return next(); }); }, function getCloudapiSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'cloudapi' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.cloudapi = svcs && svcs.length && svcs[0]; next(); }); }, function getDockerSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'docker' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.docker = svcs && svcs.length && svcs[0]; next(); }); }, function getSapiInstances(_, next) { progress('Getting SDC\'s sapi instances from SAPI'); var keys = Object.keys(services); vasync.forEachParallel({ inputs: keys, func: function (key, feNext) { var serviceUuid = services[key].uuid; self.sapi.listInstances({ service_uuid: serviceUuid }, function (instErr, insts) { if (instErr) { return feNext(instErr); } if (!insts.length) { progress('No ' + key + ' instances to update'); delete services[key]; feNext(); return; } services[key].zone = insts[0]; return feNext(); }); }}, function (err) { next(err); }); }, function checkIfCloudapiInMaint(_, next) { if (services.cloudapi) { if (services.cloudapi.metadata.CLOUDAPI_READONLY === true) { progress('Cloudapi service already in read-only mode'); } else { putCloudapiIntoMaint = true; } } next(); }, function checkIfDockerInMaint(_, next) { if (services.docker) { if (services.docker.metadata.DOCKER_READONLY === true) { progress('Docker service already in read-only mode'); } else { putDockerIntoMaint = true; } } next(); }, function setCloudapiReadonly(_, next) { if (!putCloudapiIntoMaint) { return next(); } progress('Putting cloudapi in read-only mode'); startTime = new Date(); self.sapi.updateService( services.cloudapi.uuid, { metadata: {CLOUDAPI_READONLY: true } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function setDockerReadonly(_, next) { if (!putDockerIntoMaint) { return next(); } progress('Putting docker in read-only mode'); startTime = new Date(); self.sapi.updateService( services.docker.uuid, { metadata: { DOCKER_READONLY: true } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function maybeRefreshCloudapiConfigAgent(_, next) { var zone = services.cloudapi && services.cloudapi.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, function maybeRefreshDockerConfigAgent(_, next) { var zone = services.docker && services.docker.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, /** * TODO: add readonly status to /--ping on cloudapi and watch for that. */ function saveStartTime(_, next) { if (!putCloudapiIntoMaint && !putDockerIntoMaint) { return next(); } var info = JSON.stringify({ 'startTime': startTime }, null, 4); fs.writeFile(self._dcMaintInfoPath, info, 'utf8', next); }, function waitForWorkflowDrain(_, next) { progress('Waiting up to 5 minutes for workflow jobs to drain'); var remaining = 60; var MAX_ERRS = 3; var numErrs = 0; setTimeout(pollJobs, 5000); function pollJobs() { remaining--; if (remaining <= 0) { return next(new errors.InternalError({ message: 'timeout waiting for workflow jobs to drain' })); } self.wfapi.listJobs({execution: 'running', limit: 10}, function (rErr, rJobs) { if (rErr) { numErrs++; self.log.error(rErr, 'error listing running jobs'); if (numErrs >= MAX_ERRS) { return next(rErr); } } else if (rJobs.length > 0) { self.log.debug({numJobs: rJobs.length}, 'running jobs'); return setTimeout(pollJobs, 5000); } self.wfapi.listJobs({execution: 'queued', limit: 10}, function (qErr, qJobs) { if (qErr) { numErrs++; self.log.error(qErr, 'error listing queued jobs'); if (numErrs >= MAX_ERRS) { return next(qErr); } } else if (qJobs.length > 0) { self.log.debug({numJobs: qJobs.length}, 'queued jobs'); return setTimeout(pollJobs, 5000); } progress('Workflow cleared of running and queued jobs'); next(); }); }); } } ]}, cb); }; /** * Leave maintenance mode. * * @param opts {Object} Required. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * @param cb {Function} Callback of the form `function (err)`. */ SdcAdm.prototype.dcMaintStop = function dcMaintStop(opts, cb) { assert.object(opts, 'opts'); assert.optionalFunc(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = opts.progress || function () {}; var headnode; var sdcApp = self.sdc; var services = {}; var disableCloudapiMaint = false; var disableDockerMaint = false; vasync.pipeline({funcs: [ function getHeadnode(_, next) { self.cnapi.listServers({ headnode: true }, function (err, servers) { if (err) { return next(new errors.SDCClientError(err, 'cnapi')); } headnode = servers[0]; return next(); }); }, function getCloudapiSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'cloudapi' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.cloudapi = svcs && svcs.length && svcs[0]; next(); }); }, function getDockerSvc(_, next) { var filters = { application_uuid: sdcApp.uuid, name: 'docker' }; self.sapi.listServices(filters, function (svcsErr, svcs) { if (svcsErr) { return next(new errors.SDCClientError(svcsErr, 'sapi')); } services.docker = svcs && svcs.length && svcs[0]; next(); }); }, function getSapiInstances(_, next) { progress('Getting SDC\'s sapi instances from SAPI'); var keys = Object.keys(services); vasync.forEachParallel({ inputs: keys, func: function (key, feNext) { var serviceUuid = services[key].uuid; self.sapi.listInstances({ service_uuid: serviceUuid }, function (instErr, insts) { if (instErr) { return feNext(instErr); } if (!insts.length) { progress('No ' + key + ' instances to update'); delete services[key]; feNext(); return; } services[key].zone = insts[0]; return feNext(); }); }}, function (err) { next(err); }); }, function checkIfCloudapiInMaint(_, next) { if (services.cloudapi) { if (services.cloudapi.metadata.CLOUDAPI_READONLY !== true) { progress('Cloudapi service is not in read-only mode'); } else { disableCloudapiMaint = true; } } next(); }, function checkIfDockerInMaint(_, next) { if (services.docker) { if (services.docker.metadata.DOCKER_READONLY !== true) { progress('Docker service is not in read-only mode'); } else { disableDockerMaint = true; } } next(); }, function setCloudapiWriteable(_, next) { if (!disableCloudapiMaint) { return next(); } progress('Taking cloudapi out of read-only mode'); self.sapi.updateService( services.cloudapi.uuid, { metadata: { CLOUDAPI_READONLY: false } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function setDockerWriteable(_, next) { if (!disableDockerMaint) { return next(); } progress('Taking docker out of read-only mode'); self.sapi.updateService( services.docker.uuid, { metadata: { DOCKER_READONLY: false } }, function (err, svc) { if (err) { return next(new errors.SDCClientError(err, 'sapi')); } next(); }); }, function maybeRefreshCloudapiConfigAgent(_, next) { var zone = services.cloudapi && services.cloudapi.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, function maybeRefreshDockerConfigAgent(_, next) { var zone = services.docker && services.docker.zone; if (zone) { svcadm.svcadmRefresh({ server_uuid: headnode.uuid, zone: zone.uuid, wait: true, fmri: 'config-agent', sdcadm: self, log: self.log }, next); } else { next(); } }, /** * Note: We aren't waiting for config-agent in the cloudapi instance(s) * to effect this change. TODO: add readonly status to /--ping on * cloudapi and watch for that. ... on all instances? */ function rmInfoFile(_, next) { if (!disableCloudapiMaint && !disableDockerMaint) { return next(); } fs.unlink(self._dcMaintInfoPath, function (err) { if (err) { // The info file is sugar. Don't fail if it isn't there. log.warn({dcMaintInfoPath: self._dcMaintInfoPath, err: err}, 'could not remove dc-maint info file'); } next(); }); } ]}, cb); }; /** * Check SAPI config against system "reality" and print out inconsistencies * * @param cb {Function} Callback of the form `function (err, result)`. */ SdcAdm.prototype.checkConfig = function (opts, cb) { var self = this; // SAPI values for sdc application: var sdc = self.sdc.metadata; // Name of SAPI services for VMs: var services; // Headnode sysinfo: var sysinfo; // External and admin networks: var admin; var external; // Errors: var errs = []; function getSysinfo(_, next) { self.cnapi.listServers({ headnode: true, extras: 'sysinfo' }, function (err, res) { if (err) { return next(err); } sysinfo = (res && res.length > 0 ? res[0].sysinfo : null); Object.keys(sysinfo['Network Interfaces']).filter(function (k) { return (sysinfo['Network Interfaces'][k]['NIC Names'][0] === 'admin'); }).map(function (k) { if (sysinfo['Network Interfaces'][k]['MAC Address'] !== sdc.admin_nic) { errs.push('SAPI sdc admin_nic did not match with GZ ' + 'Admin MAC Address'); } if (sysinfo['Network Interfaces'][k].ip4addr !== sdc.admin_ip) { errs.push('SAPI sdc admin_ip did not match with GZ ' + 'Admin IPv4 Address'); } }); Object.keys(sysinfo['Virtual Network Interfaces']). filter(function (k) { return (k === 'external0'); }).map(function (k) { if (sysinfo['Virtual Network Interfaces'][k].ip4addr !== sdc.external_ip) { errs.push('SAPI sdc external_ip did not match with GZ ' + 'External IPv4 Address'); } }); return next(); }); } function getNetworks(_, next) { self.napi.listNetworks({name: 'admin'}, function (err, res) { if (err) { return next(err); } admin = (res && res.length > 0 ? res[0] : null); if (admin.subnet.split('/')[0] !== sdc.admin_network) { errs.push('SAPI sdc admin_network did not match with value '+ 'defined in NAPI'); } if (admin.netmask !== sdc.admin_netmask) { errs.push('SAPI sdc admin_netmask did not match with value '+ 'defined in NAPI'); } // PEDRO: Note we should stop assuming external network will always // exist and, therefore, shouldn't return error on the next NAPI // call: self.napi.listNetworks({name: 'external'}, function (err2, res2) { if (err2) { return next(err2); } external = (res2 && res2.length > 0 ? res2[0] : null); if (external.subnet && external.subnet.split('/')[0] !== sdc.external_network) { errs.push('SAPI sdc external_network did not match with '+ 'value defined in NAPI'); } if (external.netmask !== sdc.external_netmask) { errs.push('SAPI sdc external_netmask did not match with '+ 'value defined in NAPI'); } if (external.gateway !== sdc.external_gateway) { errs.push('SAPI sdc external_gateway did not match with '+ 'value defined in NAPI'); } if (external.provision_start_ip !== sdc.external_provisionable_start) { errs.push('SAPI sdc external_provisionable_start did not '+ 'match with value defined in NAPI'); } if (external.provision_end_ip !== sdc.external_provisionable_end) { errs.push('SAPI sdc external_provisionable_end did not '+ 'match with value defined in NAPI'); } return next(); }); }); } function getDcFromUfds(_, next) { self.ufds.search('o=smartdc', { scope: 'sub', filter: sprintf('(&(objectclass=datacenter)(datacenter=%s))', self.config.datacenter_name) }, function (err, res) { if (err) { return next(err); } if (!res) { errs.push('No DC information found in UFDS'); return next(); } res.forEach(function (r) { if (r.region !== sdc.region_name) { errs.push(sprintf( 'region did not match with region_name for entry ' + 'with DN: %s', r.dn)); } if (r.datacenter !== sdc.datacenter_name) { errs.push(sprintf( 'data center did not match with datacenter_name for ' + 'entry with DN: %s', r.dn)); } // company_name and location are not required for anything to // work properly, therefore, skipping them here }); return next(); }); } function getUfdsAdmin(_, next) { self.ufds.search('o=smartdc', { scope: 'sub', filter: sprintf('(&(objectclass=sdcperson)(uuid=%s))', self.config.ufds_admin_uuid) }, function (err, res) { if (err) { return next(err); } var ufdsAdmin = (res && res.length > 0 ? res[0] : null); if (!ufdsAdmin) { errs.push('Cannot find UFDS admin user'); } if (ufdsAdmin.login !== sdc.ufds_admin_login) { errs.push('UFDS admin login did not match SAPI ' + 'ufds_admin_login'); } if (ufdsAdmin.email !== sdc.ufds_admin_email) { errs.push('UFDS admin email did not match SAPI ' + 'ufds_admin_email'); } self.ufds.search(sprintf('uuid=%s, ou=users, o=smartdc', self.config.ufds_admin_uuid), { scope: 'sub', filter: sprintf('(objectclass=sdckey)', self.config.ufds_admin_key_fp) }, function (err2, res2) { if (err2) { return next(err2); } if (!res2.length) { errs.push('Cannot find UFDS admin key'); return next(); } var sdcKey = res2.filter(function (k) { return (k.fingerprint === sdc.ufds_admin_key_fingerprint); })[0]; if (!sdcKey) { errs.push('Cannot find UFDS admin key'); return next(); } if (sdcKey.openssh !== sdc.ufds_admin_key_openssh.trim()) { errs.push('UFDS Admin key did not match with SAPI '+ 'ufds_admin_key_openssh'); } return next(); }); }); } // PEDRO: Shall we really care about core zone Admin IP addresses here?: // (Ignoring for now) function getVmsIps(_, next) { var filters = { query: sprintf('(&(tags=*-smartdc_type=core-*)' + '(|(state=running)(state=provisioning)(state=stopped))' + '(owner_uuid=%s))', self.config.ufds_admin_uuid) }; self.vmapi.listVms(filters, function (vmsErr, _vms) { if (vmsErr) { return next(vmsErr); } return next(); }); } self.sapi.listServices({ application_uuid: sdc.uuid }, function (err2, res2) { if (err2) { return cb(err2); } if (!res2.length) { return cb('Cannot find SDC services in SAPI'); } services = res2.filter(function (s) { return (s.type === 'vm'); }).map(function (s) { return (s.name); }); vasync.pipeline({ funcs: [ getSysinfo, getNetworks, getDcFromUfds, getUfdsAdmin, getVmsIps ] }, function (err4, _res) { if (err4) { return cb(err4); } // PEDRO: Note the exceptions listed below. I bet we could // remove most of these variables anyway, and left a single // value for *_pw. services.forEach(function (s) { if (!sdc[s + '_root_pw'] && s !== 'manta' && s !== 'sapi') { errs.push(sprintf('Missing %s_root_pw in SAPI', s)); } if (!sdc[s + '_admin_ips'] && s !== 'cloudapi' && s !== 'manta' && s !== 'sdcsso') { errs.push(sprintf('Missing %s_admin_ips in SAPI', s)); } if (s !== 'manatee' && s !== 'binder' && s !== 'manta' && s !== 'cloudapi') { if (!sdc[s + '_domain']) { errs.push(sprintf('Missing %s_domain in SAPI', s)); } if (!sdc[s.toUpperCase() + '_SERVICE']) { errs.push(sprintf('Missing %s_SERVICE in SAPI', s.toUpperCase())); } } }); // Check that ufds_remote_ip is present if this is not master: if (!sdc.ufds_is_master || sdc.ufds_is_master === 'false') { if (!sdc.ufds_remote_ip) { errs.push('Missing SAPI variable "ufds_remote_ip"'); } } return self.ufds.close(function (err3) { return cb(null, errs); }); }); }); }; /** * Check health of given SAPI instances. * * @param opts {Object} Required. * - insts {Array} Optional. Instance objects as returned by listInsts. * When given, `uuids` will be ignored. * - uuids {Array} Optional. SAPI instance (or service) UUIDs to check. * If not given and insts isn't present, then all SDC instances are * checked. * @param cb {Function} Callback of the form `function (err, results)`. */ SdcAdm.prototype.checkHealth = function checkHealth(opts, cb) { var self = this; assert.object(opts, 'opts'); assert.optionalArrayOfString(opts.uuids, 'opts.uuids'); assert.optionalArrayOfObject(opts.insts, 'opts.insts'); assert.optionalString(opts.type, 'opts.type'); assert.optionalArrayOfString(opts.servers, 'opts.servers'); assert.func(cb, 'cb'); var svcLookup = {}; var uuidLookup; var insts; var headnode; if (opts.insts) { insts = opts.insts; } else if (opts.uuids) { uuidLookup = {}; opts.uuids.forEach(function (id) { uuidLookup[id] = true; }); } // No need to keep these variables global to the whole sdcadm module: var pingPaths = { // vms amon: '/ping', cloudapi: '/--ping', cnapi: '/ping', fwapi: '/ping', imgapi: '/ping', napi: '/ping', papi: '/ping', sapi: '/ping', vmapi: '/ping', workflow: '/ping', // agents firewaller: '/status' }; var pingPorts = { cloudapi: 443, firewaller: 2021 }; // We can ping instances either when we checked for svcs health using // Ur client or when we did straight at the Headnode cmd. Shared code // by these two functions: function _pingInstance(inst, next) { var pingPath = pingPaths[inst.service]; if (!pingPath) { inst.healthy = true; return next(null, inst); } var port = pingPorts[inst.service] || 80; var httpClient = (port === 443 ? https : http); httpClient.get({ hostname: (inst.ip || inst.server_ip), port: port, path: pingPath, agent: false, rejectUnauthorized: false }, function (res) { self.log.debug({ http_response: res.statusCode }, 'HTTP result for ' + inst.instance); inst.healthy = (res.statusCode === 200); if (!inst.healthy) { inst.health_errors = [ { message: 'ping check to ' + inst.ip + ' failed with ' + 'HTTP code ' + res.statusCode } ]; } return next(null, inst); }).once('error', function (e) { inst.healthy = false; inst.health_errors = [ { message: 'ping check to ' + inst.ip + ' failed: ' + e.message } ]; return next(null, inst); }); } function connectToUr(_, next) { // Will wait, at least, for the 5000 msecs we gave to ur client // as connect timeout before we call it and move into the "no-ur" // branch: var t = setTimeout(function () { if (self.urConnTimedOut) { self.log.error('Error connecting to Ur Agent'); return next(); } }, 5500); // Note this timeout is intentionally longer than Ur // client connect timeout. // If the connection times out, this will never be reached, and the // function above should call next if (!self.urConnTimedOut) { self.ur.once('ready', function () { clearTimeout(t); return next(); }); } } function lookupServices(_, next) { if (opts.insts) { return next(); } var svcOpts = {}; if (opts.type) { svcOpts.type = opts.type; } self.getServices(svcOpts, function (err, svcs) { if (err) { if (!err.message) { // TODO(trentm): why this?! err = new Error(err); } return next(err); } self.log.debug({ services: svcs }, 'Look up services'); if (uuidLookup) { svcs = svcs.filter(function (svc) { var found = uuidLookup[svc.uuid]; if (found) { delete uuidLookup[svc.uuid]; } return found; }); } svcs.forEach(function (svc) { if (svc.type === 'vm' || svc.type === 'agent') { svcLookup[svc.name] = true; } }); return next(); }); } function lookupInstances(_, next) { if (opts.insts) { return next(); } var svcOpts = {}; if (opts.type) { svcOpts.types = [opts.type]; } self.listInsts(svcOpts, function (err, insts_) { if (err) { if (!err.message) { err = new Error(err); } return next(err); } self.log.debug({ instances: insts_ }, 'Look up instances'); insts = insts_.filter(function (inst) { if (inst.type !== 'vm' && inst.type !== 'agent') { return false; } if (!svcLookup[inst.service] && !(uuidLookup && uuidLookup[inst.instance])) { return false; } if (uuidLookup) { delete uuidLookup[inst.instance]; } if (inst.type === 'vm' && !inst.ip && inst.service !== 'hostvolume') { self.log.error(inst.instance, 'VM has no admin IP, skip!'); return false; } return true; }); if (uuidLookup && Object.keys(uuidLookup).length > 0) { var msg = 'unrecognized service or instances: ' + Object.keys(uuidLookup).join(', '); return next(new Error(msg)); } return next(); }); } function checkInst(inst, next) { if (inst.server === headnode.UUID) { return checkHeadnodeInst(inst, next); } if (!self.urConnTimedOut) { return checkUrInst(inst, next); } // Do nothing, since it's not a local instance, and we cannot // connect to Ur to query remote instances status return next(); } function checkUrInst(inst, next) { var script; if (inst.type === 'vm') { script = 'svcs -vxz ' + inst.instance; } else if (inst.type === 'agent') { script = 'svcs -vx ' + inst.service; } else if (inst.alias === 'global') { script = 'svcs -vx'; } else { return next(); } // there are a couple agents which don't actually have SMF services, // so skip them if (inst.service.match(/(agents_core|cabase)$/)) { return next(); } self.ur.exec({ script: script, server_uuid: inst.server, timeout: 5000 }, function (err, result) { if (err) { inst.health_errors = [ { message: err.message }]; return next(null, inst); } self.log.debug({ ur_response: result }, 'Ur result for ' + inst.instance); if (result.exit_status !== 0 || result.stderr !== '' || !(result.stdout === '' || result.stdout.match(/State\: online/))) { inst.healthy = false; var errs = []; if (result.exit_status !== 0) { errs.push('svcs returned ' + result.exit_status); } if (result.stderr) { errs.push('stderr: ' + result.stderr.replace(/\n+$/, '')); } if (!(result.stdout === '' || result.stdout.match(/State\: online/))) { errs.push('stdout: ' + result.stdout.replace(/\n+$/, '')); } if (errs.length > 0) { inst.health_errors = errs.map(function (error) { return { message: 'SMF svcs check failed: ' + error }; }); } return next(null, inst); } return _pingInstance(inst, next); }); } // Used only when cannot stablish a connection to the AMQP server: function checkHeadnodeInst(inst, next) { var argv; if (inst.type === 'vm') { argv = ['/usr/bin/svcs', '-vxz', inst.instance]; } else if (inst.type === 'agent') { argv = ['/usr/bin/svcs', '-vx', inst.service]; } else if (inst.alias === 'global') { argv = ['/usr/bin/svcs', '-vx']; } else { return next(); } // there are a couple agents which don't actually have SMF services, // so skip them if (inst.service.match(/(agents_core|cabase)$/)) { return next(); } common.execFilePlus({ argv: argv, log: self.log }, function (err, stdout, stderr) { var errs = []; if (err) { errs.push(err); } if (stderr) { errs.push('stderr: ' + stderr.replace(/\n+$/, '')); } if (!(stdout === '' || stdout.match(/State\: online/))) { errs.push('stdout: ' + stdout.replace(/\n+$/, '')); } if (errs.length > 0) { inst.healthy = false; inst.health_errors = errs.map(function (error) { return { message: 'SMF svcs check failed: ' + error }; }); return next(null, inst); } return _pingInstance(inst, next); }); } // Intentionally not dealing into CNAPI here, since we may also need // to rely into sysinfo to know the name of installed agents: function getHeadnodeSysinfo(_, next) { var argv = ['/usr/bin/sysinfo']; common.execFilePlus({ argv: argv, log: self.log }, function (err, stdout, stderr) { if (err) { return next(err); } try { headnode = JSON.parse(stdout.trim()); if (!opts.insts) { insts.push({ type: 'global', instance: headnode.UUID, alias: 'global', service: 'global', hostname: 'headnode', server: headnode.UUID }); } } catch (e) { return next(e); } return next(); }); } vasync.pipeline({ funcs: [ connectToUr, lookupServices, lookupInstances, getHeadnodeSysinfo ]}, function (err) { if (err) { self.log.error({err: err}, 'checkHealth pipeline cb'); return cb(err); } // If servers to lookup were given as arguments, ignore whatever // not into these servers: if (opts.servers && opts.servers.length) { insts = insts.filter(function (ins) { return (opts.servers.indexOf(ins.server) !== -1 || opts.servers.indexOf(ins.hostname) !== -1); }); } vasync.forEachParallel({ inputs: insts, func: checkInst }, function (err2, results) { self.ur.close(); // Might need to re-user ur latest, need to reset it in order // to be able to re-connect: delete self._ur; if (err2) { self.log.error({err: err2}, 'checkHealth parallel cb'); return cb(new errors.InternalError(new Error(err2))); } var healthResults = results.successes.filter(function (res) { return res; }); // Notify about results being fetched locally and AMQP down: if (self.urConnTimedOut) { healthResults.push({ type: 'service', instance: '00000000-0000-0000-0000-000000000000', alias: 'rabbitmq0', service: 'rabbitmq', hostname: 'headnode', healthy: false, health_errors: [ { message: 'Ur Client cannot connect to AMQP server.\n' + 'Providing results only for vms/agents running ' + 'into Headnode' }] }); } return cb(null, healthResults); }); }); }; SdcAdm.prototype.createCloudapiInstance = function createCloudapiInstance(opts, callback) { var self = this; var sapi = self.sapi; assert.func(opts.progress, 'opts.progress'); var networks; var progress = opts.progress; var cloudapisvc; var changes = []; var img, history, headnode; // find cloudapi service, get service uuid // use sapi.createInstance to create the service vasync.pipeline({ funcs: [ function (_, next) { sapi.listServices({ name: 'cloudapi' }, function (err, svcs) { if (err) { return next(err); } if (svcs.length !== 1) { return next(new Error( 'expected 1 cloudapi service, found %d', svcs.length)); } cloudapisvc = svcs[0]; next(); }); }, function (_, next) { getNetworksAdminExternal({}, function (err, nets) { if (err) { return next(err); } networks = nets; next(); }); }, function (_, next) { self.updates.listImages({ name: 'cloudapi' }, function (err, images) { if (err) { next(err); } else if (images && images.length) { img = images[images.length - 1]; //XXX presuming sorted next(); } else { next(new errors.UpdateError('no "cloudapi" image found')); } }); }, function (_, next) { changes.push({ image: img, service: cloudapisvc, type: 'add-instance', inst: { type: 'vm', alias: opts.alias, version: img.version, service: 'cloudapi', image: img.uuid } }); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } history = hst; return next(); }); }, function getHeadnode(_, next) { self.cnapi.listServers({ headnode: true }, function (err, servers) { if (err) { return next(new errors.SDCClientError(err, 'cnapi')); } headnode = servers[0]; return next(); }); }, function (_, next) { var cOpts = { params: { server_uuid: headnode.uuid, alias: opts.alias, networks: [ { uuid: networks.admin.uuid }, { primary: true, uuid: networks.external.uuid } ] } }; sapi.createInstance(cloudapisvc.uuid, cOpts, function (err, inst) { if (err) { return next(err); } changes[0].inst.zonename = changes[0].inst.uuid = inst.uuid; next(); }); }, function hupHermes(_, next) { svcadm.restartHermes({ sdcadm: self, log: self.log, progress: progress }, next); } ] }, function (err) { if (!history) { self.log.warn('History not set for post-setup cloudapi'); return callback(err); } history.changes = changes; if (err) { history.error = err; } // No need to add `history.finished` here, History instance will do self.history.updateHistory(history, function (err2, hist2) { if (err) { callback(err); } else if (err2) { callback(err2); } else { progress('cloudapi0 zone created'); callback(); } }); }); function getNetworksAdminExternal(err, cb) { var napi = self.napi; var foundnets = {}; napi.listNetworks({ name: ['admin', 'external'] }, function (listerr, nets) { if (listerr) { return cb(err); } if (!nets.length) { return cb(new Error('Couldn\'t find admin network in NAPI')); } for (var i in nets) { foundnets[nets[i].name] = nets[i]; } cb(null, foundnets); }); } }; // Extracted from setupCommonExternalNics b/c it's also used by DownloadImages // to check if the reason for an IMGAPI failure could be the lack of external // nic into imgapi zone SdcAdm.prototype.checkMissingExternalNics = function checkMissingExternalNics(opts, cb) { var self = this; assert.func(opts.progress, 'opts.progress'); assert.func(cb, 'cb'); var sapi = self.sapi; var napi = self.napi; var svcadminui; var svcimgapi; var doadminui = true; var doimgapi = true; var netexternal; function getInstance(svcname, callback) { sapi.listServices({ name: svcname }, onServices); function onServices(err, svcs) { if (err) { return cb(err); } if (!svcs.length) { return cb(new Error( 'Couldn\'t find imgapi SAPI service')); } sapi.listInstances({ service_uuid: svcs[0].uuid }, function (listerr, inst) { if (listerr) { return cb(listerr); } callback(null, inst[0]); }); } } vasync.pipeline({ funcs: [ // Look up details for the adminui, imgapi instances. function (_, next) { getInstance('adminui', function (err, inst) { if (err) { return cb(err); } svcadminui = inst; next(); }); }, function (_, next) { getInstance('imgapi', function (err, inst) { if (err) { return cb(err); } svcimgapi = inst; next(); }); }, // Grab the external network details. function (_, next) { var listOpts = { name: 'external' }; napi.listNetworks(listOpts, function (err, nets) { if (err) { return cb(err); } if (!nets.length) { return cb(new Error( 'Couldn\'t find external network in NAPI')); } netexternal = nets[0]; next(); }); }, // Check what NICS the imgapi and adminui zones currently have. Only do // work for those which do not yet have an external nic. function (_, next) { var listOpts = { belongs_to_type: 'zone', belongs_to_uuid: [ svcimgapi.uuid, svcadminui.uuid ] }; napi.listNics(listOpts, function (err, nics) { if (err) { return cb(err); } if (!nics.length) { return cb(new Error( 'Couldn\'t find NICs for imgapi or adminui')); } for (var i = 0, nic; i < nics.length; i++) { nic = nics[i]; if (nic.belongs_to_uuid === svcadminui.uuid && nic.nic_tag === 'external') { doadminui = false; } else if (nic.belongs_to_uuid === svcimgapi.uuid && nic.nic_tag === 'external') { doimgapi = false; } } next(); }); } ]}, function (err) { if (err) { cb(err); } else { cb(null, { doimgapi: doimgapi, doadminui: doadminui, svcadminui: svcadminui, svcimgapi: svcimgapi, netexternal: netexternal }); } }); }; SdcAdm.prototype.setupCommonExternalNics = function setupCommonExternalNics(opts, cb) { var self = this; assert.func(opts.progress, 'options.progress'); var progress = opts.progress; var svcadminui; var svcimgapi; var doadminui = true; var doimgapi = true; var netexternal; var changes = []; var history; var napisvc; function addExternaNicToZone(svcobj, subcb) { var addparams = { uuid: svcobj.uuid, networks: [ { 'uuid': netexternal.uuid, primary: true } ] }; self.vmapi.addNicsAndWait(addparams, subcb); } vasync.pipeline({ funcs: [ function (_, next) { self.checkMissingExternalNics(opts, function (err, res) { if (err) { return next(err); } doimgapi = res.doimgapi; doadminui = res.doadminui; svcadminui = res.svcadminui; svcimgapi = res.svcimgapi; netexternal = res.netexternal; next(); }); }, function (_, next) { if (!doadminui && !doimgapi) { return next(); } self.sapi.listServices({ name: 'napi' }, function (err, svcs) { if (err) { return next(err); } if (svcs.length !== 1) { return next(new Error( 'expected 1 napi service, found %d', svcs.length)); } napisvc = svcs[0]; next(); }); }, function (_, next) { if (!doadminui && !doimgapi) { return next(); } changes.push({ service: napisvc, type: 'add-nics', inst: { network: netexternal.uuid, adminui: doadminui, imgapi: doimgapi } }); self.history.saveHistory({ changes: changes }, function (err, hst) { if (err) { return next(err); } history = hst; return next(); }); }, function (_, next) { if (!doadminui) { progress('AdminUI already has an external nic'); return next(); } addExternaNicToZone(svcadminui, function (err) { if (err) { return next(err); } progress('Added external nic to adminui'); next(); }); }, function (_, next) { if (!doimgapi) { progress('IMGAPI already has an external nic'); return next(); } addExternaNicToZone(svcimgapi, function (err) { if (err) { return next(err); } progress('Added external nic to imgapi'); next(); }); } ]}, function (err) { if (!history) { self.log.info( 'History not set for post-setup common-external-nics'); return cb(err); } history.changes = changes; if (err) { history.error = err; } self.history.updateHistory(history, function (err2, hist2) { if (err) { cb(err); } else if (err2) { cb(err2); } else { cb(); } }); }); }; /* * Generate a rollback plan from the contents of the given update plan. * * @param options {Object} Required. * - updatePlan {Object} Required. The update plan. * - progress {Function} Optional. A function that is called * with progress messages. Called like printf, i.e. passing in * `console.log` or a Bunyan `log.info.bind(log)` is fine. * @param cb {Function} Callback of the form `function (err, plan)`. */ SdcAdm.prototype.genRollbackPlan = function genRollbackPlan(options, cb) { assert.object(options, 'options'); assert.object(options.updatePlan, 'options.updatePlan'); assert.optionalFunc(options.progress, 'options.progress'); assert.optionalString(options.uuid, 'options.uuid'); assert.func(cb, 'cb'); var self = this; var log = self.log; var progress = options.progress || function () {}; var serverFromUuidOrHostname; var rbPlan = {}; var upPlan = options.updatePlan; var svcs; var svcFromName; var insts; var changes; var plan; var servers; vasync.pipeline({funcs: [ function getServers(_, next) { self.cnapi.listServers(function (err, servers_) { servers = servers_ || []; serverFromUuidOrHostname = {}; for (var i = 0; i < servers.length; i++) { serverFromUuidOrHostname[servers[i].uuid] = servers[i]; serverFromUuidOrHostname[servers[i].hostname] = servers[i]; } next(err); }); }, function getSvcs(_, next) { self.getServices({}, function (err, svcs_) { svcs = svcs_ || []; svcFromName = {}; for (var i = 0; i < svcs.length; i++) { svcFromName[svcs[i].name] = svcs[i]; } next(err); }); }, function getInsts(_, next) { self.listInsts(function (err, insts_) { insts = insts_; next(err); }); }, function genRbSpecFromUpdate(_, next) { rbPlan.changes = []; upPlan.changes.forEach(function (change) { var chg = { service: change.service, type: (change.type === 'update-service') ? 'rollback-service' : 'unknown' }; if (change.service.type === 'vm') { if (change.service.name === 'assets') { chg.rb_img = change.inst.image; } else { chg.rb_img = change.service.params.image_uuid; } } rbPlan.changes.push(chg); }); next(); }, function getImgs(_, next) { var _changes = []; vasync.forEachParallel({ inputs: rbPlan.changes, func: function (chg, next_) { if (chg.service.type === 'vm') { self.getImage({ uuid: chg.rb_img }, function (e, img) { if (e) { return next_(e); } chg.image = img; delete chg.rb_img; _changes.push(chg); return next_(); }); } else { _changes.push(chg); return next_(); } } }, function (err) { rbPlan.changes = _changes; next(err); }); }, function createPlan(_, next) { changes = rbPlan.changes; var targ = common.deepObjCopy(insts); for (var i = 0; i < changes.length; i++) { var ch = changes[i]; for (var j = 0; j < targ.length; j++) { var inst = targ[j]; if (inst.service === ch.service.name) { inst.image = ch.image.uuid; inst.version = ch.image.version; } } } plan = new UpdatePlan({ curr: insts, targ: targ, changes: changes, rollback: true, justImages: false }); next(); }, function determineProcedures(_, next) { procedures.coordinatePlan({ plan: plan, sdcadm: self, serverFromUuidOrHostname: serverFromUuidOrHostname, log: log, progress: progress }, function (err, procs_) { plan.procs = procs_; next(err); }); } ]}, function finishRb(err) { cb(err, plan); }); }; //---- exports module.exports = SdcAdm;
TOOLS-1115: No need to call "removeAllListeners()" for Ur Discovery ("cancel()" is enough)
lib/sdcadm.js
TOOLS-1115: No need to call "removeAllListeners()" for Ur Discovery ("cancel()" is enough)
<ide><path>ib/sdcadm.js <ide> * We are done with this discovery session. Cancel it and <ide> * ignore future error/end events. <ide> */ <del> disco.removeAllListeners(); <ide> disco.cancel(); <ide> failure(err); <ide> });
Java
mit
38e51e409dbf7498d1f92c531d10c6a99061ba0e
0
tripu/validator,takenspc/validator,tripu/validator,takenspc/validator,validator/validator,YOTOV-LIMITED/validator,validator/validator,YOTOV-LIMITED/validator,validator/validator,sammuelyee/validator,tripu/validator,sammuelyee/validator,YOTOV-LIMITED/validator,sammuelyee/validator,takenspc/validator,takenspc/validator,sammuelyee/validator,sammuelyee/validator,takenspc/validator,YOTOV-LIMITED/validator,validator/validator,validator/validator,tripu/validator,YOTOV-LIMITED/validator,tripu/validator
/* * Copyright (c) 2005 Henri Sivonen * Copyright (c) 2007-2012 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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 nu.validator.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nu.validator.messages.MessageEmitterAdapter; import nu.validator.xml.PrudentHttpEntityResolver; import org.apache.log4j.Logger; /** * @version $Id$ * @author hsivonen */ public class VerifierServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 7811043632732680935L; private static final Logger log4j = Logger.getLogger(VerifierServlet.class); static final String GENERIC_HOST = System.getProperty("nu.validator.servlet.host.generic", ""); static final String HTML5_HOST = System.getProperty("nu.validator.servlet.host.html5", ""); static final String PARSETREE_HOST = System.getProperty("nu.validator.servlet.host.parsetree", ""); static final String GENERIC_PATH = System.getProperty("nu.validator.servlet.path.generic", "/"); static final String HTML5_PATH = System.getProperty("nu.validator.servlet.path.html5", "/html5/"); static final String PARSETREE_PATH = System.getProperty("nu.validator.servlet.path.parsetree", "/parsetree/"); static final boolean W3C_BRANDING = "1".equals(System.getProperty("nu.validator.servlet.w3cbranding")); private static final byte[] GENERIC_ROBOTS_TXT; private static final byte[] HTML5_ROBOTS_TXT; private static final byte[] PARSETREE_ROBOTS_TXT; private static final byte[] STYLE_CSS; private static final byte[] SCRIPT_JS; private static final byte[] ICON_PNG; private static final byte[] W3C_PNG; private static final byte[] VNU_PNG; private static final byte[] HTML_PNG; private static final byte[] ABOUT_HTML; static { String aboutPath = System.getProperty( "nu.validator.servlet.path.about", "./validator/site/"); try { GENERIC_ROBOTS_TXT = buildRobotsTxt(GENERIC_HOST, GENERIC_PATH, HTML5_HOST, HTML5_PATH, PARSETREE_HOST, PARSETREE_PATH); HTML5_ROBOTS_TXT = buildRobotsTxt(HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH, PARSETREE_HOST, PARSETREE_PATH); PARSETREE_ROBOTS_TXT = buildRobotsTxt(PARSETREE_HOST, PARSETREE_PATH, HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } try { STYLE_CSS = readFileFromPathIntoByteArray(aboutPath + "style.css"); SCRIPT_JS = readFileFromPathIntoByteArray(aboutPath + "script.js"); ICON_PNG = readFileFromPathIntoByteArray(aboutPath + "icon.png"); if (W3C_BRANDING) { W3C_PNG = readFileFromPathIntoByteArray(aboutPath + "w3c.png"); VNU_PNG = readFileFromPathIntoByteArray(aboutPath + "vnu.png"); HTML_PNG = readFileFromPathIntoByteArray(aboutPath + "html.png"); ABOUT_HTML = readFileFromPathIntoByteArray(aboutPath + "about.html"); } else { W3C_PNG = VNU_PNG = HTML_PNG = ABOUT_HTML = null; } } catch (IOException e) { throw new RuntimeException(e); } PrudentHttpEntityResolver.setParams( Integer.parseInt(System.getProperty("nu.validator.servlet.connection-timeout","5000")), Integer.parseInt(System.getProperty("nu.validator.servlet.socket-timeout","5000")), 100); PrudentHttpEntityResolver.setUserAgent("Validator.nu/LV"); // force some class loading new VerifierServletTransaction(null, null); new MessageEmitterAdapter(null, false, null, 0, null); } /** * @return * @throws UnsupportedEncodingException */ private static byte[] buildRobotsTxt(String primaryHost, String primaryPath, String secondaryHost, String secondaryPath, String tertiaryHost, String tertiaryPath) throws UnsupportedEncodingException { StringBuilder builder = new StringBuilder(); builder.append("User-agent: *\nDisallow: "); builder.append(primaryPath); builder.append("?\n"); if (primaryHost.equals(secondaryHost)) { builder.append("Disallow: "); builder.append(secondaryPath); builder.append("?\n"); } if (primaryHost.equals(tertiaryHost)) { builder.append("Disallow: "); builder.append(tertiaryPath); builder.append("?\n"); } return builder.toString().getBytes("UTF-8"); } private static byte[] readFileFromPathIntoByteArray(String path) throws IOException { File file = new File(path); byte[] buffer = new byte[(int) file.length()]; InputStream ios = null; try { ios = new FileInputStream(file); if (ios.read(buffer) != buffer.length) { throw new IOException( "Unexpected end of file reached while reading " + path); } } finally { try { if (ios != null) { ios.close(); } } catch (IOException e) { throw new RuntimeException(e); } } return buffer; } private void writeResponse(byte[] buffer, String type, HttpServletResponse response) throws IOException { try { response.setContentType(type); response.setContentLength(buffer.length); response.setDateHeader("Expires", System.currentTimeMillis() + 43200000); // 12 hours OutputStream out = response.getOutputStream(); out.write(buffer); out.flush(); out.close(); } catch (IOException e) { throw new RuntimeException(e); } return; } /** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ("/robots.txt".equals(request.getPathInfo())) { String serverName = request.getServerName(); byte[] robotsTxt = null; if (hostMatch(GENERIC_HOST, serverName)) { robotsTxt = GENERIC_ROBOTS_TXT; } else if (hostMatch(HTML5_HOST, serverName)) { robotsTxt = HTML5_ROBOTS_TXT; } else if (hostMatch(PARSETREE_HOST, serverName)) { robotsTxt = PARSETREE_ROBOTS_TXT; } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } writeResponse(robotsTxt, "text/plain; charset=utf-8", response); return; } else if ("/style.css".equals(request.getPathInfo())) { writeResponse(STYLE_CSS, "text/css; charset=utf-8", response); return; } else if ("/script.js".equals(request.getPathInfo())) { writeResponse(SCRIPT_JS, "text/javascript; charset=utf-8", response); return; } else if ("/icon.png".equals(request.getPathInfo())) { writeResponse(ICON_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/w3c.png".equals(request.getPathInfo())) { writeResponse(W3C_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/vnu.png".equals(request.getPathInfo())) { writeResponse(VNU_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/html.png".equals(request.getPathInfo())) { writeResponse(HTML_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/about.html".equals(request.getPathInfo())) { writeResponse(ABOUT_HTML, "text/html; charset=utf-8", response); return; } doPost(request, response); } private boolean hostMatch(String reference, String host) { if ("".equals(reference)) { return true; } else { // XXX case-sensitivity return reference.equalsIgnoreCase(host); } } /** * @see javax.servlet.http.HttpServlet#doOptions(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if ("*".equals(pathInfo)) { // useless RFC 2616 complication return; } else if ("/robots.txt".equals(pathInfo)) { String serverName = request.getServerName(); if (hostMatch(GENERIC_HOST, serverName) || hostMatch(HTML5_HOST, serverName) || hostMatch(PARSETREE_HOST, serverName)) { sendGetOnlyOptions(request, response); return; } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } doPost(request, response); } /** * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } /** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if (pathInfo == null) { pathInfo = "/"; // Fix for Jigsaw } String serverName = request.getServerName(); if ("/robots.txt".equals(pathInfo)) { // if we get here, we've got a POST response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } log4j.debug("pathInfo: " + pathInfo); log4j.debug("serverName: " + serverName); boolean isOptions = "OPTIONS".equals(request.getMethod()); if ("validator.nu".equals(serverName) && "/html5/".equals(pathInfo)) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); String queryString = request.getQueryString(); response.setHeader("Location", "http://html5.validator.nu/" + (queryString == null ? "" : "?" + queryString)); } else if (hostMatch(GENERIC_HOST, serverName) && GENERIC_PATH.equals(pathInfo)) { response.setHeader("Access-Control-Allow-Origin", "*"); if (isOptions) { response.setHeader("Access-Control-Policy-Path", GENERIC_PATH); sendOptions(request, response); } else { new VerifierServletTransaction(request, response).service(); } } else if (hostMatch(HTML5_HOST, serverName) && HTML5_PATH.equals(pathInfo)) { response.setHeader("Access-Control-Allow-Origin", "*"); if (isOptions) { sendOptions(request, response); } else { new Html5ConformanceCheckerTransaction(request, response).service(); } } else if (hostMatch(PARSETREE_HOST, serverName) && PARSETREE_PATH.equals(pathInfo)) { if (isOptions) { sendGetOnlyOptions(request, response); } else { new ParseTreePrinter(request, response).service(); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } private void sendGetOnlyOptions(HttpServletRequest request, HttpServletResponse response) { response.setHeader("Allow", "GET, HEAD, OPTIONS"); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS"); response.setContentType("application/octet-stream"); response.setContentLength(0); } private void sendOptions(HttpServletRequest request, HttpServletResponse response) { response.setHeader("Access-Control-Max-Age", "43200"); // 12 hours response.setHeader("Allow", "GET, HEAD, POST, OPTIONS"); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS"); response.setContentType("application/octet-stream"); response.setContentLength(0); } }
src/nu/validator/servlet/VerifierServlet.java
/* * Copyright (c) 2005 Henri Sivonen * Copyright (c) 2007-2008 Mozilla Foundation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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 nu.validator.servlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import nu.validator.messages.MessageEmitterAdapter; import nu.validator.xml.PrudentHttpEntityResolver; import org.apache.log4j.Logger; /** * @version $Id$ * @author hsivonen */ public class VerifierServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 7811043632732680935L; private static final Logger log4j = Logger.getLogger(VerifierServlet.class); static final String GENERIC_HOST = System.getProperty("nu.validator.servlet.host.generic", ""); static final String HTML5_HOST = System.getProperty("nu.validator.servlet.host.html5", ""); static final String PARSETREE_HOST = System.getProperty("nu.validator.servlet.host.parsetree", ""); static final String GENERIC_PATH = System.getProperty("nu.validator.servlet.path.generic", "/"); static final String HTML5_PATH = System.getProperty("nu.validator.servlet.path.html5", "/html5/"); static final String PARSETREE_PATH = System.getProperty("nu.validator.servlet.path.parsetree", "/parsetree/"); static final boolean W3C_BRANDING = "1".equals(System.getProperty("nu.validator.servlet.w3cbranding")); private static final byte[] GENERIC_ROBOTS_TXT; private static final byte[] HTML5_ROBOTS_TXT; private static final byte[] PARSETREE_ROBOTS_TXT; private static final byte[] STYLE_CSS; private static final byte[] SCRIPT_JS; private static final byte[] ICON_PNG; private static final byte[] W3C_PNG; private static final byte[] VNU_PNG; private static final byte[] HTML_PNG; private static final byte[] ABOUT_HTML; static { String aboutPath = System.getProperty( "nu.validator.servlet.path.about", "./validator/site/"); try { GENERIC_ROBOTS_TXT = buildRobotsTxt(GENERIC_HOST, GENERIC_PATH, HTML5_HOST, HTML5_PATH, PARSETREE_HOST, PARSETREE_PATH); HTML5_ROBOTS_TXT = buildRobotsTxt(HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH, PARSETREE_HOST, PARSETREE_PATH); PARSETREE_ROBOTS_TXT = buildRobotsTxt(PARSETREE_HOST, PARSETREE_PATH, HTML5_HOST, HTML5_PATH, GENERIC_HOST, GENERIC_PATH); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } try { STYLE_CSS = readFileFromPathIntoByteArray(aboutPath + "style.css"); SCRIPT_JS = readFileFromPathIntoByteArray(aboutPath + "script.js"); ICON_PNG = readFileFromPathIntoByteArray(aboutPath + "icon.png"); if (W3C_BRANDING) { W3C_PNG = readFileFromPathIntoByteArray(aboutPath + "w3c.png"); VNU_PNG = readFileFromPathIntoByteArray(aboutPath + "vnu.png"); HTML_PNG = readFileFromPathIntoByteArray(aboutPath + "html.png"); ABOUT_HTML = readFileFromPathIntoByteArray(aboutPath + "about.html"); } else { W3C_PNG = VNU_PNG = HTML_PNG = ABOUT_HTML = null; } } catch (IOException e) { throw new RuntimeException(e); } PrudentHttpEntityResolver.setParams( Integer.parseInt(System.getProperty("nu.validator.servlet.connection-timeout","5000")), Integer.parseInt(System.getProperty("nu.validator.servlet.socket-timeout","5000")), 100); PrudentHttpEntityResolver.setUserAgent("Validator.nu/LV"); // force some class loading new VerifierServletTransaction(null, null); new MessageEmitterAdapter(null, false, null, 0, null); } /** * @return * @throws UnsupportedEncodingException */ private static byte[] buildRobotsTxt(String primaryHost, String primaryPath, String secondaryHost, String secondaryPath, String tertiaryHost, String tertiaryPath) throws UnsupportedEncodingException { StringBuilder builder = new StringBuilder(); builder.append("User-agent: *\nDisallow: "); builder.append(primaryPath); builder.append("?\n"); if (primaryHost.equals(secondaryHost)) { builder.append("Disallow: "); builder.append(secondaryPath); builder.append("?\n"); } if (primaryHost.equals(tertiaryHost)) { builder.append("Disallow: "); builder.append(tertiaryPath); builder.append("?\n"); } return builder.toString().getBytes("UTF-8"); } private static byte[] readFileFromPathIntoByteArray(String path) throws IOException { File file = new File(path); byte[] buffer = new byte[(int) file.length()]; InputStream ios = null; try { ios = new FileInputStream(file); if (ios.read(buffer) != buffer.length) { throw new IOException( "Unexpected end of file reached while reading " + path); } } finally { try { if (ios != null) { ios.close(); } } catch (IOException e) { throw new RuntimeException(e); } } return buffer; } private void writeResponse(byte[] buffer, String type, HttpServletResponse response) throws IOException { try { response.setContentType(type); response.setContentLength(buffer.length); response.setDateHeader("Expires", System.currentTimeMillis() + 43200000); // 12 hours OutputStream out = response.getOutputStream(); out.write(buffer); out.flush(); out.close(); } catch (IOException e) { throw new RuntimeException(e); } return; } /** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if ("/robots.txt".equals(request.getPathInfo())) { String serverName = request.getServerName(); byte[] robotsTxt = null; if (hostMatch(GENERIC_HOST, serverName)) { robotsTxt = GENERIC_ROBOTS_TXT; } else if (hostMatch(HTML5_HOST, serverName)) { robotsTxt = HTML5_ROBOTS_TXT; } else if (hostMatch(PARSETREE_HOST, serverName)) { robotsTxt = PARSETREE_ROBOTS_TXT; } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } writeResponse(robotsTxt, "text/plain; charset=utf-8", response); return; } else if ("/style.css".equals(request.getPathInfo())) { writeResponse(STYLE_CSS, "text/css; charset=utf-8", response); return; } else if ("/script.js".equals(request.getPathInfo())) { writeResponse(SCRIPT_JS, "text/javascript charset=utf-8", response); return; } else if ("/icon.png".equals(request.getPathInfo())) { writeResponse(ICON_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/w3c.png".equals(request.getPathInfo())) { writeResponse(W3C_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/vnu.png".equals(request.getPathInfo())) { writeResponse(VNU_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/html.png".equals(request.getPathInfo())) { writeResponse(HTML_PNG, "image/png", response); return; } else if (W3C_BRANDING && "/about.html".equals(request.getPathInfo())) { writeResponse(ABOUT_HTML, "text/html; charset=utf-8", response); return; } doPost(request, response); } private boolean hostMatch(String reference, String host) { if ("".equals(reference)) { return true; } else { // XXX case-sensitivity return reference.equalsIgnoreCase(host); } } /** * @see javax.servlet.http.HttpServlet#doOptions(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if ("*".equals(pathInfo)) { // useless RFC 2616 complication return; } else if ("/robots.txt".equals(pathInfo)) { String serverName = request.getServerName(); if (hostMatch(GENERIC_HOST, serverName) || hostMatch(HTML5_HOST, serverName) || hostMatch(PARSETREE_HOST, serverName)) { sendGetOnlyOptions(request, response); return; } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } doPost(request, response); } /** * @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } /** * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); if (pathInfo == null) { pathInfo = "/"; // Fix for Jigsaw } String serverName = request.getServerName(); if ("/robots.txt".equals(pathInfo)) { // if we get here, we've got a POST response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } log4j.debug("pathInfo: " + pathInfo); log4j.debug("serverName: " + serverName); boolean isOptions = "OPTIONS".equals(request.getMethod()); if ("validator.nu".equals(serverName) && "/html5/".equals(pathInfo)) { response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); String queryString = request.getQueryString(); response.setHeader("Location", "http://html5.validator.nu/" + (queryString == null ? "" : "?" + queryString)); } else if (hostMatch(GENERIC_HOST, serverName) && GENERIC_PATH.equals(pathInfo)) { response.setHeader("Access-Control-Allow-Origin", "*"); if (isOptions) { response.setHeader("Access-Control-Policy-Path", GENERIC_PATH); sendOptions(request, response); } else { new VerifierServletTransaction(request, response).service(); } } else if (hostMatch(HTML5_HOST, serverName) && HTML5_PATH.equals(pathInfo)) { response.setHeader("Access-Control-Allow-Origin", "*"); if (isOptions) { sendOptions(request, response); } else { new Html5ConformanceCheckerTransaction(request, response).service(); } } else if (hostMatch(PARSETREE_HOST, serverName) && PARSETREE_PATH.equals(pathInfo)) { if (isOptions) { sendGetOnlyOptions(request, response); } else { new ParseTreePrinter(request, response).service(); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } private void sendGetOnlyOptions(HttpServletRequest request, HttpServletResponse response) { response.setHeader("Allow", "GET, HEAD, OPTIONS"); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS"); response.setContentType("application/octet-stream"); response.setContentLength(0); } private void sendOptions(HttpServletRequest request, HttpServletResponse response) { response.setHeader("Access-Control-Max-Age", "43200"); // 12 hours response.setHeader("Allow", "GET, HEAD, POST, OPTIONS"); response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS"); response.setContentType("application/octet-stream"); response.setContentLength(0); } }
Fixed typo and updated copyright date.
src/nu/validator/servlet/VerifierServlet.java
Fixed typo and updated copyright date.
<ide><path>rc/nu/validator/servlet/VerifierServlet.java <ide> /* <ide> * Copyright (c) 2005 Henri Sivonen <del> * Copyright (c) 2007-2008 Mozilla Foundation <add> * Copyright (c) 2007-2012 Mozilla Foundation <ide> * <ide> * Permission is hereby granted, free of charge, to any person obtaining a <ide> * copy of this software and associated documentation files (the "Software"), <ide> writeResponse(STYLE_CSS, "text/css; charset=utf-8", response); <ide> return; <ide> } else if ("/script.js".equals(request.getPathInfo())) { <del> writeResponse(SCRIPT_JS, "text/javascript charset=utf-8", response); <add> writeResponse(SCRIPT_JS, "text/javascript; charset=utf-8", response); <ide> return; <ide> } else if ("/icon.png".equals(request.getPathInfo())) { <ide> writeResponse(ICON_PNG, "image/png", response);
Java
mit
7ae393479436e26d41fa1edbd8a157771a25466b
0
johnjohndoe/AntennaPod,johnjohndoe/AntennaPod,johnjohndoe/AntennaPod,johnjohndoe/AntennaPod
package de.danoeh.antennapod.core.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.storage.DBWriter; /** * Provides method for sorting the queue according to rules. */ public class QueueSorter { /** * Sorts the queue by the given sort order and sends a broadcast update. * * @param sortOrder Sort order. * @param broadcastUpdate Send broadcast update? */ public static void sort(SortOrder sortOrder, boolean broadcastUpdate) { Permutor<FeedItem> permutor = getPermutor(sortOrder); if (permutor != null) { DBWriter.reorderQueue(permutor, broadcastUpdate); } } /** * Returns a Permutor that sorts a list appropriate to the given sort order. * * @param sortOrder Sort order. * @return Permutor that sorts a list appropriate to the given sort order. <code>null</code> if the order is unknown or <code>null</code>. */ public static Permutor<FeedItem> getPermutor(SortOrder sortOrder) { if (sortOrder == null) { return null; } Comparator<FeedItem> comparator = null; Permutor<FeedItem> permutor = null; switch (sortOrder) { case EPISODE_TITLE_A_Z: comparator = (f1, f2) -> f1.getTitle().compareTo(f2.getTitle()); break; case EPISODE_TITLE_Z_A: comparator = (f1, f2) -> f2.getTitle().compareTo(f1.getTitle()); break; case DATE_OLD_NEW: comparator = (f1, f2) -> f1.getPubDate().compareTo(f2.getPubDate()); break; case DATE_NEW_OLD: comparator = (f1, f2) -> f2.getPubDate().compareTo(f1.getPubDate()); break; case DURATION_SHORT_LONG: comparator = (f1, f2) -> { FeedMedia f1Media = f1.getMedia(); FeedMedia f2Media = f2.getMedia(); int duration1 = f1Media != null ? f1Media.getDuration() : -1; int duration2 = f2Media != null ? f2Media.getDuration() : -1; if (duration1 == -1 || duration2 == -1) return duration2 - duration1; else return duration1 - duration2; }; break; case DURATION_LONG_SHORT: comparator = (f1, f2) -> { FeedMedia f1Media = f1.getMedia(); FeedMedia f2Media = f2.getMedia(); int duration1 = f1Media != null ? f1Media.getDuration() : -1; int duration2 = f2Media != null ? f2Media.getDuration() : -1; return -1 * (duration1 - duration2); }; break; case FEED_TITLE_A_Z: comparator = (f1, f2) -> f1.getFeed().getTitle().compareTo(f2.getFeed().getTitle()); break; case FEED_TITLE_Z_A: comparator = (f1, f2) -> f2.getFeed().getTitle().compareTo(f1.getFeed().getTitle()); break; case RANDOM: permutor = Collections::shuffle; break; case SMART_SHUFFLE_OLD_NEW: permutor = (queue) -> smartShuffle(queue, true); break; case SMART_SHUFFLE_NEW_OLD: permutor = (queue) -> smartShuffle(queue, false); break; } if (comparator != null) { final Comparator<FeedItem> comparator2 = comparator; permutor = (queue) -> Collections.sort(queue, comparator2); } return permutor; } /** * Implements a reordering by pubdate that avoids consecutive episodes from the same feed in * the queue. * * A listener might want to hear episodes from any given feed in pubdate order, but would * prefer a more balanced ordering that avoids having to listen to clusters of consecutive * episodes from the same feed. This is what "Smart Shuffle" tries to accomplish. * * The Smart Shuffle algorithm involves spreading episodes from each feed out over the whole * queue. To do this, we calculate the number of episodes in each feed, then a common multiple * (not the smallest); each episode is then spread out, and we sort the resulting list of * episodes by "spread out factor" and feed name. * * For example, given a queue containing three episodes each from three different feeds * (A, B, and C), a simple pubdate sort might result in a queue that looks like the following: * * B1, B2, B3, A1, A2, C1, C2, C3, A3 * * (note that feed B episodes were all published before the first feed A episode, so a simple * pubdate sort will often result in significant clustering of episodes from a single feed) * * Using Smart Shuffle, the resulting queue would look like the following: * * A1, B1, C1, A2, B2, C2, A3, B3, C3 * * (note that episodes above <i>aren't strictly ordered in terms of pubdate</i>, but episodes * of each feed <b>do</b> appear in pubdate order) * * @param queue A (modifiable) list of FeedItem elements to be reordered. * @param ascending {@code true} to use ascending pubdate in the reordering; * {@code false} for descending. */ private static void smartShuffle(List<FeedItem> queue, boolean ascending) { // Divide FeedItems into lists by feed Map<Long, List<FeedItem>> map = new HashMap<>(); while (!queue.isEmpty()) { FeedItem item = queue.remove(0); Long id = item.getFeedId(); if (!map.containsKey(id)) { map.put(id, new ArrayList<>()); } map.get(id).add(item); } // Sort each individual list by PubDate (ascending/descending) Comparator<FeedItem> itemComparator = ascending ? (f1, f2) -> f1.getPubDate().compareTo(f2.getPubDate()) : (f1, f2) -> f2.getPubDate().compareTo(f1.getPubDate()); // Calculate the spread long spread = 0; for (Map.Entry<Long, List<FeedItem>> mapEntry : map.entrySet()) { List<FeedItem> feedItems = mapEntry.getValue(); Collections.sort(feedItems, itemComparator); if (spread == 0) { spread = feedItems.size(); } else if (spread % feedItems.size() != 0){ spread *= feedItems.size(); } } // Create a list of the individual FeedItems lists, and sort it by feed title (ascending). // Doing this ensures that the feed order we use is predictable/deterministic. List<List<FeedItem>> feeds = new ArrayList<>(map.values()); Collections.sort(feeds, (f1, f2) -> f1.get(0).getFeed().getTitle().compareTo(f2.get(0).getFeed().getTitle())); // Spread each episode out Map<Long, List<FeedItem>> spreadItems = new HashMap<>(); for (List<FeedItem> feedItems : feeds) { long thisSpread = spread / feedItems.size(); if (thisSpread == 0) { thisSpread = 1; } // Starting from 0 ensures we front-load, so the queue starts with one episode from // each feed in the queue long itemSpread = 0; for (FeedItem feedItem : feedItems) { if (!spreadItems.containsKey(itemSpread)) { spreadItems.put(itemSpread, new ArrayList<>()); } spreadItems.get(itemSpread).add(feedItem); itemSpread += thisSpread; } } // Go through the spread items and add them to the queue List<Long> spreads = new ArrayList<>(spreadItems.keySet()); Collections.sort(spreads); for (long itemSpread : spreads) { queue.addAll(spreadItems.get(itemSpread)); } } }
core/src/main/java/de/danoeh/antennapod/core/util/QueueSorter.java
package de.danoeh.antennapod.core.util; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import de.danoeh.antennapod.core.feed.FeedItem; import de.danoeh.antennapod.core.feed.FeedMedia; import de.danoeh.antennapod.core.storage.DBWriter; /** * Provides method for sorting the queue according to rules. */ public class QueueSorter { /** * Sorts the queue by the given sort order and sends a broadcast update. * * @param sortOrder Sort order. * @param broadcastUpdate Send broadcast update? */ public static void sort(SortOrder sortOrder, boolean broadcastUpdate) { Permutor<FeedItem> permutor = getPermutor(sortOrder); if (permutor != null) { DBWriter.reorderQueue(permutor, broadcastUpdate); } } /** * Returns a Permutor that sorts a list appropriate to the given sort order. * * @param sortOrder Sort order. * @return Permutor that sorts a list appropriate to the given sort order. <code>null</code> if the order is unknown or <code>null</code>. */ public static Permutor<FeedItem> getPermutor(SortOrder sortOrder) { if (sortOrder == null) { return null; } Comparator<FeedItem> comparator = null; Permutor<FeedItem> permutor = null; switch (sortOrder) { case EPISODE_TITLE_A_Z: comparator = (f1, f2) -> f1.getTitle().compareTo(f2.getTitle()); break; case EPISODE_TITLE_Z_A: comparator = (f1, f2) -> f2.getTitle().compareTo(f1.getTitle()); break; case DATE_OLD_NEW: comparator = (f1, f2) -> f1.getPubDate().compareTo(f2.getPubDate()); break; case DATE_NEW_OLD: comparator = (f1, f2) -> f2.getPubDate().compareTo(f1.getPubDate()); break; case DURATION_SHORT_LONG: comparator = (f1, f2) -> { FeedMedia f1Media = f1.getMedia(); FeedMedia f2Media = f2.getMedia(); int duration1 = f1Media != null ? f1Media.getDuration() : -1; int duration2 = f2Media != null ? f2Media.getDuration() : -1; if (duration1 == -1 || duration2 == -1) return duration2 - duration1; else return duration1 - duration2; }; break; case DURATION_LONG_SHORT: comparator = (f1, f2) -> { FeedMedia f1Media = f1.getMedia(); FeedMedia f2Media = f2.getMedia(); int duration1 = f1Media != null ? f1Media.getDuration() : -1; int duration2 = f2Media != null ? f2Media.getDuration() : -1; return -1 * (duration1 - duration2); }; break; case FEED_TITLE_A_Z: comparator = (f1, f2) -> f1.getFeed().getTitle().compareTo(f2.getFeed().getTitle()); break; case FEED_TITLE_Z_A: comparator = (f1, f2) -> f2.getFeed().getTitle().compareTo(f1.getFeed().getTitle()); break; case RANDOM: permutor = Collections::shuffle; break; case SMART_SHUFFLE_OLD_NEW: permutor = (queue) -> smartShuffle(queue, true); break; case SMART_SHUFFLE_NEW_OLD: permutor = (queue) -> smartShuffle(queue, false); break; } if (comparator != null) { final Comparator<FeedItem> comparator2 = comparator; permutor = (queue) -> Collections.sort(queue, comparator2); } return permutor; } /** * Implements a reordering by pubdate that avoids consecutive episodes from the same feed in * the queue. * * A listener might want to hear episodes from any given feed in pubdate order, but would * prefer a more balanced ordering that avoids having to listen to clusters of consecutive * episodes from the same feed. This is what "Smart Shuffle" tries to accomplish. * * The Smart Shuffle algorithm involves spreading episodes from each feed out over the whole * queue. To do this, we calculate the number of episodes in each feed, then a common multiple * (not the smallest); each episode is then spread out, and we sort the resulting list of * episodes by "spread out factor" and feed name. * * For example, given a queue containing three episodes each from three different feeds * (A, B, and C), a simple pubdate sort might result in a queue that looks like the following: * * B1, B2, B3, A1, A2, C1, C2, C3, A3 * * (note that feed B episodes were all published before the first feed A episode, so a simple * pubdate sort will often result in significant clustering of episodes from a single feed) * * Using Smart Shuffle, the resulting queue would look like the following: * * A1, B1, C1, A2, B2, C2, A3, B3, C3 * * (note that episodes above <i>aren't strictly ordered in terms of pubdate</i>, but episodes * of each feed <b>do</b> appear in pubdate order) * * @param queue A (modifiable) list of FeedItem elements to be reordered. * @param ascending {@code true} to use ascending pubdate in the reordering; * {@code false} for descending. */ private static void smartShuffle(List<FeedItem> queue, boolean ascending) { // Divide FeedItems into lists by feed Map<Long, List<FeedItem>> map = new HashMap<>(); while (!queue.isEmpty()) { FeedItem item = queue.remove(0); Long id = item.getFeedId(); if (!map.containsKey(id)) { map.put(id, new ArrayList<>()); } map.get(id).add(item); } // Sort each individual list by PubDate (ascending/descending) Comparator<FeedItem> itemComparator = ascending ? (f1, f2) -> f1.getPubDate().compareTo(f2.getPubDate()) : (f1, f2) -> f2.getPubDate().compareTo(f1.getPubDate()); // Calculate the spread long spread = 0; for (Map.Entry<Long, List<FeedItem>> mapEntry : map.entrySet()) { List<FeedItem> feedItems = mapEntry.getValue(); Collections.sort(feedItems, itemComparator); if (spread == 0) { spread = feedItems.size(); } else if (feedItems.size() % spread != 0){ spread *= feedItems.size(); } } // Create a list of the individual FeedItems lists, and sort it by feed title (ascending). // Doing this ensures that the feed order we use is predictable/deterministic. List<List<FeedItem>> feeds = new ArrayList<>(map.values()); Collections.sort(feeds, (f1, f2) -> f1.get(0).getFeed().getTitle().compareTo(f2.get(0).getFeed().getTitle())); // Spread each episode out Map<Long, List<FeedItem>> spreadItems = new HashMap<>(); for (List<FeedItem> feedItems : feeds) { long thisSpread = spread / feedItems.size(); // Starting from 0 ensures we front-load, so the queue starts with one episode from // each feed in the queue long itemSpread = 0; for (FeedItem feedItem : feedItems) { if (!spreadItems.containsKey(itemSpread)) { spreadItems.put(itemSpread, new ArrayList<>()); } spreadItems.get(itemSpread).add(feedItem); itemSpread += thisSpread; } } // Go through the spread items and add them to the queue List<Long> spreads = new ArrayList<>(spreadItems.keySet()); Collections.sort(spreads); for (long itemSpread : spreads) { queue.addAll(spreadItems.get(itemSpread)); } } }
Fix the smart shuffle spread calculation We want to ensure that the total spread is divisible by all feed sizes, so the modulo calculation needs to divide spread by the feed size, not the other way round as is done currently. In addition, this ensures the per-feed spread is never 0 (so the degenerate case is equivalent to the old smart shuffle). Signed-off-by: Stephen Kitt <[email protected]>
core/src/main/java/de/danoeh/antennapod/core/util/QueueSorter.java
Fix the smart shuffle spread calculation
<ide><path>ore/src/main/java/de/danoeh/antennapod/core/util/QueueSorter.java <ide> Collections.sort(feedItems, itemComparator); <ide> if (spread == 0) { <ide> spread = feedItems.size(); <del> } else if (feedItems.size() % spread != 0){ <add> } else if (spread % feedItems.size() != 0){ <ide> spread *= feedItems.size(); <ide> } <ide> } <ide> Map<Long, List<FeedItem>> spreadItems = new HashMap<>(); <ide> for (List<FeedItem> feedItems : feeds) { <ide> long thisSpread = spread / feedItems.size(); <add> if (thisSpread == 0) { <add> thisSpread = 1; <add> } <ide> // Starting from 0 ensures we front-load, so the queue starts with one episode from <ide> // each feed in the queue <ide> long itemSpread = 0;
Java
epl-1.0
8a58d9105e97152e97812fd3f97b165f312e87b5
0
brfeddersen/sadlos2,brfeddersen/sadlos2,brfeddersen/sadlos2
/************************************************************************ * Copyright \u00a9 2007-2010 - General Electric Company, All Rights Reserved * * Project: SADL * * Description: The Semantic Application Design Language (SADL) is a * language for building semantic models and expressing rules that * capture additional domain knowledge. The SADL-IDE (integrated * development environment) is a set of Eclipse plug-ins that * support the editing and testing of semantic models using the * SADL language. * * This software is distributed "AS-IS" without ANY WARRANTIES * and licensed under the Eclipse Public License - v 1.0 * which is available at http://www.eclipse.org/org/documents/epl-v10.php * ***********************************************************************/ /*********************************************************************** * $Last revised by: crapo $ * $Revision: 1.10 $ Last modified on $Date: 2015/09/22 15:00:57 $ ***********************************************************************/ package com.ge.research.sadl.jena.translator; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ge.research.sadl.model.ModelError; import com.ge.research.sadl.model.gp.BuiltinElement; import com.ge.research.sadl.model.gp.BuiltinElement.BuiltinType; import com.ge.research.sadl.model.gp.GraphPatternElement; import com.ge.research.sadl.model.gp.Junction; import com.ge.research.sadl.model.gp.Junction.JunctionType; import com.ge.research.sadl.model.gp.KnownNode; import com.ge.research.sadl.model.gp.Literal; import com.ge.research.sadl.model.gp.NamedNode; import com.ge.research.sadl.model.gp.NamedNode.NodeType; import com.ge.research.sadl.model.gp.NegatedExistentialQuantifier; import com.ge.research.sadl.model.gp.Node; import com.ge.research.sadl.model.gp.ProxyNode; import com.ge.research.sadl.model.gp.Query; import com.ge.research.sadl.model.gp.Query.Order; import com.ge.research.sadl.model.gp.Query.OrderingPair; import com.ge.research.sadl.model.gp.RDFTypeNode; import com.ge.research.sadl.model.gp.Rule; import com.ge.research.sadl.model.gp.TripleElement; import com.ge.research.sadl.model.gp.TripleElement.TripleModifierType; import com.ge.research.sadl.model.gp.VariableNode; import com.ge.research.sadl.reasoner.ConfigurationException; import com.ge.research.sadl.reasoner.ConfigurationItem; import com.ge.research.sadl.reasoner.ConfigurationItem.ConfigurationType; import com.ge.research.sadl.reasoner.ConfigurationOption; import com.ge.research.sadl.reasoner.FunctionNotSupportedException; import com.ge.research.sadl.reasoner.IConfigurationManager; import com.ge.research.sadl.reasoner.IConfigurationManagerForEditing; import com.ge.research.sadl.reasoner.ITranslator; import com.ge.research.sadl.reasoner.InvalidNameException; import com.ge.research.sadl.reasoner.ModelError.ErrorType; import com.ge.research.sadl.reasoner.TranslationException; import com.ge.research.sadl.utils.SadlUtils; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.ontology.Ontology; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.reasoner.rulesys.Builtin; import com.hp.hpl.jena.reasoner.rulesys.BuiltinRegistry; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; public class JenaTranslatorPlugin implements ITranslator { protected static final Logger logger = LoggerFactory.getLogger(JenaTranslatorPlugin.class); private static final String TranslatorCategory = "Basic_Jena_Translator"; private static final String ReasonerFamily="Jena-Based"; protected IConfigurationManager configurationMgr; public enum TranslationTarget {RULE_TRIPLE, RULE_BUILTIN, QUERY_TRIPLE, QUERY_FILTER} private enum SpecialBuiltin {NOVALUE, NOVALUESPECIFIC, NOTONLY, ONLY, ISKNOWN} private enum RulePart {PREMISE, CONCLUSION, NOT_A_RULE} private Map<String, String> prefixes = new HashMap<String, String>(); private boolean saveRuleFileAfterModelSave = true; // unless set to false because an explicit list of rules are private Rule ruleInTranslation = null; private Query queryInTranslation = null; private int nextQueryVarNum = 1; private OntModel theModel; private String modelName; protected List<ModelError> errors = null; // provided, we need to look for rule files in // imported models and if there are any create a rule file // for this model so that the imported rule files will be loaded public List<ModelError> translateAndSaveModel(OntModel model, String translationFolder, String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException { // Jena models have been saved to the OwlModels folder by the ModelManager prior to calling the translator. For Jena // reasoners, no additional saving of OWL models is need so we can continue on to rule translation and saving. if (errors != null) { errors.clear(); } if (model == null) { return addError("Cannot save model in file '" + saveFilename + "' as it has no model."); } if (modelName == null) { return addError("Cannot save model in file '" + saveFilename + "' as it has no name."); } if (saveRuleFileAfterModelSave) { String ruleFilename = createDerivedFilename(saveFilename, "rules"); String fullyQualifiedRulesFilename = translationFolder + File.separator + ruleFilename; translateAndSaveRules(model, null, modelName, fullyQualifiedRulesFilename); } saveRuleFileAfterModelSave = false; // reset return (errors != null && errors.size() > 0) ? errors : null; } public List<ModelError> translateAndSaveModel(OntModel model, List<Rule> ruleList, String translationFolder, String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException { if (errors != null) { errors.clear(); } saveRuleFileAfterModelSave = false; // a Jena model simply writes out the OWL file translateAndSaveModel(model, translationFolder, modelName, orderedImports, saveFilename); String ruleFilename = createDerivedFilename(saveFilename, "rules"); String fullyQualifiedRulesFilename = translationFolder + File.separator + ruleFilename; if (ruleList != null && ruleList.size() > 0) { translateAndSaveRules(model, ruleList, modelName, fullyQualifiedRulesFilename); } else { // there isn't a rules file but make sure there isn't an old one around that needs to be deleted File oldRuleFile = new File(fullyQualifiedRulesFilename); if (oldRuleFile.exists() && oldRuleFile.isFile()) { try { oldRuleFile.delete(); } catch (Exception e) { addError("Failed to delete old rules file '" + fullyQualifiedRulesFilename + "'."); logger.error("Failed to delete old rule file '" + fullyQualifiedRulesFilename + "': " + e.getLocalizedMessage()); } } } return (errors != null && errors.size() > 0) ? errors : null; } public String translateRule(OntModel model, Rule rule) throws TranslationException { setRuleInTranslation(rule); boolean translateToBackwardRule = false; StringBuilder sb = new StringBuilder(); // put annotations (if any) in the rule if (rule.getAnnotations() != null) { Iterator<String[]> annItr = rule.getAnnotations().iterator(); sb.append("#/**\n"); while (annItr.hasNext()) { String[] annNVP = annItr.next(); sb.append("# * @"); sb.append(annNVP[0]); sb.append("\t"); String val = annNVP[1]; String linesep =System.lineSeparator(); String[] valLines = val.split(linesep); for (int i = 0; i < valLines.length; i++) { if (i > 0) { sb.append("# * "); } sb.append(valLines[i]); sb.append("\n"); } } sb.append("# */\n"); } if (translateToBackwardRule) { sb.append("["); sb.append(rule.getRuleName()); sb.append(": "); List<GraphPatternElement> thens = rule.getThens(); String thenStr = graphPatternElementsToJenaRuleString(thens, RulePart.CONCLUSION); if (thenStr != null) { sb.append(thenStr); } sb.append(" <- "); List<GraphPatternElement> givens = rule.getGivens(); String givenStr = graphPatternElementsToJenaRuleString(givens, RulePart.PREMISE); if (givenStr != null) { sb.append(givenStr); } List<GraphPatternElement> ifs = rule.getIfs(); String ifStr = graphPatternElementsToJenaRuleString(ifs, RulePart.PREMISE); if (ifStr != null) { if (givenStr != null) { sb.append(", "); } sb.append(ifStr); } sb.append("]"); } else { sb.append("["); sb.append(rule.getRuleName()); sb.append(": "); List<GraphPatternElement> givens = rule.getGivens(); String givenStr = graphPatternElementsToJenaRuleString(givens, RulePart.PREMISE); if (givenStr != null) { sb.append(givenStr); } List<GraphPatternElement> ifs = rule.getIfs(); String ifStr = graphPatternElementsToJenaRuleString(ifs, RulePart.PREMISE); if (ifStr != null) { if (givenStr != null) { sb.append(", "); } sb.append(ifStr); } sb.append(" -> "); List<GraphPatternElement> thens = rule.getThens(); String thenStr = graphPatternElementsToJenaRuleString(thens, RulePart.CONCLUSION); if (thenStr != null) { sb.append(thenStr); } sb.append("]"); } setRuleInTranslation(null); return (sb.length() > 0 ? sb.toString() : null); } private String graphPatternElementsToJenaRuleString(List<GraphPatternElement> elements, RulePart rulePart) throws TranslationException { int cnt = 0; if (elements != null && elements.size() > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; elements != null && i < elements.size(); i++) { if (cnt > 0) sb.append(", "); SpecialBuiltin spb = processSpecialBuiltins(elements, i); // check for special handling required for some built-ins if (spb != null) { // get the triple in question TripleElement trel = null; if (elements.get(i) instanceof TripleElement) { trel = (TripleElement)elements.get(i); } else { logger.error("Unhandled graph pattern element detected as special builtin: " + elements.get(i).toString()); } // translate based on type of spb if (spb.equals(SpecialBuiltin.NOVALUE)) { sb.append(createNoValue(trel, TranslationTarget.RULE_BUILTIN)); } else if (spb.equals(SpecialBuiltin.ISKNOWN)) { sb.append(graphPatternElementToJenaRuleString(trel, rulePart)); sb.append(", "); sb.append("bound(" + nodeToString(trel.getObject(), TranslationTarget.RULE_BUILTIN) + ")"); } else { if (spb.equals(SpecialBuiltin.NOVALUESPECIFIC)) { sb.append(createNoValueSpecific(trel, TranslationTarget.RULE_BUILTIN)); } else if (spb.equals(SpecialBuiltin.NOTONLY)) { sb.append(createNotOnly(trel, TranslationTarget.RULE_BUILTIN)); } else if (spb.equals(SpecialBuiltin.ONLY)) { sb.append(createOnly((TripleElement)elements.get(i), TranslationTarget.RULE_BUILTIN)); } else { logger.error("Unhandled special builtin: " + elements.toString()); } } } else { sb.append(graphPatternElementToJenaRuleString(elements.get(i), rulePart)); } cnt++; } return sb.toString(); } return null; } /** * Look for special built-ins and if found process them, modifying the element list as needed. * @param elements * @param index * @return */ private SpecialBuiltin processSpecialBuiltins(List<GraphPatternElement> elements, int index) { if (elements.get(index) instanceof TripleElement) { if (!((TripleElement)elements.get(index)).getModifierType().equals(TripleModifierType.None)) { TripleElement trel = (TripleElement)elements.get(index); if (trel.getModifierType().equals(TripleModifierType.Not)) { if (trel.getObject() instanceof KnownNode) { return SpecialBuiltin.NOVALUE; } else { return SpecialBuiltin.NOVALUESPECIFIC; } } else if (trel.getModifierType().equals(TripleModifierType.NotOnly)) { return SpecialBuiltin.NOTONLY; } else if (trel.getModifierType().equals(TripleModifierType.Only)) { return SpecialBuiltin.ONLY; } } else if (elements.size() > (index + 1) && elements.get(index + 1) instanceof BuiltinElement) { // these special builtins will be of the form: // x predicate y, op(y,z) // or in other words, the first argument of the operation will be the object of the triple // (is that restrictive enough??) BuiltinElement be = (BuiltinElement) elements.get(index + 1); BuiltinType bt = be.getFuncType(); List<Node> args = be.getArguments(); Node biarg1 = (args.size() > 0) ? args.get(0) : null; // builtin 0th argument node Node trobj = ((TripleElement)elements.get(index)).getObject(); // triple object node if (biarg1 != null && trobj != null && biarg1 instanceof NamedNode && trobj instanceof NamedNode && ((NamedNode)biarg1).getName().equals(((NamedNode)trobj).getName())) { if (bt.equals(BuiltinType.NotEqual) && args.size() == 2) { Node arg2 = args.get(1); if (arg2 instanceof KnownNode) { // this case: (x pred y), !=(y, known) // just drop the i+1 builtin elements.remove(index + 1); return SpecialBuiltin.NOVALUE; } else { // this case: (x pred y), !=(y, z) // move the z to the object of the triple and drop the i+1 builtin if (args.size() > 1) { Node biarg2 = args.get(1); Node trsubj = ((TripleElement)elements.get(index)).getSubject(); if (biarg2 instanceof NamedNode && !(biarg2 instanceof VariableNode) && trsubj instanceof NamedNode && !(((NamedNode)biarg2).getName().equals(((NamedNode)trsubj).getName()))) { ((TripleElement)elements.get(index)).setObject(args.get(1)); elements.remove(index + 1); return SpecialBuiltin.NOVALUESPECIFIC; } } } } else if (bt.equals(BuiltinType.NotOnly)) { ((TripleElement)elements.get(index)).setObject(args.get(1)); elements.remove(index + 1); return SpecialBuiltin.NOTONLY; } else if (bt.equals(BuiltinType.Only)) { ((TripleElement)elements.get(index)).setObject(args.get(1)); elements.remove(index + 1); return SpecialBuiltin.ONLY; } } } else if (((TripleElement)elements.get(index)).getObject() instanceof KnownNode) { Node var = new VariableNode("v" + System.currentTimeMillis()); ((TripleElement)elements.get(index)).setObject(var); return SpecialBuiltin.ISKNOWN; } } return null; } private String createNoValue(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); return "noValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ")"; } private Object createNoValueSpecific(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); Node arg3 = trel.getObject(); return "noValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")"; } private Object createOnly(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); Node arg3 = trel.getObject(); return "noValuesOtherThan(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")"; } private Object createNotOnly(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); Node arg3 = trel.getObject(); return "notOnlyValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")"; } @SuppressWarnings("unused") public String translateQuery(OntModel model, Query query) throws TranslationException, InvalidNameException { boolean isEval = false; setTheModel(model); setModelName(modelName); if (query == null) { throw new TranslationException("Invalid query: query is null!"); } if (query.getPatterns() != null) { GraphPatternElement gpe1 = query.getPatterns().get(0); if (gpe1 instanceof Junction) { Object gperhs = ((Junction)gpe1).getRhs(); if (gperhs instanceof BuiltinElement && ((BuiltinElement)gperhs).getFuncName().equalsIgnoreCase("eval")) { isEval = true; Object gpelhs = ((Junction)gpe1).getLhs(); if (gpelhs instanceof GraphPatternElement) { query.getPatterns().set(0, (GraphPatternElement) gpelhs); query.setToBeEvaluated(true); } } } } if (query.getSparqlQueryString() != null) { return prepareQuery(model, query.getSparqlQueryString()); } if (query.getKeyword() == null) { if (query.getVariables() == null) { query.setKeyword("ask"); } else { query.setKeyword("select"); } } if (!query.getKeyword().equals("ask") && query.getVariables() == null) { throw new TranslationException("Invalid query (" + query.toString() + "): must be a valid structure with specified variable(s)."); } setQueryInTranslation(query); StringBuilder sbmain = new StringBuilder(); StringBuilder sbfilter = new StringBuilder(); sbmain.append(query.getKeyword()); if (query.isDistinct()) { sbmain.append("distinct "); } List<String> vars = query.getVariables(); List<GraphPatternElement> elements = query.getPatterns(); for (int i = 0; vars != null && i < vars.size(); i++) { if (i > 0) sbmain.append(" "); sbmain.append("?" + vars.get(i)); } sbmain.append(" where {"); int tripleCtr = 0; int builtinCtr = 0; for (int i = 0; elements != null && i < elements.size(); i++) { GraphPatternElement gpe = elements.get(i); // need to handle or, and if (gpe instanceof Junction) { if (tripleCtr++ > 0) sbmain.append(" . "); String junctionStr = junctionToQueryString((Junction)gpe, sbfilter); sbmain.append(junctionStr); } else if (gpe instanceof TripleElement) { if (tripleCtr++ > 0) sbmain.append(" . "); String jenaStr = graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE); sbmain.append(jenaStr); } else if (gpe instanceof BuiltinElement) { // if (builtinCtr++ > 0) { // sbfilter.append(" && "); // } // else { // sbfilter.append("FILTER ("); // } // sbfilter.append(graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_FILTER)); // the filter string will be added in the method graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); } } if (sbfilter.length() > 0) { sbfilter.insert(0, "FILTER ("); sbfilter.append(")"); if (!sbmain.toString().trim().endsWith(".")) { sbmain.append(" . "); } sbmain.append(sbfilter.toString()); } sbmain.append("}"); if (query.getOrderBy() != null) { List<OrderingPair> ops = query.getOrderBy(); if (ops.size() > 0) { sbmain.append(" order by"); for (int i = 0; i < ops.size(); i++) { sbmain.append(" "); OrderingPair op = ops.get(i); boolean explicitOrder = false; if (op.getOrder() != null && op.getOrder().equals(Order.DESC)) { sbmain.append("DESC("); explicitOrder = true; } sbmain.append("?"); sbmain.append(op.getVariable()); if (explicitOrder) { sbmain.append(")"); } } } } return prepareQuery(model, sbmain.toString()); } /** * Convert a junction to a query string. Filter stuff goes to the sbfilter StringBuilder, triple stuff gets returned. * * @param gpe * @param sbfilter * @return * @throws TranslationException */ private String junctionToQueryString(Junction gpe, StringBuilder sbfilter) throws TranslationException { // We have a junction, could be one of // 1. triple junction filter, e.g., ... x prop y and y < 3 // 2. filter junction triple, e.g., ... y < 3 and x prop z // 3. filter junction filter, e.g., ... x > 0 and x < 3 // 4. triple junction triple, e.g., ... x prop1 y and y prop2 z JunctionType jtype = ((Junction)gpe).getJunctionType(); boolean lhsFilter = false; boolean rhsFilter = false; Object lhsobj = ((Junction)gpe).getLhs(); Object rhsobj = ((Junction)gpe).getRhs(); if (lhsobj instanceof BuiltinElement) { lhsFilter = true; } if (rhsobj instanceof BuiltinElement) { rhsFilter = true; } StringBuilder sbjunct = new StringBuilder(); String connector = null; boolean wrapInCurleyBrackets = false; if (lhsFilter || rhsFilter) { if (lhsFilter && rhsFilter) { // this is a junction within the filter, case 3 connector = junctionToFilterString(jtype); sbfilter.append("("); graphPatternElementToJenaQueryString((GraphPatternElement)lhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); sbfilter.append(connector); graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); sbfilter.append(")"); } else { // Note: junctions between a triple and a built-in filter are ignored, cases 1 & 2 if (lhsFilter) { graphPatternElementToJenaQueryString((GraphPatternElement)lhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); if (rhsobj instanceof BuiltinElement) { sbfilter.append(junctionToFilterString(jtype)); } sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); } else { // rhsFilter sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) lhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); if (lhsobj instanceof BuiltinElement) { sbfilter.append(junctionToFilterString(jtype)); } graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); } } } else { // this is a junction between triple patterns, case 4 if (jtype.equals(JunctionType.Conj)) { // (and) connector = " . "; } else { // must be Disj (or) wrapInCurleyBrackets = true; connector = "} UNION {"; } if (wrapInCurleyBrackets) { sbjunct.append("{"); } sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) lhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); sbjunct.append(connector); sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); if (wrapInCurleyBrackets) { sbjunct.append("}"); } } return sbjunct.toString(); } private String junctionToFilterString(JunctionType jtype) { if (jtype.equals(JunctionType.Conj)) { // and return " && "; } else { // must be Disj (or) return " || "; } } private String builtinToFilterFunctionString(BuiltinElement gpe) throws TranslationException { List<Node> args = gpe.getArguments(); if (args.size() < 2) { throw new TranslationException("Filter '" + gpe.getFuncName() + "' must take two arguments."); } if (gpe.getFuncType().equals(BuiltinType.Equal)) { gpe.setFuncName("="); // there are several possibilities here that all map to "=" in SPARQL } if (gpe.getFuncType().equals(BuiltinType.Not)) { gpe.setFuncName("!="); } switch(gpe.getFuncType()) { case Equal: case GT: case GTE: case LT: case LTE: case NotEqual: case Not: String filter = nodeToString(args.get(0), TranslationTarget.QUERY_FILTER) + " " + gpe.getFuncName() + " " + nodeToString(args.get(1), TranslationTarget.QUERY_FILTER); return filter; // nodeToString(args.get(0), TranslationTarget.QUERY_FILTER) + " " + gpe.getFuncName() + " " + nodeToString(args.get(1), TranslationTarget.QUERY_FILTER); default: throw new TranslationException("Unhandled filter type: " + gpe.getFuncName()); } } private boolean translateAndSaveRules(OntModel model, List<Rule> ruleList, String modelName, String filename) throws TranslationException, IOException { if (ruleList == null || ruleList.size() < 1) { throw new TranslationException("No rules provided to rule translation."); } // Open file and output header and imports File ruleFile = new File(filename); if (ruleFile.exists()) { boolean success = ruleFile.delete(); if (!success) { addError("Failed to delete old rules file '" + filename + "'."); logger.error("Failed to delete old rule file '" + filename + "'."); if (ruleList == null || ruleList.size() == 0) { setTheModel(null); setModelName(null); return false; } // else don't return--maybe we can open it for output anyway } } String jenaRules = translateAndSaveRules(model, ruleList, modelName) ; SadlUtils su = new SadlUtils(); su.stringToFile(ruleFile, jenaRules, true); return (errors== null || errors.size() == 0) ? true : false; } /** * Save the * @param model * @param ruleList * @param modelName * @return * @throws TranslationException */ public String translateAndSaveRules(OntModel model, List<Rule> ruleList, String modelName) throws TranslationException { if (ruleList == null) { return null; } setTheModel(model); setModelName(modelName); StringBuilder contents = new StringBuilder(); contents.append("# Jena Rules file generated by SADL IDE -- Do not edit! Edit the SADL model and regenerate.\n"); contents.append("# Created from SADL model '" + modelName + "'\n\n"); StringBuilder ruleContent = new StringBuilder(); for (int i = 0; i < ruleList.size(); i++) { Rule rule = ruleList.get(i); ruleContent.append(translateRule(model, rule)); ruleContent.append("\n"); } // now add prefix info to rule file output Iterator<String> itr2 = prefixes.keySet().iterator(); while (itr2.hasNext()) { String prefix = itr2.next(); String ns = prefixes.get(prefix); contents.append("@prefix "); contents.append(prefix); contents.append(": <"); contents.append(ns); contents.append(">\n"); } contents.append("\n"); // Because rule files are loaded for each sub-model, there is no need to put in includes if (ruleContent.length() > 0) { contents.append(ruleContent); } setTheModel(null); setModelName(null); return contents.toString(); } public String modelNsToRuleNs(String modelNs) { return modelNs + ".rules"; } /** * Convert GraphPatternElement to String in the context of a Rule * * @param gpe * @return * @throws TranslationException */ @SuppressWarnings("unchecked") private String graphPatternElementToJenaRuleString(GraphPatternElement gpe, RulePart rulePart) throws TranslationException { StringBuilder sb = null; if (gpe instanceof TripleElement) { if (!((TripleElement)gpe).getModifierType().equals(TripleModifierType.None)) { sb = new StringBuilder(); TripleModifierType type = ((TripleElement)gpe).getModifierType(); if (type.equals(TripleModifierType.Not)) { sb.append("noValue("); } else if (type.equals(TripleModifierType.Only)) { sb.append("notOnlyValue("); } else { sb.append("noValueOtherThan("); } sb.append(nodeToString(((TripleElement)gpe).getSubject(),TranslationTarget.RULE_BUILTIN)); sb.append(", "); Node pn = ((TripleElement)gpe).getPredicate(); checkPredicateSpecial(pn); sb.append(nodeToString(pn, TranslationTarget.RULE_BUILTIN)); if (!(((TripleElement)gpe).getObject() instanceof KnownNode)) { sb.append(", "); sb.append(nodeToString(((TripleElement)gpe).getObject(), TranslationTarget.RULE_BUILTIN)); } sb.append(")"); } else { sb = tripleElementToRawJenaString((TripleElement) gpe, TranslationTarget.RULE_TRIPLE, rulePart, null); // 2/16/2011 false); } } else if (gpe instanceof BuiltinElement) { sb = new StringBuilder(); List<Node> args = ((BuiltinElement)gpe).getArguments(); sb.append(builtinTypeToString((BuiltinElement)gpe)); sb.append("("); for (int i = 0; args != null && i < args.size(); i++) { Node arg = args.get(i); if (i > 0) sb.append(", "); if (arg instanceof ProxyNode) { Object pfor = ((ProxyNode)arg).getProxyFor(); if (pfor instanceof GraphPatternElement) { sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) pfor, rulePart)); } else { throw new TranslationException("Non-graph element proxy-for in ProxyNode '" + arg.toFullyQualifiedString() + "'"); } } else { sb.append(nodeToString(arg, TranslationTarget.RULE_BUILTIN)); } } sb.append(")"); } else if (gpe instanceof Junction) { sb = new StringBuilder(); JunctionType jtype = ((Junction)gpe).getJunctionType(); if (jtype.equals(JunctionType.Conj)) { Object lhs = ((Junction)gpe).getLhs(); if (lhs instanceof List<?>) { sb.append(graphPatternElementsToJenaRuleString((List<GraphPatternElement>)lhs, rulePart)); } else if (lhs instanceof GraphPatternElement) { sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) lhs, rulePart)); } else { throw new TranslationException("Unexpected junction lhs type: " + lhs.getClass()); } Object rhs = ((Junction)gpe).getRhs(); if (rhs instanceof List<?>) { sb.append(", "); sb.append(graphPatternElementsToJenaRuleString((List<GraphPatternElement>)rhs, rulePart)); } else if (rhs instanceof GraphPatternElement) { sb.append(", "); sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) rhs, rulePart)); } else { throw new TranslationException("Unexpected junction rhs type: " + rhs.getClass()); } } else { System.err.println("Encountered unhandled OR in rule '" + ruleInTranslation.getRuleName() + "'"); // throw new TranslationException("Jena rules do not currently support disjunction (OR)."); } } else if (gpe instanceof NegatedExistentialQuantifier) { throw new TranslationException("Existential quantification with negation is not supported by the Jena reasoner."); } else { throw new TranslationException("GraphPatternElement '" + gpe.toString() + "' cannot be translated to Jena rule."); } return sb.toString(); } private String graphPatternElementToJenaQueryString(GraphPatternElement gpe, StringBuilder sbfilter, TranslationTarget target, RulePart rulePart) throws TranslationException { if (gpe instanceof TripleElement) { StringBuilder sb = tripleElementToRawJenaString((TripleElement) gpe, target, rulePart, sbfilter); return sb.toString(); } else if (gpe instanceof Junction) { String junctStr = junctionToQueryString((Junction)gpe, sbfilter); return junctStr; } else if (gpe instanceof BuiltinElement) { String bistr = builtinToFilterFunctionString((BuiltinElement)gpe); if (sbfilter.length() > 0) { String tmp = sbfilter.toString().trim(); if (!tmp.endsWith("(") && !tmp.endsWith("&&") && !tmp.endsWith("||")) { sbfilter.append(" && "); } } sbfilter.append(bistr); return null; } else { throw new TranslationException("GraphPatternElement '" + gpe.toString() + "' not yet handled in Jena query."); } } /** * Method to convert a TripleElement to a Jena String without delimiters * * @param gpe * @param sbfilter * @return * @throws TranslationException */ private StringBuilder tripleElementToRawJenaString(TripleElement gpe, TranslationTarget target, RulePart rulePart, StringBuilder sbfilter) throws TranslationException { StringBuilder sb = new StringBuilder(); Node subj = gpe.getSubject(); Node pred = gpe.getPredicate(); checkPredicateSpecial(pred); Node obj = gpe.getObject(); boolean moveObjectToEqualityTest = false; if (target.equals(TranslationTarget.RULE_TRIPLE)) { sb.insert(0, '('); } sb.append(nodeToString(subj, target)); sb.append(" "); sb.append(nodeToString(pred, target)); sb.append(" "); String newVar = null; if (rulePart.equals(RulePart.PREMISE) && target.equals(TranslationTarget.RULE_TRIPLE) && tripleHasDecimalObject(gpe)) { // this would be a triple match on a float or double value, which is not reliable // move the object to a separate equality test moveObjectToEqualityTest = true; newVar = getNewVariableForRule(); sb.append("?"); sb.append(newVar); } else { if (rulePart.equals(RulePart.NOT_A_RULE)) { if (obj instanceof KnownNode) { newVar = "?" + getNewVariableForQuery(); if (gpe.getModifierType().equals(TripleModifierType.Not)) { sb.append(newVar); sb.insert(0, "OPTIONAL {"); sb.append("}"); if (sbfilter != null) { if (sbfilter.length() > 0) { sbfilter.append(" && "); } sbfilter.append("!bound("); sbfilter.append(newVar); sbfilter.append(")"); } } else { sb.append(newVar); } } else if (tripleHasDecimalObject(gpe)) { newVar = "?" + getNewVariableForQuery(); sb.append(newVar); if (sbfilter != null) { if (sbfilter.length() > 0) { sbfilter.append(" && "); } sbfilter.append(newVar); if (gpe.getModifierType().equals(TripleModifierType.Not)) { sbfilter.append(" != "); } else { sbfilter.append(" = "); } sbfilter.append(nodeToString(obj, TranslationTarget.RULE_BUILTIN)); } else { sb.append(newVar); } } else { sb.append(nodeToString(obj, target)); } } else { sb.append(nodeToString(obj, target)); } } if (target.equals(TranslationTarget.RULE_TRIPLE)) { sb.append(")"); } else { // this is a query if (gpe.getModifierType() != null && gpe.getModifierType().equals(TripleModifierType.Not)) { // this is negation--translate into a filter on !exits sb.insert(0, "!EXISTS { "); sb.append(" }"); sbfilter.append(sb); sb.setLength(0); } } if (moveObjectToEqualityTest) { // now add the equality test. (this is only for rules) sb.append(" equal(?"); sb.append(newVar); sb.append(", "); sb.append(nodeToString(obj, TranslationTarget.RULE_BUILTIN)); sb.append(")"); } return sb; } private String getNewVariableForRule() { int cntr = 1; Rule rule = getRuleInTranslation(); if (rule != null) { String rulestr = rule.toString(); String varName; do { varName = "v" + cntr++; } while (rulestr.indexOf(varName) > 0); return varName; } else { return "v1"; } } private String getNewVariableForQuery() { int cntr = nextQueryVarNum; Query query = getQueryInTranslation(); String querystr = query.toString(); String varName; do { varName = "v" + cntr++; } while (querystr.indexOf(varName) > 0); nextQueryVarNum = cntr; return varName; } private boolean tripleHasDecimalObject(TripleElement gpe) { Node pred = gpe.getPredicate(); Node obj = gpe.getObject(); if (!(obj instanceof NamedNode) && pred instanceof NamedNode && ((NamedNode)pred).getNamespace() != null) { OntProperty prop = getTheModel().getOntProperty(((NamedNode)pred).toFullyQualifiedString()); if (prop != null && prop.isDatatypeProperty()) { Resource rng = prop.getRange(); if (rng.toString().contains("double") || rng.toString().contains("float")) { return true; } } } if (obj instanceof Literal) { Object objval = ((Literal)obj).getValue(); if (objval instanceof Double || objval instanceof Float) { return true; } } return false; } private void checkPredicateSpecial(Node predNode) { if (predNode instanceof NamedNode) { if (((NamedNode)predNode).getNamespace() == null && ((NamedNode)predNode).getName() != null && ((NamedNode)predNode).getName().equals(RDFS.comment.getLocalName()) ) { ((NamedNode)predNode).setNamespace(RDFS.getURI()); } } } private Object builtinTypeToString(BuiltinElement bin) throws TranslationException { BuiltinType ftype = bin.getFuncType(); if (ftype.equals(BuiltinType.Divide)) { // return "quotient"; bin.setFuncName("quotient"); } else if (ftype.equals(BuiltinType.Equal)) { // return "equal"; bin.setFuncName("equal"); } else if (ftype.equals(BuiltinType.GT)) { // return "greaterThan"; bin.setFuncName("greaterThan"); } else if (ftype.equals(BuiltinType.GTE)) { // return "ge"; bin.setFuncName("ge"); } else if (ftype.equals(BuiltinType.LT)) { // return "lessThan"; bin.setFuncName("lessThan"); } else if (ftype.equals(BuiltinType.LTE)) { // return "le"; bin.setFuncName("le"); } else if (ftype.equals(BuiltinType.Minus)) { // return "difference"; bin.setFuncName("difference"); } else if (ftype.equals(BuiltinType.Modulus)) { // return "mod"; bin.setFuncName("mod"); } else if (ftype.equals(BuiltinType.Multiply)) { // return "product"; bin.setFuncName("product"); } else if (ftype.equals(BuiltinType.Negative)) { // return "negative"; bin.setFuncName("negative"); } else if (ftype.equals(BuiltinType.Not)) { // return "noValue"; bin.setFuncName("noValue"); } else if (ftype.equals(BuiltinType.NotEqual)) { // return "notEqual"; bin.setFuncName("notEqual"); } else if (ftype.equals(BuiltinType.NotOnly)) { // return "notOnlyValue"; bin.setFuncName("notOnlyValue"); } else if (ftype.equals(BuiltinType.Only)) { // return "noValuesOtherThan"; bin.setFuncName("noValuesOtherThan"); } else if (ftype.equals(BuiltinType.Plus)) { // return "sum"; bin.setFuncName("sum"); } else if (ftype.equals(BuiltinType.Power)) { // return "pow"; bin.setFuncName("pow"); } else if (ftype.equals(BuiltinType.Assign)) { // return "assign"; bin.setFuncName("assign"); } String builtinName = bin.getFuncName(); // Note: the order here allows any built-in which overrides the ones in Jena to be picked up preferentially // see if it is known to the ConfigurationManager or if we can find it in the services registry boolean status = findOrAddBuiltin(builtinName); if (!status) { // if not see if it is one already registered Builtin bltin = BuiltinRegistry.theRegistry.getImplementation(builtinName); if (bltin == null) { logger.error("Something went wrong finding/loading Builtin '" + builtinName + "'"); addError("Unable to resolve built-in '" + builtinName + "'"); } } return builtinName; } @SuppressWarnings("unused") private boolean findOrAddBuiltin(String builtinName) { int cnt = 0; // is it known to the ConfigurationManager? String[] categories = new String[2]; try { categories[0] = configurationMgr.getReasoner().getReasonerFamily(); categories[1] = IConfigurationManager.BuiltinCategory; List<ConfigurationItem> knownBuiltins = configurationMgr.getConfiguration(categories, false); for (int i = 0; knownBuiltins != null && i < knownBuiltins.size(); i++) { ConfigurationItem item = knownBuiltins.get(i); Object itemName = item.getNamedValue("name"); if (itemName != null && itemName instanceof String && ((String)itemName).equals(builtinName)) { logger.debug("Built-in '" + builtinName + "' found in configuration."); return true; } } } catch (ConfigurationException e) { // this is ok--new ones won't be found // e.printStackTrace(); // logger.error("Unable to find Builtin '" + builtinName + "' in current configuration: " + e.getLocalizedMessage()); } // Use ServiceLoader to find an implementation of Builtin that has this name ServiceLoader<Builtin> serviceLoader = ServiceLoader.load(Builtin.class); if( serviceLoader != null ){ logger.debug("ServiceLoader is OK"); for( Iterator<Builtin> itr = serviceLoader.iterator(); itr.hasNext() ; ){ try { Builtin bltin = itr.next(); cnt++; if (bltin.getName().equals(builtinName)) { String clsname = bltin.getClass().getCanonicalName(); // TODO is there a reasonable check here? if (1 > 0) { if (configurationMgr instanceof IConfigurationManagerForEditing) { ConfigurationItem newItem = new ConfigurationItem(categories); newItem.addNameValuePair(newItem.new NameValuePair("name", builtinName, ConfigurationType.Bag)); newItem.addNameValuePair(newItem.new NameValuePair("class", clsname, ConfigurationType.Bag)); ((IConfigurationManagerForEditing) configurationMgr).addConfiguration(newItem); ((IConfigurationManagerForEditing) configurationMgr).saveConfiguration(); logger.info("Built-in '" + builtinName + "' found in service registry and added to configuration."); } } else { logger.info("Built-in '" + builtinName + "' found in service registry."); } BuiltinRegistry.theRegistry.register(builtinName, bltin); return true; } } catch (Throwable t) { t.printStackTrace(); logger.error(t.getLocalizedMessage()); } } } else { logger.debug("ServiceLoader is null"); } logger.debug("Failed to find Builtin with name '" + builtinName + "' after examining " + cnt + " registered Builtins."); return false; } private String nodeToString(Node node, TranslationTarget target) throws TranslationException { if (node instanceof NamedNode) { NodeType ntype = ((NamedNode)node).getNodeType(); if (ntype.equals(NodeType.VariableNode)) { // double-check this; if a concept was declared after reference in a rule or query // it may have been parsed as a variable but actually be a defined concept OntResource r = getTheModel().getOntResource(getModelName() + "#" + ((NamedNode)node).getName()); if (r == null) { return "?" + ((NamedNode)node).getName(); } // it appears that at time of parsing of the rule or query the named concept was not defined but // was subsequently. Warn user of this apparent error: concepts must be defined before they are // used in a rule or query. String msg = "The concept '" + ((NamedNode)node).getName() + "' "; if (ruleInTranslation != null) { msg += "in rule '" + ruleInTranslation.getRuleName() + "' "; } msg += " in model '" + getModelName() + "' is used before it is defined. Please define the concept before referencing it in a query or rule."; addError(msg); logger.error(msg); } if (node instanceof RDFTypeNode) { // registerPrefix("rdf", ""); I don't think these need an explicit prefix awc 11/23/2010 if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) { return "<rdf:type>"; } else { return "rdf:type"; } } else { String nts; if (((NamedNode)node).getNamespace() != null) { String prefix = ((NamedNode)node).getPrefix(); if (prefix != null) { registerPrefix(prefix, ((NamedNode)node).getNamespace()); } else { // this must be the default namespace ((NamedNode)node).setPrefix(""); } nts = ((NamedNode)node).getNamespace() + ((NamedNode)node).getName(); } else { nts = ((NamedNode)node).getName(); } if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) { return "<" + nts + ">"; } else { return nts; } } } else if (node instanceof Literal) { Object litObj = ((Literal)node).getValue(); return literalValueToString(litObj, target); } else if (node instanceof KnownNode) { return "?" + getNewVariableForRule(); } else if (node == null) { throw new TranslationException("Encountered null node in nodeToString; this indicates incorrect intermediate form and should not happen"); } else { throw new TranslationException("Nnode '" + node.toString() + "' cannot be translated to Jena format."); } } public static synchronized String literalValueToString(Object litObj, TranslationTarget target) { if (litObj instanceof String) { litObj = "\"" + litObj + "\""; } if (litObj instanceof String) { return (String)litObj; } else if (litObj instanceof Boolean) { if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#boolean>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#boolean"; } } else if (litObj instanceof Long) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#long>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#long"; } } else if (litObj instanceof Integer) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#int>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#int"; } } else if (litObj instanceof Double) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#double>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#double"; } } else if (litObj instanceof Float) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#float>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#float"; } } else { return litObj.toString(); } } private void registerPrefix(String prefix, String namespace) { if (prefix == null) { logger.error("Prefix is null in registerPrefix"); } if (!prefixes.containsKey(prefix)) { prefixes.put(prefix, namespace); } } protected String createDerivedFilename(String filename, String newext) { int lastDot = filename.lastIndexOf('.'); if (lastDot > 0) { return filename.substring(0, lastDot + 1) + newext; } return filename + "." + newext; } /** * Method to prepare a query by expanding the URIs of concepts to be complete URIs * * @param model * @param q * @return * @throws InvalidNameException */ public String prepareQuery(OntModel model, String q) throws InvalidNameException { int openBracket = q.indexOf('<'); if (openBracket > 0) { int closeBracket = q.indexOf('>', openBracket); if (closeBracket <= openBracket) { // this could be a comparison in a FILTER... return q; } String before = q.substring(0, openBracket + 1); String url = q.substring(openBracket + 1, closeBracket); String rest = q.substring(closeBracket); rest = prepareQuery(model, rest); if (url.indexOf('#') > 0) { return before + url + rest; } else if (url.indexOf(':') > 0) { url = expandPrefixedUrl(model, url); } else if (isValidLocalName(url)){ url = findNameNs(model, url); } return before + url + rest; } return q; } protected boolean isValidLocalName(String name) { if (name == null || name.indexOf(" ") >= 0 || name.indexOf("?") >= 0) { return false; } return true; } /** * This method takes an OntModel and a concept name and tries to find the concept in the model or * one of the models imported by the model. * * @param model -- the OntModel at the root of the search * @param name -- the concept name * @return -- the fully-qualified name of the concept as found in some model * * @throws InvalidNameException -- the concept was not found */ public static synchronized String findNameNs(OntModel model, String name) throws InvalidNameException { String uri = findConceptInSomeModel(model, name); if (uri != null) { return uri; } Iterator<String> impitr = model.listImportedOntologyURIs(true).iterator(); while (impitr.hasNext()) { String impuri = impitr.next(); if (!impuri.endsWith("#")) { impuri += "#"; } impuri = getUriInModel(model, impuri, name); if (impuri != null) { logger.debug("found concept with URI '" + impuri + "'"); return impuri; } } ExtendedIterator<Ontology> oitr = model.listOntologies(); while (oitr.hasNext()) { Ontology onto = oitr.next(); if (onto != null) { ExtendedIterator<OntResource> importsItr = onto.listImports(); while (importsItr.hasNext()) { OntResource or = importsItr.next(); String ns = or.getURI(); if (!ns.endsWith("#")) { ns = ns + "#"; } String muri = getUriInModel(model, or.getURI(), name); if (muri != null) { logger.debug("found concept with URI '" + muri + "'"); return muri; } } // try this ontology--maybe it wasn't in the map used by findConceptInSomeModel String muri = getUriInModel(model, onto.getURI() + "#", name); if (muri != null) { logger.debug("found concept with URI '" + muri + "'"); return muri; } } } if (logger.isDebugEnabled()) { logger.debug("Failed to find '" + name + "' in any model."); ByteArrayOutputStream sos = new ByteArrayOutputStream(); model.write(sos); logger.debug(sos.toString()); } throw new InvalidNameException("'" + name + "' not found in any model."); } private static synchronized String findConceptInSomeModel(OntModel model, String name) { Map<String, String> map = model.getNsPrefixMap(); Iterator<String> uriitr = map.values().iterator(); while (uriitr.hasNext()) { String ns = uriitr.next(); String uri = getUriInModel(model, ns, name); if (uri != null) { logger.debug("found concept with URI '" + uri + "'"); return uri; } } logger.debug("did not find concept with name '" + name + "'"); return null; } private static synchronized String getUriInModel(OntModel model, String ns, String name) { Resource r = model.getAnnotationProperty(ns + name); if (r != null) { return r.getURI(); } r = model.getDatatypeProperty(ns + name); if (r != null) { return r.getURI(); } r = model.getObjectProperty(ns + name); if (r != null) { return r.getURI(); } r = model.getOntClass(ns + name); if (r != null) { return r.getURI(); } r = model.getIndividual(ns + name); if (r != null) { return r.getURI(); } if (RDF.type.getURI().equals(ns + name)) { return RDF.type.getURI(); } return null; } protected String expandPrefixedUrl(OntModel model, String name) { String prefix = name.substring(0, name.indexOf(':')); String lname = name.substring(name.indexOf(':') + 1); String ns = model.getNsPrefixURI(prefix); if (ns != null) { name = ns + lname; } return name; } protected List<ModelError> addError(String msg) { if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(new ModelError(msg, ErrorType.ERROR)); return errors; } protected List<ModelError> addError(String msg, ErrorType errType) { if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(new ModelError(msg, errType)); return errors; } protected List<ModelError> addError(ModelError err) { if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(err); return errors; } public String getReasonerFamily() { return ReasonerFamily; } public String getConfigurationCategory() { return TranslatorCategory; } private void setRuleInTranslation(Rule ruleInTranslation) { this.ruleInTranslation = ruleInTranslation; } private Rule getRuleInTranslation() { return ruleInTranslation; } private void setTheModel(OntModel theModel) { this.theModel = theModel; } private OntModel getTheModel() { return theModel; } public Map<String, ConfigurationOption> getTranslatorConfigurationOptions() { // This translator doesn't have any configuration items return null; } public boolean configure(ConfigurationItem configItem) { // This translator doesn't have any configuration items return false; } public boolean configure(List<ConfigurationItem> configItems) { // This translator doesn't have any configuration items return false; } public List<ConfigurationItem> discoverOptimalConfiguration( String translationFolder, String modelName, IConfigurationManager configMgr, List<Query> queries) throws FunctionNotSupportedException, ConfigurationException, TranslationException { throw new FunctionNotSupportedException(this.getClass().getCanonicalName() + " does not support discovery of optimal configuration."); } private Query getQueryInTranslation() { return queryInTranslation; } private void setQueryInTranslation(Query queryInTranslation) { this.queryInTranslation = queryInTranslation; } public void setConfigurationManager(IConfigurationManager configMgr) throws ConfigurationException { // if ((configMgr instanceof IConfigurationManagerForEditing)) { // ((IConfigurationManagerForEditing) configMgr).setTranslatorClassName(this.getClass().getCanonicalName()); // } configurationMgr = configMgr; } private String getModelName() { return modelName; } private void setModelName(String modelName) { this.modelName = modelName; } @Override public List<ModelError> translateAndSaveModelWithOtherStructure( OntModel model, Object otherStructure, String translationFolder, String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException { throw new TranslationException("This translator (" + this.getClass().getCanonicalName() + ") does not translate other knowledge structures."); } public List<ModelError> validateRule(com.ge.research.sadl.model.gp.Rule rule) { List<ModelError> errors = null; // conclusion binding tests List<GraphPatternElement> thens = rule.getThens(); for (int i = 0; thens != null && i < thens.size(); i++) { GraphPatternElement gpe = thens.get(i); if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); if (args == null) { ModelError me = new ModelError("Built-in '" + ((BuiltinElement)gpe).getFuncName() + "' with no arguments not legal in rule conclusion", ErrorType.ERROR); if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(me); } else { for (int j = 0; j < args.size(); j++) { Node arg = args.get(j); if (arg instanceof VariableNode) { if (!variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, arg) && !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, arg)) { ModelError me = new ModelError("Conclusion built-in '" + ((BuiltinElement)gpe).getFuncName() + "', variable argument '" + arg.toString() + "' is not bound in rule premises", ErrorType.ERROR); if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(me); } } } } } else if (gpe instanceof TripleElement) { if (((TripleElement)gpe).getSubject() instanceof VariableNode && !variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, ((TripleElement)gpe).getSubject()) && !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, ((TripleElement)gpe).getSubject())) { ModelError me = new ModelError("Subject of conclusion triple '" + gpe.toString() + "' is not bound in rule premises", ErrorType.ERROR); addError(me); } if (((TripleElement)gpe).getObject() instanceof VariableNode && !variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, ((TripleElement)gpe).getObject()) && !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, ((TripleElement)gpe).getObject())) { ModelError me = new ModelError("Object of conclusion triple '" + gpe.toString() + "' is not bound in rule premises", ErrorType.ERROR); if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(me); } } } return errors; } @SuppressWarnings("unused") private Map<String, NamedNode> getTypedVars(com.ge.research.sadl.model.gp.Rule rule) { Map<String, NamedNode> results = getTypedVars(rule.getGivens()); Map<String, NamedNode> moreResults = getTypedVars(rule.getIfs()); if (moreResults != null) { if (results == null) { results = moreResults; } else { results.putAll(moreResults); } } moreResults = getTypedVars(rule.getThens()); if (moreResults != null) { if (results == null) { results = moreResults; } else { results.putAll(moreResults); } } return results; } private Map<String, NamedNode> getTypedVars(List<GraphPatternElement> gpes) { Map<String, NamedNode> results = null; for (int i = 0; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); if (gpe instanceof TripleElement && (((TripleElement)gpe).getModifierType() == null || ((TripleElement)gpe).getModifierType().equals(TripleModifierType.None) || ((TripleElement)gpe).getModifierType().equals(TripleModifierType.Not)) && ((TripleElement)gpe).getSubject() instanceof VariableNode && ((TripleElement)gpe).getPredicate() instanceof RDFTypeNode && ((TripleElement)gpe).getObject() instanceof NamedNode) { if (results == null) { results = new HashMap<String, NamedNode>(); } String varName = ((VariableNode)((TripleElement)gpe).getSubject()).getName(); NamedNode varType = (NamedNode) ((TripleElement)gpe).getObject(); if (results.containsKey(varName)) { NamedNode nn = results.get(varName); if (!nn.equals(varType) && !(nn instanceof VariableNode || varType instanceof VariableNode)) { addError(new ModelError("Variable '" + varName + "' is typed more than once in the rule.", ErrorType.WARNING)); } } results.put(varName, varType); } else if (gpe instanceof Junction) { Object lobj = ((Junction)gpe).getLhs(); Object robj = ((Junction)gpe).getRhs(); if (lobj instanceof GraphPatternElement || robj instanceof GraphPatternElement) { List<GraphPatternElement> junctgpes = new ArrayList<GraphPatternElement>(); if (lobj instanceof GraphPatternElement) { junctgpes.add((GraphPatternElement) lobj); } if (robj instanceof GraphPatternElement) { junctgpes.add((GraphPatternElement) robj); } if (results == null) { results = getTypedVars(junctgpes); } else { Map<String, NamedNode> moreresults = getTypedVars(junctgpes); if (moreresults != null) { results.putAll(moreresults); } } } } } return results; } /** * This method checks the list of GraphPatternElements to see if the specified variable is bound in these elements * * @param gpes - list of GraphPatternElements to check * @param startingIndex - where to start in the list * @param gp - the element in which this variable appears * @param boundIfEqual - use the current element for test? * @param matchMustBeAfter - must the binding be after the current element * @param v - the variable Node being checked * @return - true if the variable is bound else false */ public boolean variableIsBoundInOtherElement(List<GraphPatternElement> gpes, int startingIndex, GraphPatternElement gp, boolean boundIfEqual, boolean matchMustBeAfter, Node v) { boolean reachedSame = false; for (int i = startingIndex; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); while (gpe != null) { boolean same = gp == null ? false : gp.equals(gpe); if (same) { reachedSame = true; } boolean okToTest = false; if (matchMustBeAfter && reachedSame && !same) { okToTest = true; } if (!matchMustBeAfter && (!same || (same && boundIfEqual))) { okToTest = true; } if (okToTest && variableIsBound(gpe, v)) { return true; } gpe = gpe.getNext(); } } return false; } private boolean variableIsBound(GraphPatternElement gpe, Node v) { if (gpe instanceof TripleElement) { if ((((TripleElement)gpe).getSubject() != null &&((TripleElement)gpe).getSubject().equals(v)) || (((TripleElement)gpe).getObject() != null && ((TripleElement)gpe).getObject().equals(v))) { return true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); // TODO built-ins can actually have more than the last argument as output, but we can only tell this // if we have special knowledge of the builtin. Current SADL grammar doesn't allow this to occur. if (args != null && args.get(args.size() - 1) != null && args.get(args.size() - 1).equals(v)) { return true; } } else if (gpe instanceof Junction) { Object lhsobj = ((Junction)gpe).getLhs(); if (lhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)lhsobj, v)) { return true; } else if (lhsobj instanceof VariableNode && ((VariableNode)lhsobj).equals(v)) { return true; } Object rhsobj = ((Junction)gpe).getRhs(); if (rhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)rhsobj, v)) { return true; } else if (rhsobj instanceof VariableNode && ((VariableNode)rhsobj).equals(v)) { return true; } } return false; } }
com.ge.research.sadl.jena-wrapper-for-sadl/src/main/java/com/ge/research/sadl/jena/translator/JenaTranslatorPlugin.java
/************************************************************************ * Copyright \u00a9 2007-2010 - General Electric Company, All Rights Reserved * * Project: SADL * * Description: The Semantic Application Design Language (SADL) is a * language for building semantic models and expressing rules that * capture additional domain knowledge. The SADL-IDE (integrated * development environment) is a set of Eclipse plug-ins that * support the editing and testing of semantic models using the * SADL language. * * This software is distributed "AS-IS" without ANY WARRANTIES * and licensed under the Eclipse Public License - v 1.0 * which is available at http://www.eclipse.org/org/documents/epl-v10.php * ***********************************************************************/ /*********************************************************************** * $Last revised by: crapo $ * $Revision: 1.10 $ Last modified on $Date: 2015/09/22 15:00:57 $ ***********************************************************************/ package com.ge.research.sadl.jena.translator; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ServiceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ge.research.sadl.model.ModelError; import com.ge.research.sadl.model.gp.BuiltinElement; import com.ge.research.sadl.model.gp.BuiltinElement.BuiltinType; import com.ge.research.sadl.model.gp.GraphPatternElement; import com.ge.research.sadl.model.gp.Junction; import com.ge.research.sadl.model.gp.Junction.JunctionType; import com.ge.research.sadl.model.gp.KnownNode; import com.ge.research.sadl.model.gp.Literal; import com.ge.research.sadl.model.gp.NamedNode; import com.ge.research.sadl.model.gp.NamedNode.NodeType; import com.ge.research.sadl.model.gp.NegatedExistentialQuantifier; import com.ge.research.sadl.model.gp.Node; import com.ge.research.sadl.model.gp.ProxyNode; import com.ge.research.sadl.model.gp.Query; import com.ge.research.sadl.model.gp.Query.Order; import com.ge.research.sadl.model.gp.Query.OrderingPair; import com.ge.research.sadl.model.gp.RDFTypeNode; import com.ge.research.sadl.model.gp.Rule; import com.ge.research.sadl.model.gp.TripleElement; import com.ge.research.sadl.model.gp.TripleElement.TripleModifierType; import com.ge.research.sadl.model.gp.VariableNode; import com.ge.research.sadl.reasoner.ConfigurationException; import com.ge.research.sadl.reasoner.ConfigurationItem; import com.ge.research.sadl.reasoner.ConfigurationItem.ConfigurationType; import com.ge.research.sadl.reasoner.ConfigurationOption; import com.ge.research.sadl.reasoner.FunctionNotSupportedException; import com.ge.research.sadl.reasoner.IConfigurationManager; import com.ge.research.sadl.reasoner.IConfigurationManagerForEditing; import com.ge.research.sadl.reasoner.ITranslator; import com.ge.research.sadl.reasoner.InvalidNameException; import com.ge.research.sadl.reasoner.ModelError.ErrorType; import com.ge.research.sadl.reasoner.TranslationException; import com.ge.research.sadl.utils.SadlUtils; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.ontology.OntProperty; import com.hp.hpl.jena.ontology.OntResource; import com.hp.hpl.jena.ontology.Ontology; import com.hp.hpl.jena.rdf.model.Resource; import com.hp.hpl.jena.reasoner.rulesys.Builtin; import com.hp.hpl.jena.reasoner.rulesys.BuiltinRegistry; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.RDF; import com.hp.hpl.jena.vocabulary.RDFS; public class JenaTranslatorPlugin implements ITranslator { protected static final Logger logger = LoggerFactory.getLogger(JenaTranslatorPlugin.class); private static final String TranslatorCategory = "Basic_Jena_Translator"; private static final String ReasonerFamily="Jena-Based"; protected IConfigurationManager configurationMgr; public enum TranslationTarget {RULE_TRIPLE, RULE_BUILTIN, QUERY_TRIPLE, QUERY_FILTER} private enum SpecialBuiltin {NOVALUE, NOVALUESPECIFIC, NOTONLY, ONLY, ISKNOWN} private enum RulePart {PREMISE, CONCLUSION, NOT_A_RULE} private Map<String, String> prefixes = new HashMap<String, String>(); private boolean saveRuleFileAfterModelSave = true; // unless set to false because an explicit list of rules are private Rule ruleInTranslation = null; private Query queryInTranslation = null; private int nextQueryVarNum = 1; private OntModel theModel; private String modelName; protected List<ModelError> errors = null; // provided, we need to look for rule files in // imported models and if there are any create a rule file // for this model so that the imported rule files will be loaded public List<ModelError> translateAndSaveModel(OntModel model, String translationFolder, String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException { // Jena models have been saved to the OwlModels folder by the ModelManager prior to calling the translator. For Jena // reasoners, no additional saving of OWL models is need so we can continue on to rule translation and saving. if (errors != null) { errors.clear(); } if (model == null) { return addError("Cannot save model in file '" + saveFilename + "' as it has no model."); } if (modelName == null) { return addError("Cannot save model in file '" + saveFilename + "' as it has no name."); } if (saveRuleFileAfterModelSave) { String ruleFilename = createDerivedFilename(saveFilename, "rules"); String fullyQualifiedRulesFilename = translationFolder + File.separator + ruleFilename; translateAndSaveRules(model, null, modelName, fullyQualifiedRulesFilename); } saveRuleFileAfterModelSave = false; // reset return (errors != null && errors.size() > 0) ? errors : null; } public List<ModelError> translateAndSaveModel(OntModel model, List<Rule> ruleList, String translationFolder, String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException { if (errors != null) { errors.clear(); } saveRuleFileAfterModelSave = false; // a Jena model simply writes out the OWL file translateAndSaveModel(model, translationFolder, modelName, orderedImports, saveFilename); String ruleFilename = createDerivedFilename(saveFilename, "rules"); String fullyQualifiedRulesFilename = translationFolder + File.separator + ruleFilename; if (ruleList != null && ruleList.size() > 0) { translateAndSaveRules(model, ruleList, modelName, fullyQualifiedRulesFilename); } else { // there isn't a rules file but make sure there isn't an old one around that needs to be deleted File oldRuleFile = new File(fullyQualifiedRulesFilename); if (oldRuleFile.exists() && oldRuleFile.isFile()) { try { oldRuleFile.delete(); } catch (Exception e) { addError("Failed to delete old rules file '" + fullyQualifiedRulesFilename + "'."); logger.error("Failed to delete old rule file '" + fullyQualifiedRulesFilename + "': " + e.getLocalizedMessage()); } } } return (errors != null && errors.size() > 0) ? errors : null; } public String translateRule(OntModel model, Rule rule) throws TranslationException { setRuleInTranslation(rule); boolean translateToBackwardRule = false; StringBuilder sb = new StringBuilder(); // put annotations (if any) in the rule if (rule.getAnnotations() != null) { Iterator<String[]> annItr = rule.getAnnotations().iterator(); sb.append("#/**\n"); while (annItr.hasNext()) { String[] annNVP = annItr.next(); sb.append("# * @"); sb.append(annNVP[0]); sb.append("\t"); String val = annNVP[1]; String linesep =System.lineSeparator(); String[] valLines = val.split(linesep); for (int i = 0; i < valLines.length; i++) { if (i > 0) { sb.append("# * "); } sb.append(valLines[i]); sb.append("\n"); } } sb.append("# */\n"); } if (translateToBackwardRule) { sb.append("["); sb.append(rule.getRuleName()); sb.append(": "); List<GraphPatternElement> thens = rule.getThens(); String thenStr = graphPatternElementsToJenaRuleString(thens, RulePart.CONCLUSION); if (thenStr != null) { sb.append(thenStr); } sb.append(" <- "); List<GraphPatternElement> givens = rule.getGivens(); String givenStr = graphPatternElementsToJenaRuleString(givens, RulePart.PREMISE); if (givenStr != null) { sb.append(givenStr); } List<GraphPatternElement> ifs = rule.getIfs(); String ifStr = graphPatternElementsToJenaRuleString(ifs, RulePart.PREMISE); if (ifStr != null) { if (givenStr != null) { sb.append(", "); } sb.append(ifStr); } sb.append("]"); } else { sb.append("["); sb.append(rule.getRuleName()); sb.append(": "); List<GraphPatternElement> givens = rule.getGivens(); String givenStr = graphPatternElementsToJenaRuleString(givens, RulePart.PREMISE); if (givenStr != null) { sb.append(givenStr); } List<GraphPatternElement> ifs = rule.getIfs(); String ifStr = graphPatternElementsToJenaRuleString(ifs, RulePart.PREMISE); if (ifStr != null) { if (givenStr != null) { sb.append(", "); } sb.append(ifStr); } sb.append(" -> "); List<GraphPatternElement> thens = rule.getThens(); String thenStr = graphPatternElementsToJenaRuleString(thens, RulePart.CONCLUSION); if (thenStr != null) { sb.append(thenStr); } sb.append("]"); } setRuleInTranslation(null); return (sb.length() > 0 ? sb.toString() : null); } private String graphPatternElementsToJenaRuleString(List<GraphPatternElement> elements, RulePart rulePart) throws TranslationException { int cnt = 0; if (elements != null && elements.size() > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; elements != null && i < elements.size(); i++) { if (cnt > 0) sb.append(", "); SpecialBuiltin spb = processSpecialBuiltins(elements, i); // check for special handling required for some built-ins if (spb != null) { // get the triple in question TripleElement trel = null; if (elements.get(i) instanceof TripleElement) { trel = (TripleElement)elements.get(i); } else { logger.error("Unhandled graph pattern element detected as special builtin: " + elements.get(i).toString()); } // translate based on type of spb if (spb.equals(SpecialBuiltin.NOVALUE)) { sb.append(createNoValue(trel, TranslationTarget.RULE_BUILTIN)); } else if (spb.equals(SpecialBuiltin.ISKNOWN)) { sb.append(graphPatternElementToJenaRuleString(trel, rulePart)); sb.append(", "); sb.append("bound(" + nodeToString(trel.getObject(), TranslationTarget.RULE_BUILTIN) + ")"); } else { if (spb.equals(SpecialBuiltin.NOVALUESPECIFIC)) { sb.append(createNoValueSpecific(trel, TranslationTarget.RULE_BUILTIN)); } else if (spb.equals(SpecialBuiltin.NOTONLY)) { sb.append(createNotOnly(trel, TranslationTarget.RULE_BUILTIN)); } else if (spb.equals(SpecialBuiltin.ONLY)) { sb.append(createOnly((TripleElement)elements.get(i), TranslationTarget.RULE_BUILTIN)); } else { logger.error("Unhandled special builtin: " + elements.toString()); } } } else { sb.append(graphPatternElementToJenaRuleString(elements.get(i), rulePart)); } cnt++; } return sb.toString(); } return null; } /** * Look for special built-ins and if found process them, modifying the element list as needed. * @param elements * @param index * @return */ private SpecialBuiltin processSpecialBuiltins(List<GraphPatternElement> elements, int index) { if (elements.get(index) instanceof TripleElement) { if (!((TripleElement)elements.get(index)).getModifierType().equals(TripleModifierType.None)) { TripleElement trel = (TripleElement)elements.get(index); if (trel.getModifierType().equals(TripleModifierType.Not)) { if (trel.getObject() instanceof KnownNode) { return SpecialBuiltin.NOVALUE; } else { return SpecialBuiltin.NOVALUESPECIFIC; } } else if (trel.getModifierType().equals(TripleModifierType.NotOnly)) { return SpecialBuiltin.NOTONLY; } else if (trel.getModifierType().equals(TripleModifierType.Only)) { return SpecialBuiltin.ONLY; } } else if (elements.size() > (index + 1) && elements.get(index + 1) instanceof BuiltinElement) { // these special builtins will be of the form: // x predicate y, op(y,z) // or in other words, the first argument of the operation will be the object of the triple // (is that restrictive enough??) BuiltinElement be = (BuiltinElement) elements.get(index + 1); BuiltinType bt = be.getFuncType(); List<Node> args = be.getArguments(); Node biarg1 = (args.size() > 0) ? args.get(0) : null; // builtin 0th argument node Node trobj = ((TripleElement)elements.get(index)).getObject(); // triple object node if (biarg1 != null && trobj != null && biarg1 instanceof NamedNode && trobj instanceof NamedNode && ((NamedNode)biarg1).getName().equals(((NamedNode)trobj).getName())) { if (bt.equals(BuiltinType.NotEqual) && args.size() == 2) { Node arg2 = args.get(1); if (arg2 instanceof KnownNode) { // this case: (x pred y), !=(y, known) // just drop the i+1 builtin elements.remove(index + 1); return SpecialBuiltin.NOVALUE; } else { // this case: (x pred y), !=(y, z) // move the z to the object of the triple and drop the i+1 builtin if (args.size() > 1) { Node biarg2 = args.get(1); Node trsubj = ((TripleElement)elements.get(index)).getSubject(); if (biarg2 instanceof NamedNode && !(biarg2 instanceof VariableNode) && trsubj instanceof NamedNode && !(((NamedNode)biarg2).getName().equals(((NamedNode)trsubj).getName()))) { ((TripleElement)elements.get(index)).setObject(args.get(1)); elements.remove(index + 1); return SpecialBuiltin.NOVALUESPECIFIC; } } } } else if (bt.equals(BuiltinType.NotOnly)) { ((TripleElement)elements.get(index)).setObject(args.get(1)); elements.remove(index + 1); return SpecialBuiltin.NOTONLY; } else if (bt.equals(BuiltinType.Only)) { ((TripleElement)elements.get(index)).setObject(args.get(1)); elements.remove(index + 1); return SpecialBuiltin.ONLY; } } } else if (((TripleElement)elements.get(index)).getObject() instanceof KnownNode) { Node var = new VariableNode("v" + System.currentTimeMillis()); ((TripleElement)elements.get(index)).setObject(var); return SpecialBuiltin.ISKNOWN; } } return null; } private String createNoValue(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); return "noValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ")"; } private Object createNoValueSpecific(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); Node arg3 = trel.getObject(); return "noValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")"; } private Object createOnly(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); Node arg3 = trel.getObject(); return "noValuesOtherThan(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")"; } private Object createNotOnly(TripleElement trel, TranslationTarget target) throws TranslationException { Node arg1 = trel.getSubject(); Node arg2 = trel.getPredicate(); Node arg3 = trel.getObject(); return "notOnlyValue(" + nodeToString(arg1, target) + ", " + nodeToString(arg2, target) + ", " + nodeToString(arg3, target) + ")"; } public String translateQuery(OntModel model, Query query) throws TranslationException, InvalidNameException { boolean isEval = false; setTheModel(model); setModelName(modelName); if (query == null) { throw new TranslationException("Invalid query: query is null!"); } if (query.getPatterns() != null) { GraphPatternElement gpe1 = query.getPatterns().get(0); if (gpe1 instanceof Junction) { Object gperhs = ((Junction)gpe1).getRhs(); if (gperhs instanceof BuiltinElement && ((BuiltinElement)gperhs).getFuncName().equalsIgnoreCase("eval")) { isEval = true; Object gpelhs = ((Junction)gpe1).getLhs(); if (gpelhs instanceof GraphPatternElement) { query.getPatterns().set(0, (GraphPatternElement) gpelhs); query.setToBeEvaluated(true); } } } } if (query.getSparqlQueryString() != null) { return prepareQuery(model, query.getSparqlQueryString()); } if (query.getKeyword() == null) { if (query.getVariables() == null) { query.setKeyword("ask"); } else { query.setKeyword("select"); } } if (!query.getKeyword().equals("ask") && query.getVariables() == null) { throw new TranslationException("Invalid query (" + query.toString() + "): must be a valid structure with specified variable(s)."); } setQueryInTranslation(query); StringBuilder sbmain = new StringBuilder(); StringBuilder sbfilter = new StringBuilder(); sbmain.append(query.getKeyword()); if (query.isDistinct()) { sbmain.append("distinct "); } List<String> vars = query.getVariables(); List<GraphPatternElement> elements = query.getPatterns(); for (int i = 0; vars != null && i < vars.size(); i++) { if (i > 0) sbmain.append(" "); sbmain.append("?" + vars.get(i)); } sbmain.append(" where {"); int tripleCtr = 0; int builtinCtr = 0; for (int i = 0; elements != null && i < elements.size(); i++) { GraphPatternElement gpe = elements.get(i); // need to handle or, and if (gpe instanceof Junction) { if (tripleCtr++ > 0) sbmain.append(" . "); String junctionStr = junctionToQueryString((Junction)gpe, sbfilter); sbmain.append(junctionStr); } else if (gpe instanceof TripleElement) { if (tripleCtr++ > 0) sbmain.append(" . "); String jenaStr = graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE); sbmain.append(jenaStr); } else if (gpe instanceof BuiltinElement) { // if (builtinCtr++ > 0) { // sbfilter.append(" && "); // } // else { // sbfilter.append("FILTER ("); // } // sbfilter.append(graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_FILTER)); // the filter string will be added in the method graphPatternElementToJenaQueryString(gpe, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); } } if (sbfilter.length() > 0) { sbfilter.insert(0, "FILTER ("); sbfilter.append(")"); if (!sbmain.toString().trim().endsWith(".")) { sbmain.append(" . "); } sbmain.append(sbfilter.toString()); } sbmain.append("}"); if (query.getOrderBy() != null) { List<OrderingPair> ops = query.getOrderBy(); if (ops.size() > 0) { sbmain.append(" order by"); for (int i = 0; i < ops.size(); i++) { sbmain.append(" "); OrderingPair op = ops.get(i); boolean explicitOrder = false; if (op.getOrder() != null && op.getOrder().equals(Order.DESC)) { sbmain.append("DESC("); explicitOrder = true; } sbmain.append("?"); sbmain.append(op.getVariable()); if (explicitOrder) { sbmain.append(")"); } } } } return prepareQuery(model, sbmain.toString()); } /** * Convert a junction to a query string. Filter stuff goes to the sbfilter StringBuilder, triple stuff gets returned. * * @param gpe * @param sbfilter * @return * @throws TranslationException */ private String junctionToQueryString(Junction gpe, StringBuilder sbfilter) throws TranslationException { // We have a junction, could be one of // 1. triple junction filter, e.g., ... x prop y and y < 3 // 2. filter junction triple, e.g., ... y < 3 and x prop z // 3. filter junction filter, e.g., ... x > 0 and x < 3 // 4. triple junction triple, e.g., ... x prop1 y and y prop2 z JunctionType jtype = ((Junction)gpe).getJunctionType(); boolean lhsFilter = false; boolean rhsFilter = false; Object lhsobj = ((Junction)gpe).getLhs(); Object rhsobj = ((Junction)gpe).getRhs(); if (lhsobj instanceof BuiltinElement) { lhsFilter = true; } if (rhsobj instanceof BuiltinElement) { rhsFilter = true; } StringBuilder sbjunct = new StringBuilder(); String connector = null; boolean wrapInCurleyBrackets = false; if (lhsFilter || rhsFilter) { if (lhsFilter && rhsFilter) { // this is a junction within the filter, case 3 connector = junctionToFilterString(jtype); sbfilter.append("("); graphPatternElementToJenaQueryString((GraphPatternElement)lhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); sbfilter.append(connector); graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); sbfilter.append(")"); } else { // Note: junctions between a triple and a built-in filter are ignored, cases 1 & 2 if (lhsFilter) { graphPatternElementToJenaQueryString((GraphPatternElement)lhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); if (rhsobj instanceof BuiltinElement) { sbfilter.append(junctionToFilterString(jtype)); } sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); } else { // rhsFilter sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) lhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); if (lhsobj instanceof BuiltinElement) { sbfilter.append(junctionToFilterString(jtype)); } graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_FILTER, RulePart.NOT_A_RULE); } } } else { // this is a junction between triple patterns, case 4 if (jtype.equals(JunctionType.Conj)) { // (and) connector = " . "; } else { // must be Disj (or) wrapInCurleyBrackets = true; connector = "} UNION {"; } if (wrapInCurleyBrackets) { sbjunct.append("{"); } sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) lhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); sbjunct.append(connector); sbjunct.append(graphPatternElementToJenaQueryString((GraphPatternElement) rhsobj, sbfilter, TranslationTarget.QUERY_TRIPLE, RulePart.NOT_A_RULE)); if (wrapInCurleyBrackets) { sbjunct.append("}"); } } return sbjunct.toString(); } private String junctionToFilterString(JunctionType jtype) { if (jtype.equals(JunctionType.Conj)) { // and return " && "; } else { // must be Disj (or) return " || "; } } private String builtinToFilterFunctionString(BuiltinElement gpe) throws TranslationException { List<Node> args = gpe.getArguments(); if (args.size() < 2) { throw new TranslationException("Filter '" + gpe.getFuncName() + "' must take two arguments."); } if (gpe.getFuncType().equals(BuiltinType.Equal)) { gpe.setFuncName("="); // there are several possibilities here that all map to "=" in SPARQL } if (gpe.getFuncType().equals(BuiltinType.Not)) { gpe.setFuncName("!="); } switch(gpe.getFuncType()) { case Equal: case GT: case GTE: case LT: case LTE: case NotEqual: case Not: String filter = nodeToString(args.get(0), TranslationTarget.QUERY_FILTER) + " " + gpe.getFuncName() + " " + nodeToString(args.get(1), TranslationTarget.QUERY_FILTER); return filter; // nodeToString(args.get(0), TranslationTarget.QUERY_FILTER) + " " + gpe.getFuncName() + " " + nodeToString(args.get(1), TranslationTarget.QUERY_FILTER); default: throw new TranslationException("Unhandled filter type: " + gpe.getFuncName()); } } private boolean translateAndSaveRules(OntModel model, List<Rule> ruleList, String modelName, String filename) throws TranslationException, IOException { if (ruleList == null || ruleList.size() < 1) { throw new TranslationException("No rules provided to rule translation."); } // Open file and output header and imports File ruleFile = new File(filename); if (ruleFile.exists()) { boolean success = ruleFile.delete(); if (!success) { addError("Failed to delete old rules file '" + filename + "'."); logger.error("Failed to delete old rule file '" + filename + "'."); if (ruleList == null || ruleList.size() == 0) { setTheModel(null); setModelName(null); return false; } // else don't return--maybe we can open it for output anyway } } String jenaRules = translateAndSaveRules(model, ruleList, modelName) ; SadlUtils su = new SadlUtils(); su.stringToFile(ruleFile, jenaRules, true); return (errors== null || errors.size() == 0) ? true : false; } /** * Save the * @param model * @param ruleList * @param modelName * @return * @throws TranslationException */ public String translateAndSaveRules(OntModel model, List<Rule> ruleList, String modelName) throws TranslationException { if (ruleList == null) { return null; } setTheModel(model); setModelName(modelName); StringBuilder contents = new StringBuilder(); contents.append("# Jena Rules file generated by SADL IDE -- Do not edit! Edit the SADL model and regenerate.\n"); contents.append("# Created from SADL model '" + modelName + "'\n\n"); StringBuilder ruleContent = new StringBuilder(); for (int i = 0; i < ruleList.size(); i++) { Rule rule = ruleList.get(i); ruleContent.append(translateRule(model, rule)); ruleContent.append("\n"); } // now add prefix info to rule file output Iterator<String> itr2 = prefixes.keySet().iterator(); while (itr2.hasNext()) { String prefix = itr2.next(); String ns = prefixes.get(prefix); contents.append("@prefix "); contents.append(prefix); contents.append(": <"); contents.append(ns); contents.append(">\n"); } contents.append("\n"); // Because rule files are loaded for each sub-model, there is no need to put in includes if (ruleContent.length() > 0) { contents.append(ruleContent); } setTheModel(null); setModelName(null); return contents.toString(); } public String modelNsToRuleNs(String modelNs) { return modelNs + ".rules"; } /** * Convert GraphPatternElement to String in the context of a Rule * * @param gpe * @return * @throws TranslationException */ private String graphPatternElementToJenaRuleString(GraphPatternElement gpe, RulePart rulePart) throws TranslationException { StringBuilder sb = null; if (gpe instanceof TripleElement) { if (!((TripleElement)gpe).getModifierType().equals(TripleModifierType.None)) { sb = new StringBuilder(); TripleModifierType type = ((TripleElement)gpe).getModifierType(); if (type.equals(TripleModifierType.Not)) { sb.append("noValue("); } else if (type.equals(TripleModifierType.Only)) { sb.append("notOnlyValue("); } else { sb.append("noValueOtherThan("); } sb.append(nodeToString(((TripleElement)gpe).getSubject(),TranslationTarget.RULE_BUILTIN)); sb.append(", "); Node pn = ((TripleElement)gpe).getPredicate(); checkPredicateSpecial(pn); sb.append(nodeToString(pn, TranslationTarget.RULE_BUILTIN)); if (!(((TripleElement)gpe).getObject() instanceof KnownNode)) { sb.append(", "); sb.append(nodeToString(((TripleElement)gpe).getObject(), TranslationTarget.RULE_BUILTIN)); } sb.append(")"); } else { sb = tripleElementToRawJenaString((TripleElement) gpe, TranslationTarget.RULE_TRIPLE, rulePart, null); // 2/16/2011 false); } } else if (gpe instanceof BuiltinElement) { sb = new StringBuilder(); List<Node> args = ((BuiltinElement)gpe).getArguments(); sb.append(builtinTypeToString((BuiltinElement)gpe)); sb.append("("); for (int i = 0; args != null && i < args.size(); i++) { Node arg = args.get(i); if (i > 0) sb.append(", "); if (arg instanceof ProxyNode) { Object pfor = ((ProxyNode)arg).getProxyFor(); if (pfor instanceof GraphPatternElement) { sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) pfor, rulePart)); } else { throw new TranslationException("Non-graph element proxy-for in ProxyNode '" + arg.toFullyQualifiedString() + "'"); } } else { sb.append(nodeToString(arg, TranslationTarget.RULE_BUILTIN)); } } sb.append(")"); } else if (gpe instanceof Junction) { sb = new StringBuilder(); JunctionType jtype = ((Junction)gpe).getJunctionType(); if (jtype.equals(JunctionType.Conj)) { Object lhs = ((Junction)gpe).getLhs(); if (lhs instanceof List<?>) { sb.append(graphPatternElementsToJenaRuleString((List<GraphPatternElement>)lhs, rulePart)); } else if (lhs instanceof GraphPatternElement) { sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) lhs, rulePart)); } else { throw new TranslationException("Unexpected junction lhs type: " + lhs.getClass()); } Object rhs = ((Junction)gpe).getRhs(); if (rhs instanceof List<?>) { sb.append(", "); sb.append(graphPatternElementsToJenaRuleString((List<GraphPatternElement>)rhs, rulePart)); } else if (rhs instanceof GraphPatternElement) { sb.append(", "); sb.append(graphPatternElementToJenaRuleString((GraphPatternElement) rhs, rulePart)); } else { throw new TranslationException("Unexpected junction rhs type: " + rhs.getClass()); } } else { System.err.println("Encountered unhandled OR in rule '" + ruleInTranslation.getRuleName() + "'"); // throw new TranslationException("Jena rules do not currently support disjunction (OR)."); } } else if (gpe instanceof NegatedExistentialQuantifier) { throw new TranslationException("Existential quantification with negation is not supported by the Jena reasoner."); } else { throw new TranslationException("GraphPatternElement '" + gpe.toString() + "' cannot be translated to Jena rule."); } return sb.toString(); } private String graphPatternElementToJenaQueryString(GraphPatternElement gpe, StringBuilder sbfilter, TranslationTarget target, RulePart rulePart) throws TranslationException { if (gpe instanceof TripleElement) { StringBuilder sb = tripleElementToRawJenaString((TripleElement) gpe, target, rulePart, sbfilter); return sb.toString(); } else if (gpe instanceof Junction) { String junctStr = junctionToQueryString((Junction)gpe, sbfilter); return junctStr; } else if (gpe instanceof BuiltinElement) { String bistr = builtinToFilterFunctionString((BuiltinElement)gpe); if (sbfilter.length() > 0) { String tmp = sbfilter.toString().trim(); if (!tmp.endsWith("(") && !tmp.endsWith("&&") && !tmp.endsWith("||")) { sbfilter.append(" && "); } } sbfilter.append(bistr); return null; } else { throw new TranslationException("GraphPatternElement '" + gpe.toString() + "' not yet handled in Jena query."); } } /** * Method to convert a TripleElement to a Jena String without delimiters * * @param gpe * @param sbfilter * @return * @throws TranslationException */ private StringBuilder tripleElementToRawJenaString(TripleElement gpe, TranslationTarget target, RulePart rulePart, StringBuilder sbfilter) throws TranslationException { StringBuilder sb = new StringBuilder(); Node subj = gpe.getSubject(); Node pred = gpe.getPredicate(); checkPredicateSpecial(pred); Node obj = gpe.getObject(); boolean moveObjectToEqualityTest = false; if (target.equals(TranslationTarget.RULE_TRIPLE)) { sb.insert(0, '('); } sb.append(nodeToString(subj, target)); sb.append(" "); sb.append(nodeToString(pred, target)); sb.append(" "); String newVar = null; if (rulePart.equals(RulePart.PREMISE) && target.equals(TranslationTarget.RULE_TRIPLE) && tripleHasDecimalObject(gpe)) { // this would be a triple match on a float or double value, which is not reliable // move the object to a separate equality test moveObjectToEqualityTest = true; newVar = getNewVariableForRule(); sb.append("?"); sb.append(newVar); } else { if (rulePart.equals(RulePart.NOT_A_RULE)) { if (obj instanceof KnownNode) { newVar = "?" + getNewVariableForQuery(); if (gpe.getModifierType().equals(TripleModifierType.Not)) { sb.append(newVar); sb.insert(0, "OPTIONAL {"); sb.append("}"); if (sbfilter != null) { if (sbfilter.length() > 0) { sbfilter.append(" && "); } sbfilter.append("!bound("); sbfilter.append(newVar); sbfilter.append(")"); } } else { sb.append(newVar); } } else if (tripleHasDecimalObject(gpe)) { newVar = "?" + getNewVariableForQuery(); sb.append(newVar); if (sbfilter != null) { if (sbfilter.length() > 0) { sbfilter.append(" && "); } sbfilter.append(newVar); if (gpe.getModifierType().equals(TripleModifierType.Not)) { sbfilter.append(" != "); } else { sbfilter.append(" = "); } sbfilter.append(nodeToString(obj, TranslationTarget.RULE_BUILTIN)); } else { sb.append(newVar); } } else { sb.append(nodeToString(obj, target)); } } else { sb.append(nodeToString(obj, target)); } } if (target.equals(TranslationTarget.RULE_TRIPLE)) { sb.append(")"); } else { // this is a query if (gpe.getModifierType() != null && gpe.getModifierType().equals(TripleModifierType.Not)) { // this is negation--translate into a filter on !exits sb.insert(0, "!EXISTS { "); sb.append(" }"); sbfilter.append(sb); sb.setLength(0); } } if (moveObjectToEqualityTest) { // now add the equality test. (this is only for rules) sb.append(" equal(?"); sb.append(newVar); sb.append(", "); sb.append(nodeToString(obj, TranslationTarget.RULE_BUILTIN)); sb.append(")"); } return sb; } private String getNewVariableForRule() { int cntr = 1; Rule rule = getRuleInTranslation(); if (rule != null) { String rulestr = rule.toString(); String varName; do { varName = "v" + cntr++; } while (rulestr.indexOf(varName) > 0); return varName; } else { return "v1"; } } private String getNewVariableForQuery() { int cntr = nextQueryVarNum; Query query = getQueryInTranslation(); String querystr = query.toString(); String varName; do { varName = "v" + cntr++; } while (querystr.indexOf(varName) > 0); nextQueryVarNum = cntr; return varName; } private boolean tripleHasDecimalObject(TripleElement gpe) { Node pred = gpe.getPredicate(); Node obj = gpe.getObject(); if (!(obj instanceof NamedNode) && pred instanceof NamedNode && ((NamedNode)pred).getNamespace() != null) { OntProperty prop = getTheModel().getOntProperty(((NamedNode)pred).toFullyQualifiedString()); if (prop != null && prop.isDatatypeProperty()) { Resource rng = prop.getRange(); if (rng.toString().contains("double") || rng.toString().contains("float")) { return true; } } } if (obj instanceof Literal) { Object objval = ((Literal)obj).getValue(); if (objval instanceof Double || objval instanceof Float) { return true; } } return false; } private void checkPredicateSpecial(Node predNode) { if (predNode instanceof NamedNode) { if (((NamedNode)predNode).getNamespace() == null && ((NamedNode)predNode).getName() != null && ((NamedNode)predNode).getName().equals(RDFS.comment.getLocalName()) ) { ((NamedNode)predNode).setNamespace(RDFS.getURI()); } } } private Object builtinTypeToString(BuiltinElement bin) throws TranslationException { BuiltinType ftype = bin.getFuncType(); if (ftype.equals(BuiltinType.Divide)) { // return "quotient"; bin.setFuncName("quotient"); } else if (ftype.equals(BuiltinType.Equal)) { // return "equal"; bin.setFuncName("equal"); } else if (ftype.equals(BuiltinType.GT)) { // return "greaterThan"; bin.setFuncName("greaterThan"); } else if (ftype.equals(BuiltinType.GTE)) { // return "ge"; bin.setFuncName("ge"); } else if (ftype.equals(BuiltinType.LT)) { // return "lessThan"; bin.setFuncName("lessThan"); } else if (ftype.equals(BuiltinType.LTE)) { // return "le"; bin.setFuncName("le"); } else if (ftype.equals(BuiltinType.Minus)) { // return "difference"; bin.setFuncName("difference"); } else if (ftype.equals(BuiltinType.Modulus)) { // return "mod"; bin.setFuncName("mod"); } else if (ftype.equals(BuiltinType.Multiply)) { // return "product"; bin.setFuncName("product"); } else if (ftype.equals(BuiltinType.Negative)) { // return "negative"; bin.setFuncName("negative"); } else if (ftype.equals(BuiltinType.Not)) { // return "noValue"; bin.setFuncName("noValue"); } else if (ftype.equals(BuiltinType.NotEqual)) { // return "notEqual"; bin.setFuncName("notEqual"); } else if (ftype.equals(BuiltinType.NotOnly)) { // return "notOnlyValue"; bin.setFuncName("notOnlyValue"); } else if (ftype.equals(BuiltinType.Only)) { // return "noValuesOtherThan"; bin.setFuncName("noValuesOtherThan"); } else if (ftype.equals(BuiltinType.Plus)) { // return "sum"; bin.setFuncName("sum"); } else if (ftype.equals(BuiltinType.Power)) { // return "pow"; bin.setFuncName("pow"); } else if (ftype.equals(BuiltinType.Assign)) { // return "assign"; bin.setFuncName("assign"); } String builtinName = bin.getFuncName(); // Note: the order here allows any built-in which overrides the ones in Jena to be picked up preferentially // see if it is known to the ConfigurationManager or if we can find it in the services registry boolean status = findOrAddBuiltin(builtinName); if (!status) { // if not see if it is one already registered Builtin bltin = BuiltinRegistry.theRegistry.getImplementation(builtinName); if (bltin == null) { logger.error("Something went wrong finding/loading Builtin '" + builtinName + "'"); addError("Unable to resolve built-in '" + builtinName + "'"); } } return builtinName; } private boolean findOrAddBuiltin(String builtinName) { int cnt = 0; // is it known to the ConfigurationManager? String[] categories = new String[2]; try { categories[0] = configurationMgr.getReasoner().getReasonerFamily(); categories[1] = IConfigurationManager.BuiltinCategory; List<ConfigurationItem> knownBuiltins = configurationMgr.getConfiguration(categories, false); for (int i = 0; knownBuiltins != null && i < knownBuiltins.size(); i++) { ConfigurationItem item = knownBuiltins.get(i); Object itemName = item.getNamedValue("name"); if (itemName != null && itemName instanceof String && ((String)itemName).equals(builtinName)) { logger.debug("Built-in '" + builtinName + "' found in configuration."); return true; } } } catch (ConfigurationException e) { // this is ok--new ones won't be found // e.printStackTrace(); // logger.error("Unable to find Builtin '" + builtinName + "' in current configuration: " + e.getLocalizedMessage()); } // Use ServiceLoader to find an implementation of Builtin that has this name ServiceLoader<Builtin> serviceLoader = ServiceLoader.load(Builtin.class); if( serviceLoader != null ){ logger.debug("ServiceLoader is OK"); for( Iterator<Builtin> itr = serviceLoader.iterator(); itr.hasNext() ; ){ try { Builtin bltin = itr.next(); cnt++; if (bltin.getName().equals(builtinName)) { String clsname = bltin.getClass().getCanonicalName(); // TODO is there a reasonable check here? if (1 > 0) { if (configurationMgr instanceof IConfigurationManagerForEditing) { ConfigurationItem newItem = new ConfigurationItem(categories); newItem.addNameValuePair(newItem.new NameValuePair("name", builtinName, ConfigurationType.Bag)); newItem.addNameValuePair(newItem.new NameValuePair("class", clsname, ConfigurationType.Bag)); ((IConfigurationManagerForEditing) configurationMgr).addConfiguration(newItem); ((IConfigurationManagerForEditing) configurationMgr).saveConfiguration(); logger.info("Built-in '" + builtinName + "' found in service registry and added to configuration."); } } else { logger.info("Built-in '" + builtinName + "' found in service registry."); } BuiltinRegistry.theRegistry.register(builtinName, bltin); return true; } } catch (Throwable t) { t.printStackTrace(); logger.error(t.getLocalizedMessage()); } } } else { logger.debug("ServiceLoader is null"); } logger.debug("Failed to find Builtin with name '" + builtinName + "' after examining " + cnt + " registered Builtins."); return false; } private String nodeToString(Node node, TranslationTarget target) throws TranslationException { if (node instanceof NamedNode) { NodeType ntype = ((NamedNode)node).getNodeType(); if (ntype.equals(NodeType.VariableNode)) { // double-check this; if a concept was declared after reference in a rule or query // it may have been parsed as a variable but actually be a defined concept OntResource r = getTheModel().getOntResource(getModelName() + "#" + ((NamedNode)node).getName()); if (r == null) { return "?" + ((NamedNode)node).getName(); } // it appears that at time of parsing of the rule or query the named concept was not defined but // was subsequently. Warn user of this apparent error: concepts must be defined before they are // used in a rule or query. String msg = "The concept '" + ((NamedNode)node).getName() + "' "; if (ruleInTranslation != null) { msg += "in rule '" + ruleInTranslation.getRuleName() + "' "; } msg += " in model '" + getModelName() + "' is used before it is defined. Please define the concept before referencing it in a query or rule."; addError(msg); logger.error(msg); } if (node instanceof RDFTypeNode) { // registerPrefix("rdf", ""); I don't think these need an explicit prefix awc 11/23/2010 if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) { return "<rdf:type>"; } else { return "rdf:type"; } } else { String nts; if (((NamedNode)node).getNamespace() != null) { String prefix = ((NamedNode)node).getPrefix(); if (prefix != null) { registerPrefix(prefix, ((NamedNode)node).getNamespace()); } else { // this must be the default namespace ((NamedNode)node).setPrefix(""); } nts = ((NamedNode)node).getNamespace() + ((NamedNode)node).getName(); } else { nts = ((NamedNode)node).getName(); } if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) { return "<" + nts + ">"; } else { return nts; } } } else if (node instanceof Literal) { Object litObj = ((Literal)node).getValue(); return literalValueToString(litObj, target); } else if (node instanceof KnownNode) { return "?" + getNewVariableForRule(); } else if (node == null) { throw new TranslationException("Encountered null node in nodeToString; this indicates incorrect intermediate form and should not happen"); } else { throw new TranslationException("Nnode '" + node.toString() + "' cannot be translated to Jena format."); } } public static synchronized String literalValueToString(Object litObj, TranslationTarget target) { if (litObj instanceof String) { litObj = "\"" + litObj + "\""; } if (litObj instanceof String) { return (String)litObj; } else if (litObj instanceof Boolean) { if (target.equals(TranslationTarget.QUERY_TRIPLE) || target.equals(TranslationTarget.QUERY_FILTER)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#boolean>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#boolean"; } } else if (litObj instanceof Long) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#long>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#long"; } } else if (litObj instanceof Integer) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#int>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#int"; } } else if (litObj instanceof Double) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#double>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#double"; } } else if (litObj instanceof Float) { if (target.equals(TranslationTarget.QUERY_FILTER) || target.equals(TranslationTarget.RULE_BUILTIN)) { return litObj.toString().trim(); } else if (target.equals(TranslationTarget.QUERY_TRIPLE)) { return "'" + litObj.toString().trim() + "'^^<http://www.w3.org/2001/XMLSchema#float>"; } else { return "'" + litObj.toString().trim() + "'^^http://www.w3.org/2001/XMLSchema#float"; } } else { return litObj.toString(); } } private void registerPrefix(String prefix, String namespace) { if (prefix == null) { logger.error("Prefix is null in registerPrefix"); } if (!prefixes.containsKey(prefix)) { prefixes.put(prefix, namespace); } } protected String createDerivedFilename(String filename, String newext) { int lastDot = filename.lastIndexOf('.'); if (lastDot > 0) { return filename.substring(0, lastDot + 1) + newext; } return filename + "." + newext; } /** * Method to prepare a query by expanding the URIs of concepts to be complete URIs * * @param model * @param q * @return * @throws InvalidNameException */ public String prepareQuery(OntModel model, String q) throws InvalidNameException { int openBracket = q.indexOf('<'); if (openBracket > 0) { int closeBracket = q.indexOf('>', openBracket); if (closeBracket <= openBracket) { // this could be a comparison in a FILTER... return q; } String before = q.substring(0, openBracket + 1); String url = q.substring(openBracket + 1, closeBracket); String rest = q.substring(closeBracket); rest = prepareQuery(model, rest); if (url.indexOf('#') > 0) { return before + url + rest; } else if (url.indexOf(':') > 0) { url = expandPrefixedUrl(model, url); } else if (isValidLocalName(url)){ url = findNameNs(model, url); } return before + url + rest; } return q; } protected boolean isValidLocalName(String name) { if (name == null || name.indexOf(" ") >= 0 || name.indexOf("?") >= 0) { return false; } return true; } /** * This method takes an OntModel and a concept name and tries to find the concept in the model or * one of the models imported by the model. * * @param model -- the OntModel at the root of the search * @param name -- the concept name * @return -- the fully-qualified name of the concept as found in some model * * @throws InvalidNameException -- the concept was not found */ public static synchronized String findNameNs(OntModel model, String name) throws InvalidNameException { String uri = findConceptInSomeModel(model, name); if (uri != null) { return uri; } Iterator<String> impitr = model.listImportedOntologyURIs(true).iterator(); while (impitr.hasNext()) { String impuri = impitr.next(); if (!impuri.endsWith("#")) { impuri += "#"; } impuri = getUriInModel(model, impuri, name); if (impuri != null) { logger.debug("found concept with URI '" + impuri + "'"); return impuri; } } ExtendedIterator<Ontology> oitr = model.listOntologies(); while (oitr.hasNext()) { Ontology onto = oitr.next(); if (onto != null) { ExtendedIterator<OntResource> importsItr = onto.listImports(); while (importsItr.hasNext()) { OntResource or = importsItr.next(); String ns = or.getURI(); if (!ns.endsWith("#")) { ns = ns + "#"; } String muri = getUriInModel(model, or.getURI(), name); if (muri != null) { logger.debug("found concept with URI '" + muri + "'"); return muri; } } // try this ontology--maybe it wasn't in the map used by findConceptInSomeModel String muri = getUriInModel(model, onto.getURI() + "#", name); if (muri != null) { logger.debug("found concept with URI '" + muri + "'"); return muri; } } } if (logger.isDebugEnabled()) { logger.debug("Failed to find '" + name + "' in any model."); ByteArrayOutputStream sos = new ByteArrayOutputStream(); model.write(sos); logger.debug(sos.toString()); } throw new InvalidNameException("'" + name + "' not found in any model."); } private static synchronized String findConceptInSomeModel(OntModel model, String name) { Map<String, String> map = model.getNsPrefixMap(); Iterator<String> uriitr = map.values().iterator(); while (uriitr.hasNext()) { String ns = uriitr.next(); String uri = getUriInModel(model, ns, name); if (uri != null) { logger.debug("found concept with URI '" + uri + "'"); return uri; } } logger.debug("did not find concept with name '" + name + "'"); return null; } private static synchronized String getUriInModel(OntModel model, String ns, String name) { Resource r = model.getAnnotationProperty(ns + name); if (r != null) { return r.getURI(); } r = model.getDatatypeProperty(ns + name); if (r != null) { return r.getURI(); } r = model.getObjectProperty(ns + name); if (r != null) { return r.getURI(); } r = model.getOntClass(ns + name); if (r != null) { return r.getURI(); } r = model.getIndividual(ns + name); if (r != null) { return r.getURI(); } if (RDF.type.getURI().equals(ns + name)) { return RDF.type.getURI(); } return null; } protected String expandPrefixedUrl(OntModel model, String name) { String prefix = name.substring(0, name.indexOf(':')); String lname = name.substring(name.indexOf(':') + 1); String ns = model.getNsPrefixURI(prefix); if (ns != null) { name = ns + lname; } return name; } protected List<ModelError> addError(String msg) { if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(new ModelError(msg, ErrorType.ERROR)); return errors; } protected List<ModelError> addError(String msg, ErrorType errType) { if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(new ModelError(msg, errType)); return errors; } protected List<ModelError> addError(ModelError err) { if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(err); return errors; } public String getReasonerFamily() { return ReasonerFamily; } public String getConfigurationCategory() { return TranslatorCategory; } private void setRuleInTranslation(Rule ruleInTranslation) { this.ruleInTranslation = ruleInTranslation; } private Rule getRuleInTranslation() { return ruleInTranslation; } private void setTheModel(OntModel theModel) { this.theModel = theModel; } private OntModel getTheModel() { return theModel; } public Map<String, ConfigurationOption> getTranslatorConfigurationOptions() { // This translator doesn't have any configuration items return null; } public boolean configure(ConfigurationItem configItem) { // This translator doesn't have any configuration items return false; } public boolean configure(List<ConfigurationItem> configItems) { // This translator doesn't have any configuration items return false; } public List<ConfigurationItem> discoverOptimalConfiguration( String translationFolder, String modelName, IConfigurationManager configMgr, List<Query> queries) throws FunctionNotSupportedException, ConfigurationException, TranslationException { throw new FunctionNotSupportedException(this.getClass().getCanonicalName() + " does not support discovery of optimal configuration."); } private Query getQueryInTranslation() { return queryInTranslation; } private void setQueryInTranslation(Query queryInTranslation) { this.queryInTranslation = queryInTranslation; } public void setConfigurationManager(IConfigurationManager configMgr) throws ConfigurationException { // if ((configMgr instanceof IConfigurationManagerForEditing)) { // ((IConfigurationManagerForEditing) configMgr).setTranslatorClassName(this.getClass().getCanonicalName()); // } configurationMgr = configMgr; } private String getModelName() { return modelName; } private void setModelName(String modelName) { this.modelName = modelName; } @Override public List<ModelError> translateAndSaveModelWithOtherStructure( OntModel model, Object otherStructure, String translationFolder, String modelName, List<String> orderedImports, String saveFilename) throws TranslationException, IOException, URISyntaxException { throw new TranslationException("This translator (" + this.getClass().getCanonicalName() + ") does not translate other knowledge structures."); } public List<ModelError> validateRule(com.ge.research.sadl.model.gp.Rule rule) { List<ModelError> errors = null; // conclusion binding tests List<GraphPatternElement> thens = rule.getThens(); for (int i = 0; thens != null && i < thens.size(); i++) { GraphPatternElement gpe = thens.get(i); if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); if (args == null) { ModelError me = new ModelError("Built-in '" + ((BuiltinElement)gpe).getFuncName() + "' with no arguments not legal in rule conclusion", ErrorType.ERROR); if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(me); } else { for (int j = 0; j < args.size(); j++) { Node arg = args.get(j); if (arg instanceof VariableNode) { if (!variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, arg) && !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, arg)) { ModelError me = new ModelError("Conclusion built-in '" + ((BuiltinElement)gpe).getFuncName() + "', variable argument '" + arg.toString() + "' is not bound in rule premises", ErrorType.ERROR); if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(me); } } } } } else if (gpe instanceof TripleElement) { if (((TripleElement)gpe).getSubject() instanceof VariableNode && !variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, ((TripleElement)gpe).getSubject()) && !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, ((TripleElement)gpe).getSubject())) { ModelError me = new ModelError("Subject of conclusion triple '" + gpe.toString() + "' is not bound in rule premises", ErrorType.ERROR); addError(me); } if (((TripleElement)gpe).getObject() instanceof VariableNode && !variableIsBoundInOtherElement(rule.getGivens(), 0, gpe, false, false, ((TripleElement)gpe).getObject()) && !variableIsBoundInOtherElement(rule.getIfs(), 0, gpe, false, false, ((TripleElement)gpe).getObject())) { ModelError me = new ModelError("Object of conclusion triple '" + gpe.toString() + "' is not bound in rule premises", ErrorType.ERROR); if (errors == null) { errors = new ArrayList<ModelError>(); } errors.add(me); } } } return errors; } private Map<String, NamedNode> getTypedVars(com.ge.research.sadl.model.gp.Rule rule) { Map<String, NamedNode> results = getTypedVars(rule.getGivens()); Map<String, NamedNode> moreResults = getTypedVars(rule.getIfs()); if (moreResults != null) { if (results == null) { results = moreResults; } else { results.putAll(moreResults); } } moreResults = getTypedVars(rule.getThens()); if (moreResults != null) { if (results == null) { results = moreResults; } else { results.putAll(moreResults); } } return results; } private Map<String, NamedNode> getTypedVars(List<GraphPatternElement> gpes) { Map<String, NamedNode> results = null; for (int i = 0; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); if (gpe instanceof TripleElement && (((TripleElement)gpe).getModifierType() == null || ((TripleElement)gpe).getModifierType().equals(TripleModifierType.None) || ((TripleElement)gpe).getModifierType().equals(TripleModifierType.Not)) && ((TripleElement)gpe).getSubject() instanceof VariableNode && ((TripleElement)gpe).getPredicate() instanceof RDFTypeNode && ((TripleElement)gpe).getObject() instanceof NamedNode) { if (results == null) { results = new HashMap<String, NamedNode>(); } String varName = ((VariableNode)((TripleElement)gpe).getSubject()).getName(); NamedNode varType = (NamedNode) ((TripleElement)gpe).getObject(); if (results.containsKey(varName)) { NamedNode nn = results.get(varName); if (!nn.equals(varType) && !(nn instanceof VariableNode || varType instanceof VariableNode)) { addError(new ModelError("Variable '" + varName + "' is typed more than once in the rule.", ErrorType.WARNING)); } } results.put(varName, varType); } else if (gpe instanceof Junction) { Object lobj = ((Junction)gpe).getLhs(); Object robj = ((Junction)gpe).getRhs(); if (lobj instanceof GraphPatternElement || robj instanceof GraphPatternElement) { List<GraphPatternElement> junctgpes = new ArrayList<GraphPatternElement>(); if (lobj instanceof GraphPatternElement) { junctgpes.add((GraphPatternElement) lobj); } if (robj instanceof GraphPatternElement) { junctgpes.add((GraphPatternElement) robj); } if (results == null) { results = getTypedVars(junctgpes); } else { Map<String, NamedNode> moreresults = getTypedVars(junctgpes); if (moreresults != null) { results.putAll(moreresults); } } } } } return results; } /** * This method checks the list of GraphPatternElements to see if the specified variable is bound in these elements * * @param gpes - list of GraphPatternElements to check * @param startingIndex - where to start in the list * @param gp - the element in which this variable appears * @param boundIfEqual - use the current element for test? * @param matchMustBeAfter - must the binding be after the current element * @param v - the variable Node being checked * @return - true if the variable is bound else false */ public boolean variableIsBoundInOtherElement(List<GraphPatternElement> gpes, int startingIndex, GraphPatternElement gp, boolean boundIfEqual, boolean matchMustBeAfter, Node v) { boolean reachedSame = false; for (int i = startingIndex; gpes != null && i < gpes.size(); i++) { GraphPatternElement gpe = gpes.get(i); while (gpe != null) { boolean same = gp == null ? false : gp.equals(gpe); if (same) { reachedSame = true; } boolean okToTest = false; if (matchMustBeAfter && reachedSame && !same) { okToTest = true; } if (!matchMustBeAfter && (!same || (same && boundIfEqual))) { okToTest = true; } if (okToTest && variableIsBound(gpe, v)) { return true; } gpe = gpe.getNext(); } } return false; } private boolean variableIsBound(GraphPatternElement gpe, Node v) { if (gpe instanceof TripleElement) { if ((((TripleElement)gpe).getSubject() != null &&((TripleElement)gpe).getSubject().equals(v)) || (((TripleElement)gpe).getObject() != null && ((TripleElement)gpe).getObject().equals(v))) { return true; } } else if (gpe instanceof BuiltinElement) { List<Node> args = ((BuiltinElement)gpe).getArguments(); // TODO built-ins can actually have more than the last argument as output, but we can only tell this // if we have special knowledge of the builtin. Current SADL grammar doesn't allow this to occur. if (args != null && args.get(args.size() - 1) != null && args.get(args.size() - 1).equals(v)) { return true; } } else if (gpe instanceof Junction) { Object lhsobj = ((Junction)gpe).getLhs(); if (lhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)lhsobj, v)) { return true; } else if (lhsobj instanceof VariableNode && ((VariableNode)lhsobj).equals(v)) { return true; } Object rhsobj = ((Junction)gpe).getRhs(); if (rhsobj instanceof GraphPatternElement && variableIsBound((GraphPatternElement)rhsobj, v)) { return true; } else if (rhsobj instanceof VariableNode && ((VariableNode)rhsobj).equals(v)) { return true; } } return false; } }
Removed warnings Added SuppressWarnings attribute to remove warnings
com.ge.research.sadl.jena-wrapper-for-sadl/src/main/java/com/ge/research/sadl/jena/translator/JenaTranslatorPlugin.java
Removed warnings
<ide><path>om.ge.research.sadl.jena-wrapper-for-sadl/src/main/java/com/ge/research/sadl/jena/translator/JenaTranslatorPlugin.java <ide> } <ide> <ide> <add> @SuppressWarnings("unused") <ide> public String translateQuery(OntModel model, Query query) <ide> throws TranslationException, InvalidNameException { <ide> boolean isEval = false; <ide> * @return <ide> * @throws TranslationException <ide> */ <add> @SuppressWarnings("unchecked") <ide> private String graphPatternElementToJenaRuleString(GraphPatternElement gpe, RulePart rulePart) throws TranslationException { <ide> StringBuilder sb = null; <ide> if (gpe instanceof TripleElement) { <ide> return builtinName; <ide> } <ide> <add> @SuppressWarnings("unused") <ide> private boolean findOrAddBuiltin(String builtinName) { <ide> int cnt = 0; <ide> // is it known to the ConfigurationManager? <ide> return errors; <ide> } <ide> <add> @SuppressWarnings("unused") <ide> private Map<String, NamedNode> getTypedVars(com.ge.research.sadl.model.gp.Rule rule) { <ide> Map<String, NamedNode> results = getTypedVars(rule.getGivens()); <ide> Map<String, NamedNode> moreResults = getTypedVars(rule.getIfs());
JavaScript
mit
1e7217795062939cf524122b6e01f29cc7a108af
0
taingk/SmartPoker,taingk/SmartPoker,taingk/SmartPoker
var lock = false; function socket_listens_players(socket, table) { var player; // Current player. var curseat; // Current seat. var channel; // Channel involved. socket.on("is valid nickname", function(nickname, seat_idx) { curseat = get_seat(table.seats, seat_idx); channel = get_private_id(table.private_ids, seat_idx); if (!nickname || check_blanks(nickname) || nickname.length < 2 || nickname.length > 8) { console.log("Invalid nickname!"); socket.emit("is valid nickname info", "invalid"); } else if (table.nicknames.indexOf(nickname) != -1) { console.log("Nickname already taken!"); socket.emit("is valid nickname info", "already taken"); } else if (curseat.state != "available") socket.emit("is valid nickname info", "seat busy"); else { console.log(nickname + " is valid!"); socket.emit("is valid nickname info", "valid", nickname); table.nicknames.push(nickname); // Add the user nickname to the table nicknames array. if (table.players_nb < 6) ++table.players_nb; console.log("There are now " + table.players_nb + " seated at the table (imo of course)!"); player = new Player(seat_idx, nickname, +table.start_bankroll, -1, -1, -1, -1); curseat.state = "busy"; curseat.player = player; console.log("Seat" + seat_idx + " is now " + curseat.state); io.to(table.id).emit("new player", player); if (table.playing_seats.indexOf(seat_idx) != -1) return; if (table.game.moment == "waiting") table.playing_seats.push(seat_idx); for (var i = 0; i < table.playing_seats.length; i++) get_seat(table.seats, table.playing_seats[i]).state = "playing"; console.log(table.game.moment); if (table.players_nb >= 1 && table.game.moment == "waiting") { if (lock) return; else tryChrono(socket, table); } return; } }); socket.on("get seated players", function() { send_seats_infos(table); }); socket.on("get board", function() { if (table.game.board.length >= 3) io.to(table.id).emit("send flop", table.game.board[0], table.game.board[1], table.game.board[2]); if (table.game.board.length >= 4) io.to(table.id).emit("send turn", table.game.board[3]); if (table.game.board.length === 5) io.to(table.id).emit("send river", table.game.board[4]); }); socket.on("player decision", function(decision, channel_id, bet_amount, rc) { if (!decision || !channel_id) return; var seat_nb = +channel_id[channel_id.length - 1]; var player = get_seat(table.seats, seat_nb).player; if (table.playing_seats.length == 2) table.game.highlights_pos = seat_nb; if (seat_nb != table.game.highlights_pos) return; if (bet_amount && bet_amount[bet_amount.length - 1] == "$") { bet_amount = bet_amount.slice(0, bet_amount.length - 1); bet_amount = (Math.round(+bet_amount * 100)) / 100; } treat_decision(table, get_seat(table.seats, seat_nb), decision, bet_amount, get_seat(table.seats, seat_nb).player, seat_nb, rc); console.log(decision + " " + bet_amount + " has been chosen by seat n°" + seat_nb); io.to(table.id).emit("last action", decision, seat_nb, bet_amount); console.log(table.game.round_nb + "/" + table.playing_seats.length); if (decision == "FOLD" && table.game.round_nb > table.playing_seats.length && check_bets(table, table.seats)) { if (table.playing_seats.length < 2) return one_playing_player_left(table); next_moment(table, table.game); } else if (table.game.round_nb >= table.playing_seats.length && check_bets(table, table.seats)) { if (table.playing_seats.length < 2) return one_playing_player_left(table); decision == "FOLD" ? switch_next_player(table) : next_moment(table, table.game); } else { if (table.playing_seats.length < 2) return one_playing_player_left(table); switch_next_player(table); } if (decision == "FOLD" && (table.game.round_nb + 1) == table.playing_seats.length); else ++table.game.round_nb; /* if (!get_seat(table.seats, table.game.highlights_pos).player.bankroll) { remove_from_playing_seats(table.playing_seats, seat_nb); get_seat(table.seats, table.game.highlights_pos).state = "busy"; console.log('qui ? ' + seat_nb, get_seat(table.seats, table.game.highlights_pos).state); } if (table.playing_seats.length < 2) return one_playing_player_left(table);*/ }); socket.on("action done", function() { io.to(table.id).emit("action is true"); }); socket.on("stop timer action", function(tablee) { stop_timer(tablee); }); socket.on("ask buttons", function() { if (table.game.highlights_pos) { io.to(table.id).emit("place button", "sb", table.game.sb_pos); // Respect this sending order. io.to(table.id).emit("place button", "dealer", table.game.d_pos); io.to(table.id).emit("place button", "bb", table.game.bb_pos); } io.to(table.id).emit("highlights", table.game.highlights_pos); }); socket.on('get pot amount', function() { socket.emit('pot amount', table.game.pot_amount); }); socket.on('need Id', function() { io.to(table.id).emit('give Idx', table_id); }); io.to(table.id).emit("pot modification", table.game.pot_amount); } function tryChrono(socket, table) { lock = true; io.to(table.id).emit("chrono", 45, "The game will begin ..."); var timer = setInterval(function() { clearInterval(timer); io.to(table.id).emit("chrono off"); if (table.playing_seats.length > 1) { console.log("Starting a new game..."); new_cashgame(socket, table); lock = false; } else tryChrono(socket, table); }, 45000); } function treat_decision(table, seat, decision, bet_amount, player, seat_nb, rc) { if (decision == "FOLD") decision = "FOLD"; else if (rc == "undefined") decision = "CALL"; else if (rc == 1) decision = "RAISE"; if (decision == "CHECK" && +seat.bet === +table.game.curbet) return (1); else if (decision == "CALL") { player.bankroll -= (+table.game.curbet - +seat.bet) > 0 ? (+table.game.curbet - +seat.bet) : +table.game.curbet; if (player.bankroll < 0) player.bankroll = 0; seat.bet = +seat.bet + +bet_amount; seat.bet = Math.round(seat.bet * 100) / 100; seat.bet = +seat.bet + (+table.game.curbet - +seat.bet); table.game.pot_amount = +table.game.pot_amount + +bet_amount; io.to(table.id).emit("bet", seat_nb, +seat.bet); io.to(table.id).emit("bankroll modification", seat_nb, player); io.to(table.id).emit("pot modification", +table.game.pot_amount); return (1); } else if (decision == "RAISE" || decision == "BET") { if (bet_amount > player.bankroll || bet_amount <= 0) return (0); player.bankroll -= +bet_amount; if (player.bankroll < 0) player.bankroll = 0; table.game.curbet = +bet_amount /*+ +seat.bet*/ ; seat.bet = /*+seat.bet +*/ +bet_amount; seat.bet = Math.round(seat.bet * 100) / 100; table.game.pot_amount = +table.game.pot_amount + +bet_amount; io.to(table.id).emit("bet", seat_nb, +seat.bet); io.to(table.id).emit("bankroll modification", seat_nb, player); io.to(table.id).emit("pot modification", +table.game.pot_amount); return (1); } else if (decision == "FOLD") { remove_from_playing_seats(table.playing_seats, seat_nb); seat.state = "busy"; io.to(table.id).emit("fold", seat_nb); return (1); } return (1); } function adjust_bets_values(table) { var curseat; for (var idx = 1; idx <= 6; ++idx) { if (table.playing_seats.indexOf(idx) != -1) { curseat = get_seat(table.seats, idx); curseat.bet = (Math.round(curseat.bet * 100)) / 100; console.log("Seat bet n°" + idx + ": " + curseat.bet); } } } function switch_next_player(table) { var player; console.log('switch next player'); if (table.game.highlights_pos == "none") return; io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait"); io.to(table.id).emit("highlights", table.game.highlights_pos, "off"); table.game.highlights_pos = get_next_player(table, table.game); io.to(table.id).emit("highlights", table.game.highlights_pos, "on"); send_raise_limits(table, table.game, table.game.highlights_pos, 0); adjust_bets_values(table); io.to(table.id).emit("timer action", get_table(table.id, tables)); if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) { if (table.game.curbet == "0") { send_option(table, table.game.highlights_pos, "first choice", "check", 0); send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind); send_raise_limits(table, table.game, table.game.highlights_pos, 1); } else { if (table.game.curbet > get_seat(table.seats, table.game.highlights_pos).player.bankroll) { send_option(table, table.game.highlights_pos, "first choice", "call", get_seat(table.seats, table.game.highlights_pos).player.bankroll); send_option(table, table.game.highlights_pos, "second choice", "null", -1); } else { send_option(table, table.game.highlights_pos, "first choice", "call", table.game.curbet); if (table.game.curbet * 2 > get_seat(table.seats, table.game.highlights_pos).player.bankroll) { send_option(table, table.game.highlights_pos, "second choice", "null", -1); } else { send_option(table, table.game.highlights_pos, "second choice", "raise", table.game.curbet * 2) } } } send_option(table, table.game.highlights_pos, "third choice", "fold", 0); } else { if (table.playing_seats.length < 3) { if (table.game.moment == "preflop") { table.game.moment = "flop"; deal_flop(table, table.game); evalhand(table, table.game); } if (table.game.moment == "flop") { table.game.moment = "turn"; deal_turn(table, table.game); evalhand(table, table.game); } if (table.game.moment == "turn") { table.game.moment = "river"; deal_river(table, table.game); evalhand(table, table.game); } if (table.game.moment == "river") { return show_down(table, table.game); } } // io.to(table.id).emit("action is true"); send_option(table, table.game.highlights_pos, "first choice", "check", -1); send_option(table, table.game.highlights_pos, "second choice", "null", -1); send_option(table, table.game.highlights_pos, "third choice", "fold", -1); // io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0); } } function next_moment(table, game) { var player; console.log('next_moment'); if (table.game.moment == "preflop") { table.game.curbet = "0"; table.game.moment = "flop"; deal_flop(table, game); evalhand(table, game); } else if (table.game.moment == "flop") { table.game.curbet = "0"; table.game.moment = "turn"; deal_turn(table, game); evalhand(table, game); } else if (table.game.moment == "turn") { table.game.curbet = "0"; table.game.moment = "river"; deal_river(table, game); evalhand(table, game); } else if (table.game.moment == "river") { return show_down(table, game); } table.game.round_nb = 0; table.game.curbet = "0"; for (var idx = 1; idx <= 6; ++idx) { get_seat(table.seats, idx).bet = 0; io.to(table.id).emit("bet", idx, ""); } io.to(table.id).emit("timer action", get_table(table.id, tables)); io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait"); io.to(table.id).emit("highlights", table.game.highlights_pos, "off"); table.game.highlights_pos = get_first_to_talk(table, game, false); io.to(table.id).emit("highlights", table.game.highlights_pos, "on"); send_raise_limits(table, table.game, table.game.highlights_pos, 1); if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) { send_option(table, table.game.highlights_pos, "first choice", "check", 0); if (get_seat(table.seats, table.game.highlights_pos).player.bankroll < cfg.conf.big_blind) send_option(table, table.game.highlights_pos, "second choice", "null", -1); else send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind); send_option(table, table.game.highlights_pos, "third choice", "fold", 0); } else { if (table.playing_seats.length < 3) { if (table.game.moment == "preflop") { table.game.moment = "flop"; deal_flop(table, table.game); evalhand(table, table.game); } if (table.game.moment == "flop") { table.game.moment = "turn"; deal_turn(table, table.game); evalhand(table, table.game); } if (table.game.moment == "turn") { table.game.moment = "river"; deal_river(table, table.game); evalhand(table, table.game); } if (table.game.moment == "river") { return show_down(table, table.game); } } // io.to(table.id).emit("action is true"); send_option(table, table.game.highlights_pos, "first choice", "check", -1); send_option(table, table.game.highlights_pos, "second choice", "null", -1); send_option(table, table.game.highlights_pos, "third choice", "fold", -1); // io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0); } } function one_playing_player_left(table) { var player = get_seat(table.seats, table.playing_seats[0]).player; table = get_table(table.id, tables); player.bankroll += +table.game.pot_amount; io.to(table.id).emit("bankroll modification", table.playing_seats[0], player); if (table.game.moment != "waiting" || table.game.moment != "waiting end game") return end_game(table, table.game, 42, player); else return; }
sv/players_general_socket.js
var lock = false; function socket_listens_players(socket, table) { var player; // Current player. var curseat; // Current seat. var channel; // Channel involved. socket.on("is valid nickname", function(nickname, seat_idx) { curseat = get_seat(table.seats, seat_idx); channel = get_private_id(table.private_ids, seat_idx); if (!nickname || check_blanks(nickname) || nickname.length < 2 || nickname.length > 8) { console.log("Invalid nickname!"); socket.emit("is valid nickname info", "invalid"); } else if (table.nicknames.indexOf(nickname) != -1) { console.log("Nickname already taken!"); socket.emit("is valid nickname info", "already taken"); } else if (curseat.state != "available") socket.emit("is valid nickname info", "seat busy"); else { console.log(nickname + " is valid!"); socket.emit("is valid nickname info", "valid", nickname); table.nicknames.push(nickname); // Add the user nickname to the table nicknames array. if (table.players_nb < 6) ++table.players_nb; console.log("There are now " + table.players_nb + " seated at the table (imo of course)!"); player = new Player(seat_idx, nickname, +table.start_bankroll, -1, -1, -1, -1); curseat.state = "busy"; curseat.player = player; console.log("Seat" + seat_idx + " is now " + curseat.state); io.to(table.id).emit("new player", player); if (table.playing_seats.indexOf(seat_idx) != -1) return; if (table.game.moment == "waiting") table.playing_seats.push(seat_idx); for (var i = 0; i < table.playing_seats.length; i++) get_seat(table.seats, table.playing_seats[i]).state = "playing"; console.log(table.game.moment); if (table.players_nb >= 1 && table.game.moment == "waiting") { if (lock) return; else tryChrono(socket, table); } return; } }); socket.on("get seated players", function() { send_seats_infos(table); }); socket.on("get board", function() { if (table.game.board.length >= 3) io.to(table.id).emit("send flop", table.game.board[0], table.game.board[1], table.game.board[2]); if (table.game.board.length >= 4) io.to(table.id).emit("send turn", table.game.board[3]); if (table.game.board.length === 5) io.to(table.id).emit("send river", table.game.board[4]); }); socket.on("player decision", function(decision, channel_id, bet_amount, rc) { if (!decision || !channel_id) return; var seat_nb = +channel_id[channel_id.length - 1]; var player = get_seat(table.seats, seat_nb).player; if (table.playing_seats.length == 2) table.game.highlights_pos = seat_nb; if (seat_nb != table.game.highlights_pos) return; if (bet_amount && bet_amount[bet_amount.length - 1] == "$") { bet_amount = bet_amount.slice(0, bet_amount.length - 1); bet_amount = (Math.round(+bet_amount * 100)) / 100; } treat_decision(table, get_seat(table.seats, seat_nb), decision, bet_amount, get_seat(table.seats, seat_nb).player, seat_nb, rc); console.log(decision + " " + bet_amount + " has been chosen by seat n°" + seat_nb); io.to(table.id).emit("last action", decision, seat_nb, bet_amount); console.log(table.game.round_nb + "/" + table.playing_seats.length); if (decision == "FOLD" && table.game.round_nb > table.playing_seats.length && check_bets(table, table.seats)) { if (table.playing_seats.length < 2) return one_playing_player_left(table); next_moment(table, table.game); } else if (table.game.round_nb >= table.playing_seats.length && check_bets(table, table.seats)) { if (table.playing_seats.length < 2) return one_playing_player_left(table); decision == "FOLD" ? switch_next_player(table) : next_moment(table, table.game); } else { if (table.playing_seats.length < 2) return one_playing_player_left(table); switch_next_player(table); } if (decision == "FOLD" && (table.game.round_nb + 1) == table.playing_seats.length); else ++table.game.round_nb; if (!get_seat(table.seats, table.game.highlights_pos).player.bankroll) { remove_from_playing_seats(table.playing_seats, seat_nb); get_seat(table.seats, table.game.highlights_pos).state = "busy"; console.log('qui ? ' + seat_nb, get_seat(table.seats, table.game.highlights_pos).state); } if (table.playing_seats.length < 2) return one_playing_player_left(table); }); socket.on("action done", function() { io.to(table.id).emit("action is true"); }); socket.on("stop timer action", function(tablee) { stop_timer(tablee); }); socket.on("ask buttons", function() { if (table.game.highlights_pos) { io.to(table.id).emit("place button", "sb", table.game.sb_pos); // Respect this sending order. io.to(table.id).emit("place button", "dealer", table.game.d_pos); io.to(table.id).emit("place button", "bb", table.game.bb_pos); } io.to(table.id).emit("highlights", table.game.highlights_pos); }); socket.on('get pot amount', function() { socket.emit('pot amount', table.game.pot_amount); }); socket.on('need Id', function() { io.to(table.id).emit('give Idx', table_id); }); io.to(table.id).emit("pot modification", table.game.pot_amount); } function tryChrono(socket, table) { lock = true; io.to(table.id).emit("chrono", 45, "The game will begin ..."); var timer = setInterval(function() { clearInterval(timer); io.to(table.id).emit("chrono off"); if (table.playing_seats.length > 1) { console.log("Starting a new game..."); new_cashgame(socket, table); lock = false; } else tryChrono(socket, table); }, 45000); } function treat_decision(table, seat, decision, bet_amount, player, seat_nb, rc) { if (decision == "FOLD") decision = "FOLD"; else if (rc == "undefined") decision = "CALL"; else if (rc == 1) decision = "RAISE"; if (decision == "CHECK" && +seat.bet === +table.game.curbet) return (1); else if (decision == "CALL") { player.bankroll -= (+table.game.curbet - +seat.bet) > 0 ? (+table.game.curbet - +seat.bet) : +table.game.curbet; if (player.bankroll < 0) player.bankroll = 0; seat.bet = +seat.bet + +bet_amount; seat.bet = Math.round(seat.bet * 100) / 100; seat.bet = +seat.bet + (+table.game.curbet - +seat.bet); table.game.pot_amount = +table.game.pot_amount + +bet_amount; io.to(table.id).emit("bet", seat_nb, +seat.bet); io.to(table.id).emit("bankroll modification", seat_nb, player); io.to(table.id).emit("pot modification", +table.game.pot_amount); return (1); } else if (decision == "RAISE" || decision == "BET") { if (bet_amount > player.bankroll || bet_amount <= 0) return (0); player.bankroll -= +bet_amount; if (player.bankroll < 0) player.bankroll = 0; table.game.curbet = +bet_amount /*+ +seat.bet*/ ; seat.bet = /*+seat.bet +*/ +bet_amount; seat.bet = Math.round(seat.bet * 100) / 100; table.game.pot_amount = +table.game.pot_amount + +bet_amount; io.to(table.id).emit("bet", seat_nb, +seat.bet); io.to(table.id).emit("bankroll modification", seat_nb, player); io.to(table.id).emit("pot modification", +table.game.pot_amount); return (1); } else if (decision == "FOLD") { remove_from_playing_seats(table.playing_seats, seat_nb); seat.state = "busy"; io.to(table.id).emit("fold", seat_nb); return (1); } return (1); } function adjust_bets_values(table) { var curseat; for (var idx = 1; idx <= 6; ++idx) { if (table.playing_seats.indexOf(idx) != -1) { curseat = get_seat(table.seats, idx); curseat.bet = (Math.round(curseat.bet * 100)) / 100; console.log("Seat bet n°" + idx + ": " + curseat.bet); } } } function switch_next_player(table) { var player; console.log('switch next player'); if (table.game.highlights_pos == "none") return; io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait"); io.to(table.id).emit("highlights", table.game.highlights_pos, "off"); table.game.highlights_pos = get_next_player(table, table.game); io.to(table.id).emit("highlights", table.game.highlights_pos, "on"); send_raise_limits(table, table.game, table.game.highlights_pos, 0); adjust_bets_values(table); io.to(table.id).emit("timer action", get_table(table.id, tables)); if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) { if (table.game.curbet == "0") { send_option(table, table.game.highlights_pos, "first choice", "check", 0); send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind); send_raise_limits(table, table.game, table.game.highlights_pos, 1); } else { if (table.game.curbet > get_seat(table.seats, table.game.highlights_pos).player.bankroll) { send_option(table, table.game.highlights_pos, "first choice", "call", get_seat(table.seats, table.game.highlights_pos).player.bankroll); send_option(table, table.game.highlights_pos, "second choice", "null", -1); } else { send_option(table, table.game.highlights_pos, "first choice", "call", table.game.curbet); if (table.game.curbet * 2 > get_seat(table.seats, table.game.highlights_pos).player.bankroll) { send_option(table, table.game.highlights_pos, "second choice", "null", -1); } else { send_option(table, table.game.highlights_pos, "second choice", "raise", table.game.curbet * 2) } } } send_option(table, table.game.highlights_pos, "third choice", "fold", 0); } else { if (table.playing_seats.length < 3) { if (table.game.moment == "preflop") { table.game.moment = "flop"; deal_flop(table, table.game); evalhand(table, table.game); } if (table.game.moment == "flop") { table.game.moment = "turn"; deal_turn(table, table.game); evalhand(table, table.game); } if (table.game.moment == "turn") { table.game.moment = "river"; deal_river(table, table.game); evalhand(table, table.game); } if (table.game.moment == "river") { return show_down(table, table.game); } } io.to(table.id).emit("action is true"); /*send_option(table, table.game.highlights_pos, "first choice", "check", -1); send_option(table, table.game.highlights_pos, "second choice", "null", -1); send_option(table, table.game.highlights_pos, "third choice", "fold", -1); io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0);*/ } } function next_moment(table, game) { var player; console.log('next_moment'); if (table.game.moment == "preflop") { table.game.curbet = "0"; table.game.moment = "flop"; deal_flop(table, game); evalhand(table, game); } else if (table.game.moment == "flop") { table.game.curbet = "0"; table.game.moment = "turn"; deal_turn(table, game); evalhand(table, game); } else if (table.game.moment == "turn") { table.game.curbet = "0"; table.game.moment = "river"; deal_river(table, game); evalhand(table, game); } else if (table.game.moment == "river") { return show_down(table, game); } table.game.round_nb = 0; table.game.curbet = "0"; for (var idx = 1; idx <= 6; ++idx) { get_seat(table.seats, idx).bet = 0; io.to(table.id).emit("bet", idx, ""); } io.to(table.id).emit("timer action", get_table(table.id, tables)); io.to(get_private_id(table.private_ids, table.game.highlights_pos)).emit("turn wait"); io.to(table.id).emit("highlights", table.game.highlights_pos, "off"); table.game.highlights_pos = get_first_to_talk(table, game, false); io.to(table.id).emit("highlights", table.game.highlights_pos, "on"); send_raise_limits(table, table.game, table.game.highlights_pos, 1); if (get_seat(table.seats, table.game.highlights_pos).player.bankroll) { send_option(table, table.game.highlights_pos, "first choice", "check", 0); if (get_seat(table.seats, table.game.highlights_pos).player.bankroll < cfg.conf.big_blind) send_option(table, table.game.highlights_pos, "second choice", "null", -1); else send_option(table, table.game.highlights_pos, "second choice", "call", cfg.conf.big_blind); send_option(table, table.game.highlights_pos, "third choice", "fold", 0); } else { if (table.playing_seats.length < 3) { if (table.game.moment == "preflop") { table.game.moment = "flop"; deal_flop(table, table.game); evalhand(table, table.game); } if (table.game.moment == "flop") { table.game.moment = "turn"; deal_turn(table, table.game); evalhand(table, table.game); } if (table.game.moment == "turn") { table.game.moment = "river"; deal_river(table, table.game); evalhand(table, table.game); } if (table.game.moment == "river") { return show_down(table, table.game); } } io.to(table.id).emit("action is true"); /*send_option(table, table.game.highlights_pos, "first choice", "check", -1); send_option(table, table.game.highlights_pos, "second choice", "null", -1); send_option(table, table.game.highlights_pos, "third choice", "fold", -1); io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0);*/ } } function one_playing_player_left(table) { var player = get_seat(table.seats, table.playing_seats[0]).player; table = get_table(table.id, tables); player.bankroll += +table.game.pot_amount; io.to(table.id).emit("bankroll modification", table.playing_seats[0], player); if (table.game.moment != "waiting" || table.game.moment != "waiting end game") return end_game(table, table.game, 42, player); else return; }
retry
sv/players_general_socket.js
retry
<ide><path>v/players_general_socket.js <ide> if (decision == "FOLD" && (table.game.round_nb + 1) == table.playing_seats.length); <ide> else <ide> ++table.game.round_nb; <del> if (!get_seat(table.seats, table.game.highlights_pos).player.bankroll) { <add> /* if (!get_seat(table.seats, table.game.highlights_pos).player.bankroll) { <ide> remove_from_playing_seats(table.playing_seats, seat_nb); <ide> get_seat(table.seats, table.game.highlights_pos).state = "busy"; <ide> console.log('qui ? ' + seat_nb, get_seat(table.seats, table.game.highlights_pos).state); <ide> } <ide> if (table.playing_seats.length < 2) <del> return one_playing_player_left(table); <add> return one_playing_player_left(table);*/ <ide> }); <ide> socket.on("action done", function() { <ide> io.to(table.id).emit("action is true"); <ide> return show_down(table, table.game); <ide> } <ide> } <del> io.to(table.id).emit("action is true"); <del> /*send_option(table, table.game.highlights_pos, "first choice", "check", -1); <add>// io.to(table.id).emit("action is true"); <add> send_option(table, table.game.highlights_pos, "first choice", "check", -1); <ide> send_option(table, table.game.highlights_pos, "second choice", "null", -1); <ide> send_option(table, table.game.highlights_pos, "third choice", "fold", -1); <del> io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0);*/ <add>// io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0); <ide> } <ide> } <ide> <ide> return show_down(table, table.game); <ide> } <ide> } <del> io.to(table.id).emit("action is true"); <del> /*send_option(table, table.game.highlights_pos, "first choice", "check", -1); <add>// io.to(table.id).emit("action is true"); <add> send_option(table, table.game.highlights_pos, "first choice", "check", -1); <ide> send_option(table, table.game.highlights_pos, "second choice", "null", -1); <ide> send_option(table, table.game.highlights_pos, "third choice", "fold", -1); <del> io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0);*/ <add>// io.to(table.id).emit("i fold", "PASS", get_private_id(table.private_ids, table.game.highlights_pos), 0); <ide> } <ide> } <ide>
Java
apache-2.0
ed5e336872efe638198ccabc7a4e054f7d24df20
0
Danny02/deltaspike,os890/DS_Discuss,struberg/deltaspike,chkal/deltaspike,mlachat/deltaspike,rdicroce/deltaspike,tremes/deltaspike,LightGuard/incubator-deltaspike,os890/deltaspike-vote,chkal/deltaspike,idontgotit/deltaspike,rafabene/deltaspike,idontgotit/deltaspike,os890/DS_Discuss,os890/deltaspike-vote,subaochen/deltaspike,idontgotit/deltaspike,rdicroce/deltaspike,subaochen/deltaspike,jharting/deltaspike,mlachat/deltaspike,chkal/deltaspike,subaochen/deltaspike,rafabene/deltaspike,tremes/deltaspike,jharting/deltaspike,rdicroce/deltaspike,os890/DeltaSpikePlayground,os890/DeltaSpikePlayground,jharting/deltaspike,chkal/deltaspike,danielsoro/deltaspike,apache/deltaspike,LightGuard/incubator-deltaspike,tremes/deltaspike,os890/deltaspike-vote,tremes/deltaspike,os890/DeltaSpikePlayground,Danny02/deltaspike,Danny02/deltaspike,rafabene/deltaspike,apache/deltaspike,struberg/deltaspike,struberg/deltaspike,mlachat/deltaspike,apache/deltaspike,Danny02/deltaspike,os890/deltaspike-vote,subaochen/deltaspike,danielsoro/deltaspike,LightGuard/incubator-deltaspike,idontgotit/deltaspike,rdicroce/deltaspike,danielsoro/deltaspike,struberg/deltaspike,os890/DS_Discuss,mlachat/deltaspike,os890/DS_Discuss,danielsoro/deltaspike,apache/deltaspike
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.deltaspike.test.core.impl.resourceloader; import org.apache.deltaspike.core.api.literal.ExternalResourceLiteral; import org.apache.deltaspike.core.api.resourceloader.ClasspathStorage; import org.apache.deltaspike.test.util.ArchiveUtils; import org.apache.deltaspike.test.utils.CdiContainerUnderTest; import org.apache.deltaspike.test.utils.CdiImplementation; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Properties; @RunWith(Arquillian.class) public class ClasspathResourceTest { @Deployment public static Archive<?> createResourceLoaderArchive() { Class versionDependentImplementation = Cdi11Bean.class; if (isOwbForCdi10()) { versionDependentImplementation = Cdi10Bean.class; } Archive<?> arch = ShrinkWrap.create(WebArchive.class, ClasspathResourceTest.class.getSimpleName() + ".war") .addClass(TestResourceHolder.class) .addClass(versionDependentImplementation) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .add(new StringAsset("some.propertykey = somevalue"), "WEB-INF/classes/testconfig.properties") .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreArchive()); return arch; } @Inject private TestResourceHolder testResourceHolder; @Test public void testInputStream() throws IOException { Assume.assumeTrue(!isOwbForCdi10()); Assert.assertNotNull(testResourceHolder.getInputStream()); Properties p = new Properties(); p.load(testResourceHolder.getInputStream()); Assert.assertEquals("somevalue", p.getProperty("some.propertykey", "wrong answer")); } @Test public void testProperties() { Assume.assumeTrue(!isOwbForCdi10()); Assert.assertEquals("somevalue", testResourceHolder.getProperties().getProperty("some.propertykey", "wrong answer")); } @Test(expected = RuntimeException.class) public void testAmbiguousFileLookup() { Assume.assumeTrue(!isOwbForCdi10()); testResourceHolder.getInputStreamInstance() .select(new ExternalResourceLiteral(ClasspathStorage.class, "META-INF/beans.xml")).get(); } @Test public void testSuccessfulAmbiguousLookup() { Assume.assumeTrue(!isOwbForCdi10()); //note, we only test this on classpath, since File impl is always getting 1. List<InputStream> streams = testResourceHolder.getInputStreams(); Assert.assertTrue(streams.size() > 1); //the count is different on as7 compared to the standalone setup } private static boolean isOwbForCdi10() { return CdiContainerUnderTest.isCdiVersion(CdiImplementation.OWB11) || CdiContainerUnderTest.isCdiVersion(CdiImplementation.OWB12); } }
deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/resourceloader/ClasspathResourceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.deltaspike.test.core.impl.resourceloader; import org.apache.deltaspike.core.api.literal.ExternalResourceLiteral; import org.apache.deltaspike.core.api.resourceloader.ClasspathStorage; import org.apache.deltaspike.test.util.ArchiveUtils; import org.apache.deltaspike.test.utils.CdiContainerUnderTest; import org.apache.deltaspike.test.utils.CdiImplementation; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.Assume; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Properties; @RunWith(Arquillian.class) public class ClasspathResourceTest { @Deployment public static Archive<?> createResourceLoaderArchive() { Class versionDependentImplementation = Cdi11Bean.class; if (isOwbForCdi10()) { versionDependentImplementation = Cdi10Bean.class; } Archive<?> arch = ShrinkWrap.create(WebArchive.class, ClasspathResourceTest.class.getSimpleName() + ".war") .addClass(TestResourceHolder.class) .addClass(versionDependentImplementation) .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") .add(new StringAsset("some.propertykey = somevalue"), "WEB-INF/classes/testconfig.properties") .addAsLibraries(ArchiveUtils.getDeltaSpikeCoreArchive()); return arch; } @Inject private TestResourceHolder testResourceHolder; @Test public void testInputStream() throws IOException { Assume.assumeTrue(!isOwbForCdi10()); Assert.assertNotNull(testResourceHolder.getInputStream()); Properties p = new Properties(); p.load(testResourceHolder.getInputStream()); Assert.assertEquals("somevalue", p.getProperty("some.propertykey", "wrong answer")); } @Test public void testProperties() { Assume.assumeTrue(!isOwbForCdi10()); Assert.assertEquals("somevalue", testResourceHolder.getProperties().getProperty("some.propertykey", "wrong answer")); } @Test(expected = RuntimeException.class) public void testAmbiguousFileLookup() { Assume.assumeTrue(!isOwbForCdi10()); testResourceHolder.getInputStreamInstance() .select(new ExternalResourceLiteral(ClasspathStorage.class, "META-INF/beans.xml")).get(); } @Test public void testSuccessfulAmbiguousLookup() { Assume.assumeTrue(!isOwbForCdi10()); //note, we only test this on classpath, since File impl is always getting 1. List<InputStream> streams = testResourceHolder.getInputStreams(); Assert.assertEquals(4,streams.size()); } private static boolean isOwbForCdi10() { return CdiContainerUnderTest.isCdiVersion(CdiImplementation.OWB11) || CdiContainerUnderTest.isCdiVersion(CdiImplementation.OWB12); } }
DELTASPIKE-399 fixed test
deltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/resourceloader/ClasspathResourceTest.java
DELTASPIKE-399 fixed test
<ide><path>eltaspike/core/impl/src/test/java/org/apache/deltaspike/test/core/impl/resourceloader/ClasspathResourceTest.java <ide> Assume.assumeTrue(!isOwbForCdi10()); <ide> //note, we only test this on classpath, since File impl is always getting 1. <ide> List<InputStream> streams = testResourceHolder.getInputStreams(); <del> Assert.assertEquals(4,streams.size()); <del> <add> Assert.assertTrue(streams.size() > 1); //the count is different on as7 compared to the standalone setup <ide> } <ide> <ide> private static boolean isOwbForCdi10()
Java
apache-2.0
c35707ce06bd1c2eae0a56d43c8d1057ed8efc70
0
idea4bsd/idea4bsd,apixandru/intellij-community,robovm/robovm-studio,izonder/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,semonte/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,supersven/intellij-community,kool79/intellij-community,fitermay/intellij-community,apixandru/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,petteyg/intellij-community,Distrotech/intellij-community,da1z/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,signed/intellij-community,pwoodworth/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,signed/intellij-community,ibinti/intellij-community,da1z/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,ibinti/intellij-community,jagguli/intellij-community,dslomov/intellij-community,da1z/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,slisson/intellij-community,allotria/intellij-community,supersven/intellij-community,Distrotech/intellij-community,caot/intellij-community,retomerz/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,izonder/intellij-community,supersven/intellij-community,kool79/intellij-community,hurricup/intellij-community,fitermay/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,da1z/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,dslomov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,slisson/intellij-community,semonte/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,consulo/consulo,gnuhub/intellij-community,ernestp/consulo,retomerz/intellij-community,holmes/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,consulo/consulo,ahb0327/intellij-community,ernestp/consulo,FHannes/intellij-community,blademainer/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,dslomov/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,izonder/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,ernestp/consulo,ryano144/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,Lekanich/intellij-community,kool79/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,kool79/intellij-community,jagguli/intellij-community,da1z/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,blademainer/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,amith01994/intellij-community,signed/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,allotria/intellij-community,fitermay/intellij-community,petteyg/intellij-community,amith01994/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,supersven/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,allotria/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,holmes/intellij-community,retomerz/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,dslomov/intellij-community,wreckJ/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,signed/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,diorcety/intellij-community,allotria/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,slisson/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,caot/intellij-community,signed/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,allotria/intellij-community,holmes/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,fnouama/intellij-community,samthor/intellij-community,wreckJ/intellij-community,samthor/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,clumsy/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,jagguli/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,hurricup/intellij-community,robovm/robovm-studio,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,fnouama/intellij-community,vladmm/intellij-community,slisson/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,dslomov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,izonder/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,caot/intellij-community,ibinti/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,fitermay/intellij-community,dslomov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,consulo/consulo,retomerz/intellij-community,supersven/intellij-community,vladmm/intellij-community,supersven/intellij-community,ibinti/intellij-community,kdwink/intellij-community,kool79/intellij-community,xfournet/intellij-community,semonte/intellij-community,retomerz/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,apixandru/intellij-community,asedunov/intellij-community,supersven/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,slisson/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,gnuhub/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,clumsy/intellij-community,xfournet/intellij-community,vladmm/intellij-community,FHannes/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,consulo/consulo,tmpgit/intellij-community,asedunov/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,nicolargo/intellij-community,supersven/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,jagguli/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,retomerz/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,dslomov/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,da1z/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,fnouama/intellij-community,kdwink/intellij-community,robovm/robovm-studio,consulo/consulo,apixandru/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,fitermay/intellij-community,caot/intellij-community,semonte/intellij-community,fitermay/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ryano144/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,caot/intellij-community,clumsy/intellij-community,caot/intellij-community,diorcety/intellij-community,apixandru/intellij-community,ryano144/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,akosyakov/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,kool79/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,allotria/intellij-community,da1z/intellij-community,wreckJ/intellij-community,semonte/intellij-community,izonder/intellij-community,signed/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,diorcety/intellij-community,supersven/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,slisson/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,petteyg/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,semonte/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,ernestp/consulo,xfournet/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,samthor/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,caot/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,petteyg/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,hurricup/intellij-community,blademainer/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,asedunov/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,vladmm/intellij-community,holmes/intellij-community,fitermay/intellij-community,semonte/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,signed/intellij-community,kdwink/intellij-community,amith01994/intellij-community,caot/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,caot/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,petteyg/intellij-community,fnouama/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,diorcety/intellij-community,ryano144/intellij-community,ernestp/consulo,wreckJ/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,allotria/intellij-community,clumsy/intellij-community,kool79/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,slisson/intellij-community,asedunov/intellij-community,vladmm/intellij-community,kool79/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,caot/intellij-community,supersven/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,Lekanich/intellij-community,samthor/intellij-community,signed/intellij-community,caot/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,robovm/robovm-studio,consulo/consulo,ernestp/consulo,kdwink/intellij-community,nicolargo/intellij-community
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide; import com.intellij.mock.MockApplication; import com.intellij.mock.MockProject; import com.intellij.mock.MockProjectEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.impl.ModalityStateEx; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.BusyObject; import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Created by IntelliJ IDEA. * User: kirillk * Date: 8/17/11 * Time: 10:04 AM * To change this template use File | Settings | File Templates. */ public class ActivityMonitorTest extends UsefulTestCase { private UiActivityMonitorImpl myMonitor; private ModalityState myCurrentState; @Override protected void setUp() throws Exception { super.setUp(); myCurrentState = ModalityState.NON_MODAL; final ModalityStateEx any = new ModalityStateEx(); Extensions.registerAreaClass("IDEA_PROJECT", null); ApplicationManager.setApplication(new MockApplication(getTestRootDisposable()) { @NotNull @Override public ModalityState getCurrentModalityState() { return myCurrentState; } @Override public ModalityState getAnyModalityState() { return any; } }, getTestRootDisposable()); myMonitor = new UiActivityMonitorImpl(new MockApplication(getTestRootDisposable())); myMonitor.setActive(true); disposeOnTearDown(myMonitor); } public void testReady() { assertReady(null); MockProject project1 = new MockProjectEx(getTestRootDisposable()); assertReady(project1); assertFalse(myMonitor.hasObjectFor(project1)); MockProject project2 = new MockProjectEx(getTestRootDisposable()); assertReady(project2); assertFalse(myMonitor.hasObjectFor(project2)); myMonitor.initBusyObjectFor(project1); assertTrue(myMonitor.hasObjectFor(project1)); myMonitor.initBusyObjectFor(project2); assertTrue(myMonitor.hasObjectFor(project2)); myMonitor.addActivity(new UiActivity("global"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertBusy(project2); myMonitor.addActivity(new UiActivity("global"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertBusy(project2); myMonitor.removeActivity(new UiActivity("global")); assertReady(null); assertReady(project1); assertReady(project2); myMonitor.addActivity(project1, new UiActivity("p1"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertReady(project2); myMonitor.addActivity(new UiActivity("global"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertBusy(project2); myMonitor.removeActivity(new UiActivity("global")); assertBusy(null); assertBusy(project1); assertReady(project2); myMonitor.removeActivity(project1, new UiActivity("p1")); assertReady(null); assertReady(project1); assertReady(project2); } public void testReadyWithWatchActivities() throws Exception { final UiActivity root = new UiActivity("root"); final UiActivity op1 = new UiActivity("root", "operation1"); final UiActivity op2 = new UiActivity("root", "operation2"); final UiActivity op12 = new UiActivity("root", "operation1", "operation12"); final UiActivity op121 = new UiActivity("root", "operation1", "operation12", "operation121"); myMonitor.addActivity(op1); assertBusy(null); assertReady(null, op2); assertBusy(null, op1); assertBusy(null, root); myMonitor.removeActivity(op1); assertReady(null); assertReady(null, op2); assertReady(null, op1); assertReady(null, root); myMonitor.addActivity(op12); assertBusy(null); assertBusy(null, root); assertBusy(null, op12); assertReady(null, op121); } public void testModalityState() { assertReady(null); myMonitor.addActivity(new UiActivity("non_modal_1"), ModalityState.NON_MODAL); assertBusy(null); myCurrentState = new ModalityStateEx(new Object[] {"dialog"}); assertReady(null); myMonitor.addActivity(new UiActivity("non_modal2"), ModalityState.NON_MODAL); assertReady(null); myMonitor.addActivity(new UiActivity("modal_1"), new ModalityStateEx(new Object[] {"dialog"})); assertBusy(null); myMonitor.addActivity(new UiActivity("modal_2"), new ModalityStateEx(new Object[] {"dialog", "popup"})); assertBusy(null); myCurrentState = ModalityState.NON_MODAL; assertBusy(null); } public void testModalityStateAny() { assertReady(null); myMonitor.addActivity(new UiActivity("non_modal_1"), ModalityState.any()); assertBusy(null); myCurrentState = new ModalityStateEx(new Object[] {"dialog"}); assertBusy(null); } public void testUiActivity() throws Exception { assertTrue(new UiActivity("root", "folder1").isSameOrGeneralFor(new UiActivity("root", "folder1"))); assertTrue(new UiActivity("root", "folder1").isSameOrGeneralFor(new UiActivity("root", "folder1", "folder2"))); assertFalse(new UiActivity("root", "folder2").isSameOrGeneralFor(new UiActivity("root", "folder1", "folder2"))); assertFalse(new UiActivity("root", "folder2").isSameOrGeneralFor(new UiActivity("anotherRoot"))); } private void assertReady(@Nullable Project key, UiActivity ... activities) { BusyObject.Impl busy = (BusyObject.Impl)(key != null ? myMonitor.getBusy(key, activities) : myMonitor.getBusy(activities)); assertTrue("Must be READY, but was: BUSY", busy.isReady()); final boolean[] done = new boolean[] {false}; busy.getReady(this).doWhenDone(new Runnable() { @Override public void run() { done[0] = true; } }); assertTrue(done[0]); } private void assertBusy(@Nullable Project key, UiActivity ... activities) { BusyObject.Impl busy = (BusyObject.Impl)(key != null ? myMonitor.getBusy(key, activities) : myMonitor.getBusy(activities)); assertFalse("Must be BUSY, but was: READY", busy.isReady()); } }
platform/platform-impl/testSrc/com/intellij/ide/ActivityMonitorTest.java
/* * Copyright 2000-2011 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide; import com.intellij.mock.MockApplication; import com.intellij.mock.MockProject; import com.intellij.mock.MockProjectEx; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.impl.ModalityStateEx; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.BusyObject; import com.intellij.testFramework.UsefulTestCase; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Created by IntelliJ IDEA. * User: kirillk * Date: 8/17/11 * Time: 10:04 AM * To change this template use File | Settings | File Templates. */ public class ActivityMonitorTest extends UsefulTestCase { private UiActivityMonitorImpl myMonitor; private ModalityState myCurrentState; @Override protected void setUp() throws Exception { super.setUp(); myCurrentState = ModalityState.NON_MODAL; final ModalityStateEx any = new ModalityStateEx(); Extensions.registerAreaClass("IDEA_PROJECT", null); ApplicationManager.setApplication(new MockApplication(getTestRootDisposable()) { @NotNull @Override public ModalityState getCurrentModalityState() { return myCurrentState; } @Override public ModalityState getAnyModalityState() { return any; } }, getTestRootDisposable()); myMonitor = new UiActivityMonitorImpl(new MockApplication(getTestRootDisposable())); disposeOnTearDown(myMonitor); } public void testReady() { assertReady(null); MockProject project1 = new MockProjectEx(getTestRootDisposable()); assertReady(project1); assertFalse(myMonitor.hasObjectFor(project1)); MockProject project2 = new MockProjectEx(getTestRootDisposable()); assertReady(project2); assertFalse(myMonitor.hasObjectFor(project2)); myMonitor.initBusyObjectFor(project1); assertTrue(myMonitor.hasObjectFor(project1)); myMonitor.initBusyObjectFor(project2); assertTrue(myMonitor.hasObjectFor(project2)); myMonitor.addActivity(new UiActivity("global"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertBusy(project2); myMonitor.addActivity(new UiActivity("global"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertBusy(project2); myMonitor.removeActivity(new UiActivity("global")); assertReady(null); assertReady(project1); assertReady(project2); myMonitor.addActivity(project1, new UiActivity("p1"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertReady(project2); myMonitor.addActivity(new UiActivity("global"), ModalityState.any()); assertBusy(null); assertBusy(project1); assertBusy(project2); myMonitor.removeActivity(new UiActivity("global")); assertBusy(null); assertBusy(project1); assertReady(project2); myMonitor.removeActivity(project1, new UiActivity("p1")); assertReady(null); assertReady(project1); assertReady(project2); } public void testReadyWithWatchActivities() throws Exception { final UiActivity root = new UiActivity("root"); final UiActivity op1 = new UiActivity("root", "operation1"); final UiActivity op2 = new UiActivity("root", "operation2"); final UiActivity op12 = new UiActivity("root", "operation1", "operation12"); final UiActivity op121 = new UiActivity("root", "operation1", "operation12", "operation121"); myMonitor.addActivity(op1); assertBusy(null); assertReady(null, op2); assertBusy(null, op1); assertBusy(null, root); myMonitor.removeActivity(op1); assertReady(null); assertReady(null, op2); assertReady(null, op1); assertReady(null, root); myMonitor.addActivity(op12); assertBusy(null); assertBusy(null, root); assertBusy(null, op12); assertReady(null, op121); } public void testModalityState() { assertReady(null); myMonitor.addActivity(new UiActivity("non_modal_1"), ModalityState.NON_MODAL); assertBusy(null); myCurrentState = new ModalityStateEx(new Object[] {"dialog"}); assertReady(null); myMonitor.addActivity(new UiActivity("non_modal2"), ModalityState.NON_MODAL); assertReady(null); myMonitor.addActivity(new UiActivity("modal_1"), new ModalityStateEx(new Object[] {"dialog"})); assertBusy(null); myMonitor.addActivity(new UiActivity("modal_2"), new ModalityStateEx(new Object[] {"dialog", "popup"})); assertBusy(null); myCurrentState = ModalityState.NON_MODAL; assertBusy(null); } public void testModalityStateAny() { assertReady(null); myMonitor.addActivity(new UiActivity("non_modal_1"), ModalityState.any()); assertBusy(null); myCurrentState = new ModalityStateEx(new Object[] {"dialog"}); assertBusy(null); } public void testUiActivity() throws Exception { assertTrue(new UiActivity("root", "folder1").isSameOrGeneralFor(new UiActivity("root", "folder1"))); assertTrue(new UiActivity("root", "folder1").isSameOrGeneralFor(new UiActivity("root", "folder1", "folder2"))); assertFalse(new UiActivity("root", "folder2").isSameOrGeneralFor(new UiActivity("root", "folder1", "folder2"))); assertFalse(new UiActivity("root", "folder2").isSameOrGeneralFor(new UiActivity("anotherRoot"))); } private void assertReady(@Nullable Project key, UiActivity ... activities) { BusyObject.Impl busy = (BusyObject.Impl)(key != null ? myMonitor.getBusy(key, activities) : myMonitor.getBusy(activities)); assertTrue("Must be READY, but was: BUSY", busy.isReady()); final boolean[] done = new boolean[] {false}; busy.getReady(this).doWhenDone(new Runnable() { @Override public void run() { done[0] = true; } }); assertTrue(done[0]); } private void assertBusy(@Nullable Project key, UiActivity ... activities) { BusyObject.Impl busy = (BusyObject.Impl)(key != null ? myMonitor.getBusy(key, activities) : myMonitor.getBusy(activities)); assertFalse("Must be BUSY, but was: READY", busy.isReady()); } }
ActivityMonitor test fixed
platform/platform-impl/testSrc/com/intellij/ide/ActivityMonitorTest.java
ActivityMonitor test fixed
<ide><path>latform/platform-impl/testSrc/com/intellij/ide/ActivityMonitorTest.java <ide> } <ide> }, getTestRootDisposable()); <ide> myMonitor = new UiActivityMonitorImpl(new MockApplication(getTestRootDisposable())); <add> myMonitor.setActive(true); <ide> disposeOnTearDown(myMonitor); <ide> } <ide>
Java
apache-2.0
4e6b93a230ed3bf75f9e176576159d67a2958517
0
Penrillian/LongStringLoader,bellabling/LongStringLoader
package com.penrillian.longstringloaderexample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.google.android.gms.common.GoogleApiAvailability; import com.penrillian.longstringloader.LongStringLoadCompleteListener; import com.penrillian.longstringloader.LongStringLoader; import com.penrillian.longstringloader.LongStringLoaderException; public class RecyclerViewExampleActivity extends AppCompatActivity implements LongStringLoadCompleteListener { private LinearLayout mLongStringLayout; private RelativeLayout mLoadingLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recycler_view_example); mLoadingLayout = (RelativeLayout) findViewById(R.id.loading_layout); mLongStringLayout = (LinearLayout) findViewById(R.id.long_string_layout); try { new LongStringLoader(this, mLongStringLayout).load(GoogleApiAvailability.getInstance().getOpenSourceSoftwareLicenseInfo(this)); } catch (LongStringLoaderException e) { e.printStackTrace(); } } @Override public void onLongStringLoadComplete() { mLoadingLayout.setVisibility(View.GONE); } }
exampleApp/LongStringLoaderExample/app/src/main/java/com/penrillian/longstringloaderexample/RecyclerViewExampleActivity.java
package com.penrillian.longstringloaderexample; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.google.android.gms.common.GoogleApiAvailability; import com.penrillian.longstringloader.LongStringLoadCompleteListener; import com.penrillian.longstringloader.LongStringLoader; import com.penrillian.longstringloader.LongStringLoaderException; public class RecyclerViewExampleActivity extends AppCompatActivity implements LongStringLoadCompleteListener { private LinearLayout mLongStringLayout; private RelativeLayout mLoadingLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recycler_view_example); mLoadingLayout = (RelativeLayout) findViewById(R.id.loading_layout); mLongStringLayout = (LinearLayout) findViewById(R.id.long_string_layout); try { new LongStringLoader(this, GoogleApiAvailability.getInstance().getOpenSourceSoftwareLicenseInfo(this), mLongStringLayout); } catch (LongStringLoaderException e) { e.printStackTrace(); } } @Override public void onLongStringLoadComplete() { mLoadingLayout.setVisibility(View.GONE); } }
Use new API
exampleApp/LongStringLoaderExample/app/src/main/java/com/penrillian/longstringloaderexample/RecyclerViewExampleActivity.java
Use new API
<ide><path>xampleApp/LongStringLoaderExample/app/src/main/java/com/penrillian/longstringloaderexample/RecyclerViewExampleActivity.java <ide> mLongStringLayout = (LinearLayout) findViewById(R.id.long_string_layout); <ide> try <ide> { <del> new LongStringLoader(this, GoogleApiAvailability.getInstance().getOpenSourceSoftwareLicenseInfo(this), mLongStringLayout); <add> new LongStringLoader(this, mLongStringLayout).load(GoogleApiAvailability.getInstance().getOpenSourceSoftwareLicenseInfo(this)); <ide> } catch (LongStringLoaderException e) <ide> { <ide> e.printStackTrace();
Java
mit
e36620ac9ebf604882596aae0b70ab576622be3e
0
jonasrottmann/realm-browser
package de.jonasrottmann.realmsample.data; import io.realm.RealmObject; public class Image extends RealmObject { private int id; private byte[] bytes; public int getId() { return id; } public void setId(int id) { this.id = id; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } }
app/src/main/java/de/jonasrottmann/realmsample/data/Image.java
package de.jonasrottmann.realmsample.data; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class Image extends RealmObject { @PrimaryKey private int id; private byte[] bytes; public int getId() { return id; } public void setId(int id) { this.id = id; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } }
removed pk from test image entity
app/src/main/java/de/jonasrottmann/realmsample/data/Image.java
removed pk from test image entity
<ide><path>pp/src/main/java/de/jonasrottmann/realmsample/data/Image.java <ide> package de.jonasrottmann.realmsample.data; <ide> <ide> import io.realm.RealmObject; <del>import io.realm.annotations.PrimaryKey; <ide> <ide> public class Image extends RealmObject { <del> @PrimaryKey <ide> private int id; <ide> private byte[] bytes; <ide>
Java
lgpl-2.1
fac1361e6664eb740793c7381811d2495075c0c2
0
tiry/nuxeo-security-policy-logger
package org.nuxeo.security.logger; import java.security.Principal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; 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.model.Document; import org.nuxeo.ecm.core.query.sql.model.SQLQuery.Transformer; import org.nuxeo.ecm.core.security.AbstractSecurityPolicy; import org.nuxeo.ecm.core.security.SecurityPolicy; public class LogingSecurityPolicy extends AbstractSecurityPolicy implements SecurityPolicy { protected static final Log log = LogFactory.getLog(LogingSecurityPolicy.class); @Override public Transformer getQueryTransformer(String repositoryName) { return Transformer.IDENTITY; } @Override public QueryTransformer getQueryTransformer(String repositoryName, String queryLanguage) { return QueryTransformer.IDENTITY; } @Override public boolean isExpressibleInQuery(String repositoryName) { return true; } @Override public Access checkPermission(Document doc, ACP mergedAcp, Principal principal, String permission, String[] resolvedPermissions, String[] additionalPrincipals) { StringBuffer sb = new StringBuffer(); sb.append("target="); try { sb.append(doc.getPath().toString()); } catch (Exception e) { sb.append(doc.getUUID()); } sb.append(";checked permissions= "); sb.append(permission); sb.append(";principal= "); sb.append(principal.getName()); sb.append("\n mergedACL= "); sb.append(dumpACP(mergedAcp)); sb.append(" resolvedPermissions= ["); for (String p : resolvedPermissions) { sb.append(p); sb.append(","); } sb.append("]"); sb.append("\n"); sb.append(" groups= ["); for (String p : additionalPrincipals) { sb.append(p); sb.append(","); } sb.append("]"); log.info("Permission check :" + sb.toString()); return Access.UNKNOWN; } protected String dumpACP(ACP acp){ StringBuffer sb = new StringBuffer(); for (ACL acl : acp.getACLs()) { sb.append(acl.getName()); sb.append(" : ("); for (ACE ace : acl.getACEs()) { sb.append(ace.toString()); sb.append(";"); } sb.append(")\n"); } return sb.toString(); } }
src/main/java/org/nuxeo/security/logger/LogingSecurityPolicy.java
package org.nuxeo.security.logger; import java.security.Principal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuxeo.ecm.core.api.security.ACP; import org.nuxeo.ecm.core.api.security.Access; import org.nuxeo.ecm.core.model.Document; import org.nuxeo.ecm.core.query.sql.model.SQLQuery.Transformer; import org.nuxeo.ecm.core.security.AbstractSecurityPolicy; import org.nuxeo.ecm.core.security.SecurityPolicy; public class LogingSecurityPolicy extends AbstractSecurityPolicy implements SecurityPolicy { protected static final Log log = LogFactory.getLog(LogingSecurityPolicy.class); @Override public Transformer getQueryTransformer(String repositoryName) { return Transformer.IDENTITY; } @Override public QueryTransformer getQueryTransformer(String repositoryName, String queryLanguage) { return QueryTransformer.IDENTITY; } @Override public boolean isExpressibleInQuery(String repositoryName) { return true; } @Override public Access checkPermission(Document doc, ACP mergedAcp, Principal principal, String permission, String[] resolvedPermissions, String[] additionalPrincipals) { StringBuffer sb = new StringBuffer(); sb.append("target="); try { sb.append(doc.getPath().toString()); } catch (Exception e) { sb.append(doc.getUUID()); } sb.append(";checked permissions= "); sb.append(permission); sb.append(";principal= "); sb.append(principal.getName()); sb.append("\n"); sb.append(" resolvedPermissions= ["); for (String p : resolvedPermissions) { sb.append(p); sb.append(","); } sb.append("]"); sb.append("\n"); sb.append(" groups= ["); for (String p : additionalPrincipals) { sb.append(p); sb.append(","); } sb.append("]"); log.info("Permission check :" + sb.toString()); return Access.UNKNOWN; } }
Add more logs to get info on ACLs
src/main/java/org/nuxeo/security/logger/LogingSecurityPolicy.java
Add more logs to get info on ACLs
<ide><path>rc/main/java/org/nuxeo/security/logger/LogingSecurityPolicy.java <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <add>import org.nuxeo.ecm.core.api.security.ACE; <add>import org.nuxeo.ecm.core.api.security.ACL; <ide> import org.nuxeo.ecm.core.api.security.ACP; <ide> import org.nuxeo.ecm.core.api.security.Access; <ide> import org.nuxeo.ecm.core.model.Document; <ide> import org.nuxeo.ecm.core.query.sql.model.SQLQuery.Transformer; <ide> import org.nuxeo.ecm.core.security.AbstractSecurityPolicy; <ide> import org.nuxeo.ecm.core.security.SecurityPolicy; <add> <add> <ide> <ide> public class LogingSecurityPolicy extends AbstractSecurityPolicy implements SecurityPolicy { <ide> <ide> } <ide> sb.append(";checked permissions= "); <ide> sb.append(permission); <add> <ide> sb.append(";principal= "); <ide> sb.append(principal.getName()); <ide> <del> sb.append("\n"); <add> sb.append("\n mergedACL= "); <add> sb.append(dumpACP(mergedAcp)); <add> <ide> sb.append(" resolvedPermissions= ["); <ide> for (String p : resolvedPermissions) { <ide> sb.append(p); <ide> sb.append(","); <ide> } <ide> sb.append("]"); <del> <ide> <ide> sb.append("\n"); <ide> sb.append(" groups= ["); <ide> return Access.UNKNOWN; <ide> } <ide> <add> protected String dumpACP(ACP acp){ <add> StringBuffer sb = new StringBuffer(); <add> for (ACL acl : acp.getACLs()) { <add> sb.append(acl.getName()); <add> sb.append(" : ("); <add> for (ACE ace : acl.getACEs()) { <add> sb.append(ace.toString()); <add> sb.append(";"); <add> } <add> sb.append(")\n"); <add> } <add> return sb.toString(); <add> } <ide> }
Java
mit
ed915a8a86e09205bd56bfdbda52b7cb259d31bd
0
godotgildor/igv,godotgildor/igv,itenente/igv,igvteam/igv,godotgildor/igv,godotgildor/igv,amwenger/igv,amwenger/igv,itenente/igv,amwenger/igv,igvteam/igv,godotgildor/igv,amwenger/igv,itenente/igv,igvteam/igv,amwenger/igv,itenente/igv,igvteam/igv,igvteam/igv,itenente/igv
/* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ package org.broad.igv.util; import biz.source_code.base64Coder.Base64Coder; import htsjdk.samtools.seekablestream.SeekableStream; import htsjdk.samtools.util.ftp.FTPClient; import htsjdk.samtools.util.ftp.FTPStream; import org.apache.log4j.Logger; import org.apache.tomcat.util.HttpDate; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.exceptions.HttpResponseException; import org.broad.igv.gs.GSUtils; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.CancellableProgressDialog; import org.broad.igv.ui.util.ProgressMonitor; import org.broad.igv.util.collections.CI; import org.broad.igv.util.ftp.FTPUtils; import org.broad.igv.util.stream.IGVSeekableHTTPStream; import org.broad.igv.util.stream.IGVUrlHelper; import javax.net.ssl.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.List; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; /** * Wrapper utility class... for interacting with HttpURLConnection. * * @author Jim Robinson * @date 9/22/11 */ public class HttpUtils { private static Logger log = Logger.getLogger(HttpUtils.class); private static HttpUtils instance; private Map<String, Boolean> byteRangeTestMap; private ProxySettings proxySettings = null; private final int MAX_REDIRECTS = 5; private String defaultUserName = null; private char[] defaultPassword = null; private static Pattern URLmatcher = Pattern.compile(".{1,8}://.*"); // static provided to support unit testing private static boolean BYTE_RANGE_DISABLED = false; private Map<URL, Boolean> headURLCache = new HashMap<URL, Boolean>(); /** * @return the single instance */ public static HttpUtils getInstance() { if (instance == null) { instance = new HttpUtils(); } return instance; } private HttpUtils() { htsjdk.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class); if(!Globals.checkJavaVersion("1.8")) { disableCertificateValidation(); } CookieHandler.setDefault(new IGVCookieManager()); Authenticator.setDefault(new IGVAuthenticator()); try { System.setProperty("java.net.useSystemProxies", "true"); } catch (Exception e) { log.info("Couldn't set useSystemProxies=true"); } byteRangeTestMap = Collections.synchronizedMap(new HashMap()); } public static boolean isRemoteURL(String string) { String lcString = string.toLowerCase(); return lcString.startsWith("http://") || lcString.startsWith("https://") || lcString.startsWith("ftp://"); } /** * Provided to support unit testing (force disable byte range requests) * * @return */ public static void disableByteRange(boolean b) { BYTE_RANGE_DISABLED = b; } /** * Return the contents of the url as a String. This method should only be used for queries expected to return * a small amount of data. * * @param url * @return * @throws IOException */ public String getContentsAsString(URL url) throws IOException { InputStream is = null; HttpURLConnection conn = openConnection(url, null); try { is = getInputStream(conn); return readContents(is); } catch (IOException e) { readErrorStream(conn); // Consume content throw e; } finally { if (is != null) is.close(); } } public String getContentsAsJSON(URL url) throws IOException { InputStream is = null; Map<String, String> reqProperties = new HashMap(); reqProperties.put("Accept", "application/json,text/plain"); HttpURLConnection conn = openConnection(url, reqProperties); try { is = getInputStream(conn); return readContents(is); } catch (IOException e) { readErrorStream(conn); // Consume content throw e; } finally { if (is != null) is.close(); } } public String doPost(URL url, Map<String, String> params) throws IOException { StringBuilder postData = new StringBuilder(); for (Map.Entry<String, String> param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(param.getKey()); postData.append('='); postData.append(param.getValue()); } byte[] postDataBytes = postData.toString().getBytes(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); StringBuilder response = new StringBuilder(); Reader in = new BufferedReader(new InputStreamReader(getInputStream(conn), "UTF-8")); for (int c; (c = in.read()) >= 0; ) { response.append((char) c); } return response.toString(); } /** * Open a connection stream for the URL. * * @param url * @return * @throws IOException */ public InputStream openConnectionStream(URL url) throws IOException { log.debug("Opening connection stream to " + url); if (url.getProtocol().toLowerCase().equals("ftp")) { String userInfo = url.getUserInfo(); String host = url.getHost(); String file = url.getPath(); FTPClient ftp = FTPUtils.connect(host, userInfo, new UserPasswordInputImpl()); ftp.pasv(); ftp.retr(file); return new FTPStream(ftp); } else { return openConnectionStream(url, null); } } public InputStream openConnectionStream(URL url, Map<String, String> requestProperties) throws IOException { HttpURLConnection conn = openConnection(url, requestProperties); if (conn == null) { return null; } boolean rangeRequestedNotReceived = isExpectedRangeMissing(conn, requestProperties); if (rangeRequestedNotReceived) { String msg = "Byte range requested, but no Content-Range header in response"; log.error(msg); // if(Globals.isTesting()){ // throw new IOException(msg); // } } try { InputStream input = getInputStream(conn); return input; } catch (IOException e) { readErrorStream(conn); // Consume content throw e; } } private InputStream getInputStream(HttpURLConnection conn) throws IOException { InputStream input = conn.getInputStream(); // if ("gzip".equals(conn.getContentEncoding())) { // input = new GZIPInputStream(input); // } return input; } boolean isExpectedRangeMissing(URLConnection conn, Map<String, String> requestProperties) { final boolean rangeRequested = (requestProperties != null) && (new CI.CIHashMap<String>(requestProperties)).containsKey("Range"); if (!rangeRequested) return false; Map<String, List<String>> headerFields = conn.getHeaderFields(); boolean rangeReceived = (headerFields != null) && (new CI.CIHashMap<List<String>>(headerFields)).containsKey("Content-Range"); return !rangeReceived; } public boolean resourceAvailable(URL url) { log.debug("Checking if resource is available: " + url); if (url.getProtocol().toLowerCase().equals("ftp")) { return FTPUtils.resourceAvailable(url); } else { try { HttpURLConnection conn = openConnectionHeadOrGet(url); int code = conn.getResponseCode(); return code >= 200 && code < 300; } catch (Exception e) { return false; } } } /** * First tries a HEAD request, then a GET request if the HEAD fails. * If the GET fails, the exception is thrown * * @param url * @return * @throws IOException */ private HttpURLConnection openConnectionHeadOrGet(URL url) throws IOException { // Keep track of urls for which "HEAD" does not work (e.g. Amazon with signed urls). boolean tryHead = headURLCache.containsKey(url) ? headURLCache.get(url) : true; if (tryHead) { try { HttpURLConnection conn = openConnection(url, null, "HEAD"); headURLCache.put(url, true); return conn; } catch (IOException e) { if (e instanceof FileNotFoundException) { throw e; } log.info("HEAD request failed for url: " + url.toExternalForm() + ". Trying GET"); headURLCache.put(url, false); } } return openConnection(url, null, "GET"); } public String getHeaderField(URL url, String key) throws IOException { HttpURLConnection conn = openConnectionHeadOrGet(url); if (conn == null) return null; return conn.getHeaderField(key); } public long getLastModified(URL url) throws IOException { HttpURLConnection conn = openConnectionHeadOrGet(url); if (conn == null) return 0; return conn.getLastModified(); } public long getContentLength(URL url) throws IOException { try { String contentLengthString = getHeaderField(url, "Content-Length"); if (contentLengthString == null) { return -1; } else { return Long.parseLong(contentLengthString); } } catch (Exception e) { log.error("Error fetching content length", e); return -1; } } /** * Compare a local and remote resource, returning true if it is believed that the * remote file is newer than the local file * * @param file * @param url * @param compareContentLength Whether to use the content length to compare files. If false, only * the modified date is used * @return true if the files are the same or the local file is newer, false if the remote file has been modified wrt the local one. * @throws IOException */ public boolean remoteIsNewer(File file, URL url, boolean compareContentLength) throws IOException { if (!file.exists()) { return false; } HttpURLConnection conn = openConnection(url, null, "HEAD"); // Check content-length first long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { try { contentLength = Long.parseLong(contentLengthString); } catch (NumberFormatException e) { log.error("Error parsing content-length string: " + contentLengthString + " from URL: " + url.toString()); contentLength = -1; } } if (contentLength != file.length()) { return true; } // Compare last-modified dates String lastModifiedString = conn.getHeaderField("Last-Modified"); if (lastModifiedString == null) { return false; } else { HttpDate date = new HttpDate(); date.parse(lastModifiedString); long remoteModifiedTime = date.getTime(); long localModifiedTime = file.lastModified(); return remoteModifiedTime > localModifiedTime; } } public void updateProxySettings() { boolean useProxy; String proxyHost; int proxyPort = -1; boolean auth = false; String user = null; String pw = null; PreferenceManager prefMgr = PreferenceManager.getInstance(); useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY); proxyHost = prefMgr.get(PreferenceManager.PROXY_HOST, null); try { proxyPort = Integer.parseInt(prefMgr.get(PreferenceManager.PROXY_PORT, "-1")); } catch (NumberFormatException e) { proxyPort = -1; } auth = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE); user = prefMgr.get(PreferenceManager.PROXY_USER, null); String pwString = prefMgr.get(PreferenceManager.PROXY_PW, null); if (pwString != null) { pw = Utilities.base64Decode(pwString); } String proxyTypeString = prefMgr.get(PreferenceManager.PROXY_TYPE, "HTTP"); Proxy.Type type = Proxy.Type.valueOf(proxyTypeString.trim().toUpperCase()); proxySettings = new ProxySettings(useProxy, user, pw, auth, proxyHost, proxyPort, type); } /** * Get the system defined proxy defined for the URI, or null if * not available. May also return a {@code Proxy} object which * represents a direct connection * * @param uri * @return */ private Proxy getSystemProxy(String uri) { try { log.debug("Getting system proxy for " + uri); ProxySelector selector = ProxySelector.getDefault(); List<Proxy> proxyList = selector.select(new URI(uri)); return proxyList.get(0); } catch (URISyntaxException e) { log.error(e.getMessage(), e); return null; } catch (NullPointerException e) { return null; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * Calls {@link #downloadFile(String, java.io.File, Frame, String)} * with {@code dialogsParent = null, title = null} * * @param url * @param outputFile * @return RunnableResult * @throws IOException */ public RunnableResult downloadFile(String url, File outputFile) throws IOException { URLDownloader downloader = downloadFile(url, outputFile, null, null); return downloader.getResult(); } /** * @param url * @param outputFile * @param dialogsParent Parent of dialog to show progress. If null, none shown * @return URLDownloader used to perform download * @throws IOException */ public URLDownloader downloadFile(String url, File outputFile, Frame dialogsParent, String dialogTitle) throws IOException { final URLDownloader urlDownloader = new URLDownloader(url, outputFile); boolean showProgressDialog = dialogsParent != null; if (!showProgressDialog) { urlDownloader.run(); return urlDownloader; } else { ProgressMonitor monitor = new ProgressMonitor(); urlDownloader.setMonitor(monitor); ActionListener buttonListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { urlDownloader.cancel(true); } }; String permText = "Downloading " + url; String title = dialogTitle != null ? dialogTitle : permText; CancellableProgressDialog dialog = CancellableProgressDialog.showCancellableProgressDialog(dialogsParent, title, buttonListener, false, monitor); dialog.setPermText(permText); Dimension dms = new Dimension(600, 150); dialog.setPreferredSize(dms); dialog.setSize(dms); dialog.validate(); LongRunningTask.submit(urlDownloader); return urlDownloader; } } public void uploadGenomeSpaceFile(String uri, File file, Map<String, String> headers) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; URL url = new URL(uri); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int i; // read byte by byte until end of stream while ((i = bis.read()) > 0) { bos.write(i); } bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. if (responseCode >= 400) { String message = readErrorStream(urlconnection); throw new IOException("Error uploading " + file.getName() + " : " + message); } } public String createGenomeSpaceDirectory(URL url, String body) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("Content-Length", String.valueOf(body.getBytes().length)); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); bos.write(body.getBytes()); bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. StringBuffer buf = new StringBuffer(); InputStream inputStream; if (responseCode >= 200 && responseCode < 300) { inputStream = getInputStream(urlconnection); } else { inputStream = urlconnection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String nextLine; while ((nextLine = br.readLine()) != null) { buf.append(nextLine); buf.append('\n'); } inputStream.close(); if (responseCode >= 200 && responseCode < 300) { return buf.toString(); } else { throw new IOException("Error creating GS directory: " + buf.toString()); } } /** * Code for disabling SSL certification */ private void disableCertificateValidation() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (NoSuchAlgorithmException e) { } catch (KeyManagementException e) { } // Install a callback to allow the igv Amazon and local hosts HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { if (hostname.equals("igv.broadinstitute.org") || hostname.equals("igvdata.broadinstitute.org") || hostname.equals("localhost")) return true; return true; } }); } private String readContents(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) >= 0) { bos.write(b); } return new String(bos.toByteArray()); } private String readErrorStream(HttpURLConnection connection) throws IOException { InputStream inputStream = null; try { inputStream = connection.getErrorStream(); if (inputStream == null) { return null; } return readContents(inputStream); } finally { if (inputStream != null) inputStream.close(); } } public HttpURLConnection delete(URL url) throws IOException { return openConnection(url, Collections.<String, String>emptyMap(), "DELETE"); } HttpURLConnection openConnection(URL url, Map<String, String> requestProperties) throws IOException { return openConnection(url, requestProperties, "GET"); } private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method) throws IOException { return openConnection(url, requestProperties, method, 0); } /** * The "real" connection method * * @param url * @param requestProperties * @param method * @return * @throws java.io.IOException */ private HttpURLConnection openConnection( URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { //Encode query string portions url = StringUtils.encodeURLQueryString(url); if (log.isTraceEnabled()) { log.trace(url); } //Encode base portions. Right now just spaces, most common case //TODO This is a hack and doesn't work for all characters which need it if (StringUtils.countChar(url.toExternalForm(), ' ') > 0) { String newPath = url.toExternalForm().replaceAll(" ", "%20"); url = new URL(newPath); } Proxy sysProxy = null; boolean igvProxySettingsExist = proxySettings != null && proxySettings.useProxy; //Only check for system proxy if igv proxy settings not found if (!igvProxySettingsExist) { sysProxy = getSystemProxy(url.toExternalForm()); } boolean useProxy = sysProxy != null || igvProxySettingsExist; HttpURLConnection conn; if (useProxy) { Proxy proxy = sysProxy; if (igvProxySettingsExist) { if (proxySettings.type == Proxy.Type.DIRECT) { proxy = Proxy.NO_PROXY; } else { proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); } } conn = (HttpURLConnection) url.openConnection(proxy); if (igvProxySettingsExist && proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes)); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { conn.setRequestProperty("Accept", "application/json,text/plain"); } else { if (!"HEAD".equals(method)) conn.setRequestProperty("Accept", "text/plain"); } //------// //There seems to be a bug with JWS caches //So we avoid caching //This default is persistent, really should be available statically but isn't conn.setDefaultUseCaches(false); conn.setUseCaches(false); //------// conn.setConnectTimeout(Globals.CONNECT_TIMEOUT); conn.setReadTimeout(Globals.READ_TIMEOUT); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "Keep-Alive"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } conn.setRequestProperty("User-Agent", Globals.applicationString()); if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); if (log.isDebugEnabled()) { //logHeaders(conn); } // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code >= 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); log.debug("Redirecting to " + newLocation); return openConnection(new URL(newLocation), requestProperties, method, ++redirectCount); } // TODO -- handle other response codes. else if (code >= 400) { String message; if (code == 404) { message = "File not found: " + url.toString(); throw new FileNotFoundException(message); } else if (code == 401) { // Looks like this only happens when user hits "Cancel". // message = "Not authorized to view this file"; // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE); redirectCount = MAX_REDIRECTS + 1; return null; } else { message = conn.getResponseMessage(); } String details = readErrorStream(conn); log.error("URL: " + url.toExternalForm() + ". error stream: " + details); log.error("Code: " + code + ". " + message); HttpResponseException exc = new HttpResponseException(code); throw exc; } } return conn; } //Used for testing sometimes, please do not delete private void logHeaders(HttpURLConnection conn) { Map<String, List<String>> headerFields = conn.getHeaderFields(); log.debug("Headers for " + conn.getURL()); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { log.debug(header.getKey() + ": " + StringUtils.join(header.getValue(), ",")); } } public void setDefaultPassword(String defaultPassword) { this.defaultPassword = defaultPassword.toCharArray(); } public void setDefaultUserName(String defaultUserName) { this.defaultUserName = defaultUserName; } public void clearDefaultCredentials() { this.defaultPassword = null; this.defaultUserName = null; } /** * Test to see if this client can successfully retrieve a portion of a remote file using the byte-range header. * This is not a test of the server, but the client. In some environments the byte-range header gets removed * by filters after the request is made by IGV. * * @return */ public boolean useByteRange(URL url) { if (BYTE_RANGE_DISABLED) return false; // We can test byte-range success for hosts we can reach. synchronized (byteRangeTestMap) { final String host = url.getHost(); if (byteRangeTestMap.containsKey(host)) { return byteRangeTestMap.get(host); } else { SeekableStream str = null; try { boolean byteRangeTestSuccess = true; if (host.contains("broadinstitute.org")) { byteRangeTestSuccess = testBroadHost(host); } else { // Non-broad URL int l = (int) Math.min(1000, HttpUtils.getInstance().getContentLength(url)); if (l > 100) { byte[] firstBytes = new byte[l]; str = new IGVSeekableHTTPStream(url); str.readFully(firstBytes); int end = firstBytes.length; int start = end - 100; str.seek(start); int len = end - start; byte[] buffer = new byte[len]; int n = 0; while (n < len) { int count = str.read(buffer, n, len - n); if (count < 0) throw new EOFException(); n += count; } for (int i = 0; i < len; i++) { if (buffer[i] != firstBytes[i + start]) { byteRangeTestSuccess = false; break; } } } else { // Too small a sample to test, or unknown content length. Return "true" but don't record // this host as tested. return true; } } if (byteRangeTestSuccess) { log.info("Range-byte request succeeded"); } else { log.info("Range-byte test failed -- problem with client network environment."); } byteRangeTestMap.put(host, byteRangeTestSuccess); return byteRangeTestSuccess; } catch (IOException e) { log.error("Error while testing byte range " + e.getMessage()); // We could not reach the test server, so we can't know if this client can do byte-range tests or // not. Take the "optimistic" view. return true; } finally { if (str != null) try { str.close(); } catch (IOException e) { log.error("Error closing stream (" + url.toExternalForm() + ")", e); } } } } } private boolean testBroadHost(String host) throws IOException { // Test broad urls for successful byte range requests. log.info("Testing range-byte request on host: " + host); String testURL; if (host.startsWith("igvdata.broadinstitute.org")) { // Amazon cloud front testURL = "http://igvdata.broadinstitute.org/genomes/seq/hg19/chr12.txt"; } else if (host.startsWith("igv.broadinstitute.org")) { // Amazon S3 testURL = "http://igv.broadinstitute.org/genomes/seq/hg19/chr12.txt"; } else { // All others testURL = "http://www.broadinstitute.org/igvdata/annotations/seq/hg19/chr12.txt"; } byte[] expectedBytes = {'T', 'C', 'G', 'C', 'T', 'T', 'G', 'A', 'A', 'C', 'C', 'C', 'G', 'G', 'G', 'A', 'G', 'A', 'G', 'G'}; IGVSeekableHTTPStream str = null; try { str = new IGVSeekableHTTPStream(new URL(testURL)); str.seek(25350000); byte[] buffer = new byte[80000]; str.read(buffer); String result = new String(buffer); for (int i = 0; i < expectedBytes.length; i++) { if (buffer[i] != expectedBytes[i]) { return false; } } return true; } finally { if (str != null) str.close(); } } public void shutdown() { // Do any cleanup required here } /** * Checks if the string is a URL (not necessarily remote, can be any protocol) * * @param f * @return */ public static boolean isURL(String f) { return f.startsWith("http:") || f.startsWith("ftp:") || f.startsWith("https:") || URLmatcher.matcher(f).matches(); } public static Map<String, String> parseQueryString(String query) { String[] params = query.split("&"); Map<String, String> map = new HashMap<String, String>(); for (String param : params) { String[] name_val = param.split("=", 2); if (name_val.length == 2) { map.put(name_val[0], name_val[1]); } } return map; } public static class ProxySettings { boolean auth = false; String user; String pw; boolean useProxy; String proxyHost; int proxyPort = -1; Proxy.Type type; public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort) { this(useProxy, user, pw, auth, proxyHost, proxyPort, Proxy.Type.HTTP); this.auth = auth; } public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort, Proxy.Type proxyType) { this.auth = auth; this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.pw = pw; this.useProxy = useProxy; this.user = user; this.type = proxyType; } } /** * The default authenticator */ public class IGVAuthenticator extends Authenticator { Hashtable<String, PasswordAuthentication> pwCache = new Hashtable<String, PasswordAuthentication>(); HashSet<String> cacheAttempts = new HashSet<String>(); /** * Called when password authentication is needed. * * @return */ @Override protected synchronized PasswordAuthentication getPasswordAuthentication() { RequestorType type = getRequestorType(); String urlString = getRequestingURL().toString(); boolean isProxyChallenge = type == RequestorType.PROXY; // Cache user entered PWs. In normal use this shouldn't be necessary as credentials are cached upstream, // but if loading many files in parallel (e.g. from sessions) calls to this method can queue up before the // user enters their credentials, causing needless reentry. String pKey = type.toString() + getRequestingProtocol() + getRequestingHost(); PasswordAuthentication pw = pwCache.get(pKey); if (pw != null) { // Prevents infinite loop if credentials are incorrect if (cacheAttempts.contains(urlString)) { cacheAttempts.remove(urlString); } else { cacheAttempts.add(urlString); return pw; } } if (isProxyChallenge) { if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { return new PasswordAuthentication(proxySettings.user, proxySettings.pw.toCharArray()); } } if (defaultUserName != null && defaultPassword != null) { return new PasswordAuthentication(defaultUserName, defaultPassword); } Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null; boolean isGenomeSpace = GSUtils.isGenomeSpace(getRequestingURL()); if (isGenomeSpace) { // If we are being challenged by GS the token must be bad/expired GSUtils.logout(); } LoginDialog dlg = new LoginDialog(owner, isGenomeSpace, urlString, isProxyChallenge); dlg.setVisible(true); if (dlg.isCanceled()) { return null; } else { final String userString = dlg.getUsername(); final char[] userPass = dlg.getPassword(); if (isProxyChallenge) { proxySettings.user = userString; proxySettings.pw = new String(userPass); } pw = new PasswordAuthentication(userString, userPass); pwCache.put(pKey, pw); return pw; } } } /** * Runnable for downloading a file from a URL. * Downloading is buffered, and can be cancelled (between buffers) * via {@link #cancel(boolean)} */ public class URLDownloader implements Runnable { private ProgressMonitor monitor = null; private final URL srcUrl; private final File outputFile; private volatile boolean started = false; private volatile boolean done = false; private volatile boolean cancelled = false; private volatile RunnableResult result; public URLDownloader(String url, File outputFile) throws MalformedURLException { this.srcUrl = new URL(url); this.outputFile = outputFile; } @Override public void run() { if (this.cancelled) { return; } started = true; try { this.result = doDownload(); } catch (IOException e) { log.error(e.getMessage(), e); } finally { this.done(); } } /** * Return the result. Must be called after run is complete * * @return */ public RunnableResult getResult() { if (!this.done) throw new IllegalStateException("Must wait for run to finish before getting result"); return this.result; } private RunnableResult doDownload() throws IOException { log.info("Downloading " + srcUrl + " to " + outputFile.getAbsolutePath()); HttpURLConnection conn = openConnection(this.srcUrl, null); long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } InputStream is = null; OutputStream out = null; long downloaded = 0; long downSinceLast = 0; String curStatus; String msg1 = String.format("downloaded of %s total", contentLength >= 0 ? bytesToByteCountString(contentLength) : "unknown"); int perc = 0; try { is = getInputStream(conn); out = new FileOutputStream(outputFile); byte[] buf = new byte[64 * 1024]; int counter = 0; int interval = 100; int bytesRead = 0; while (!this.cancelled && (bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); downloaded += bytesRead; downSinceLast += bytesRead; counter = (counter + 1) % interval; if (counter == 0 && this.monitor != null) { curStatus = String.format("%s %s", bytesToByteCountString(downloaded), msg1); this.monitor.updateStatus(curStatus); if (contentLength >= 0) { perc = (int) ((downSinceLast * 100) / contentLength); this.monitor.fireProgressChange(perc); if (perc >= 1) downSinceLast = 0; } } } log.info("Download complete. Total bytes downloaded = " + downloaded); } catch (IOException e) { readErrorStream(conn); throw e; } finally { if (is != null) is.close(); if (out != null) { out.flush(); out.close(); } } long fileLength = outputFile.length(); if (this.cancelled) return RunnableResult.CANCELLED; boolean knownComplete = contentLength == fileLength; //Assume success if file length not known if (knownComplete || contentLength < 0) { if (this.monitor != null) { this.monitor.fireProgressChange(100); this.monitor.updateStatus("Done"); } return RunnableResult.SUCCESS; } else { return RunnableResult.FAILURE; } } protected void done() { this.done = true; } public boolean isDone() { return this.done; } /** * See {@link java.util.concurrent.FutureTask#cancel(boolean)} * * @param mayInterruptIfRunning * @return */ public boolean cancel(boolean mayInterruptIfRunning) { if (this.started && !mayInterruptIfRunning) { return false; } this.cancelled = true; return true; } public void setMonitor(ProgressMonitor monitor) { this.monitor = monitor; } /** * Convert bytes to human-readable string. * e.g. 102894 -> 102.89 KB. If too big or too small, * doesn't append a prefix just returns {@code bytes + " B"} * * @param bytes * @return */ public String bytesToByteCountString(long bytes) { int unit = 1000; String prefs = "KMGT"; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); if (exp <= 0 || exp >= prefs.length()) return bytes + " B"; String pre = (prefs).charAt(exp - 1) + ""; return String.format("%.2f %sB", bytes / Math.pow(unit, exp), pre); } } /** * Provide override for unit tests */ public void setAuthenticator(Authenticator authenticator) { Authenticator.setDefault(authenticator); } /** * For unit tests */ public void resetAuthenticator() { Authenticator.setDefault(new IGVAuthenticator()); } /** * Extension of CookieManager that grabs cookies from the GenomeSpace identity server to store locally. * This is to support the GenomeSpace "single sign-on". Examples ... * gs-username=igvtest; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/ * gs-token=HnR9rBShNO4dTXk8cKXVJT98Oe0jWVY+; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/ */ static class IGVCookieManager extends CookieHandler { CookieManager wrappedManager; public IGVCookieManager() { wrappedManager = new CookieManager(); } @Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException { Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.putAll(wrappedManager.get(uri, requestHeaders)); if (GSUtils.isGenomeSpace(uri.toURL())) { String token = GSUtils.getGSToken(); if (token != null) { List<String> cookieList = headers.get("Cookie"); boolean needsTokenCookie = true; boolean needsToolCookie = true; if (cookieList == null) { cookieList = new ArrayList<String>(1); headers.put("Cookie", cookieList); } for (String cookie : cookieList) { if (cookie.startsWith("gs-token")) { needsTokenCookie = false; } else if (cookie.startsWith("gs-toolname")) { needsToolCookie = false; } } if (needsTokenCookie) { cookieList.add("gs-token=" + token); } if (needsToolCookie) { cookieList.add("gs-toolname=IGV"); } } } return Collections.unmodifiableMap(headers); } @Override public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException { String urilc = uri.toString().toLowerCase(); if (urilc.contains("identity") && urilc.contains("genomespace")) { List<String> cookies = responseHeaders.get("Set-Cookie"); if (cookies != null) { for (String cstring : cookies) { List<HttpCookie> cookieList = HttpCookie.parse(cstring); for (HttpCookie cookie : cookieList) { String cookieName = cookie.getName(); String value = cookie.getValue(); if (cookieName.equals("gs-token")) { //log.debug("gs-token: " + value); GSUtils.setGSToken(value); } else if (cookieName.equals("gs-username")) { //log.debug("gs-username: " + value); GSUtils.setGSUser(value); } } } } } wrappedManager.put(uri, responseHeaders); } } }
src/org/broad/igv/util/HttpUtils.java
/* * Copyright (c) 2007-2012 The Broad Institute, Inc. * SOFTWARE COPYRIGHT NOTICE * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved. * * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality. * * This software is licensed under the terms of the GNU Lesser General Public License (LGPL), * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php. */ package org.broad.igv.util; import biz.source_code.base64Coder.Base64Coder; import htsjdk.samtools.seekablestream.SeekableStream; import htsjdk.samtools.util.ftp.FTPClient; import htsjdk.samtools.util.ftp.FTPStream; import org.apache.log4j.Logger; import org.apache.tomcat.util.HttpDate; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.exceptions.HttpResponseException; import org.broad.igv.gs.GSUtils; import org.broad.igv.ui.IGV; import org.broad.igv.ui.util.CancellableProgressDialog; import org.broad.igv.ui.util.ProgressMonitor; import org.broad.igv.util.collections.CI; import org.broad.igv.util.ftp.FTPUtils; import org.broad.igv.util.stream.IGVSeekableHTTPStream; import org.broad.igv.util.stream.IGVUrlHelper; import javax.net.ssl.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.List; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; /** * Wrapper utility class... for interacting with HttpURLConnection. * * @author Jim Robinson * @date 9/22/11 */ public class HttpUtils { private static Logger log = Logger.getLogger(HttpUtils.class); private static HttpUtils instance; private Map<String, Boolean> byteRangeTestMap; private ProxySettings proxySettings = null; private final int MAX_REDIRECTS = 5; private String defaultUserName = null; private char[] defaultPassword = null; private static Pattern URLmatcher = Pattern.compile(".{1,8}://.*"); // static provided to support unit testing private static boolean BYTE_RANGE_DISABLED = false; private Map<URL, Boolean> headURLCache = new HashMap<URL, Boolean>(); /** * @return the single instance */ public static HttpUtils getInstance() { if (instance == null) { instance = new HttpUtils(); } return instance; } private HttpUtils() { htsjdk.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class); // disableCertificateValidation(); CookieHandler.setDefault(new IGVCookieManager()); Authenticator.setDefault(new IGVAuthenticator()); try { System.setProperty("java.net.useSystemProxies", "true"); } catch (Exception e) { log.info("Couldn't set useSystemProxies=true"); } byteRangeTestMap = Collections.synchronizedMap(new HashMap()); } public static boolean isRemoteURL(String string) { String lcString = string.toLowerCase(); return lcString.startsWith("http://") || lcString.startsWith("https://") || lcString.startsWith("ftp://"); } /** * Provided to support unit testing (force disable byte range requests) * * @return */ public static void disableByteRange(boolean b) { BYTE_RANGE_DISABLED = b; } /** * Return the contents of the url as a String. This method should only be used for queries expected to return * a small amount of data. * * @param url * @return * @throws IOException */ public String getContentsAsString(URL url) throws IOException { InputStream is = null; HttpURLConnection conn = openConnection(url, null); try { is = getInputStream(conn); return readContents(is); } catch (IOException e) { readErrorStream(conn); // Consume content throw e; } finally { if (is != null) is.close(); } } public String getContentsAsJSON(URL url) throws IOException { InputStream is = null; Map<String, String> reqProperties = new HashMap(); reqProperties.put("Accept", "application/json,text/plain"); HttpURLConnection conn = openConnection(url, reqProperties); try { is = getInputStream(conn); return readContents(is); } catch (IOException e) { readErrorStream(conn); // Consume content throw e; } finally { if (is != null) is.close(); } } public String doPost(URL url, Map<String, String> params) throws IOException { StringBuilder postData = new StringBuilder(); for (Map.Entry<String, String> param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(param.getKey()); postData.append('='); postData.append(param.getValue()); } byte[] postDataBytes = postData.toString().getBytes(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); StringBuilder response = new StringBuilder(); Reader in = new BufferedReader(new InputStreamReader(getInputStream(conn), "UTF-8")); for (int c; (c = in.read()) >= 0; ) { response.append((char) c); } return response.toString(); } /** * Open a connection stream for the URL. * * @param url * @return * @throws IOException */ public InputStream openConnectionStream(URL url) throws IOException { log.debug("Opening connection stream to " + url); if (url.getProtocol().toLowerCase().equals("ftp")) { String userInfo = url.getUserInfo(); String host = url.getHost(); String file = url.getPath(); FTPClient ftp = FTPUtils.connect(host, userInfo, new UserPasswordInputImpl()); ftp.pasv(); ftp.retr(file); return new FTPStream(ftp); } else { return openConnectionStream(url, null); } } public InputStream openConnectionStream(URL url, Map<String, String> requestProperties) throws IOException { HttpURLConnection conn = openConnection(url, requestProperties); if (conn == null) { return null; } boolean rangeRequestedNotReceived = isExpectedRangeMissing(conn, requestProperties); if (rangeRequestedNotReceived) { String msg = "Byte range requested, but no Content-Range header in response"; log.error(msg); // if(Globals.isTesting()){ // throw new IOException(msg); // } } try { InputStream input = getInputStream(conn); return input; } catch (IOException e) { readErrorStream(conn); // Consume content throw e; } } private InputStream getInputStream(HttpURLConnection conn) throws IOException { InputStream input = conn.getInputStream(); // if ("gzip".equals(conn.getContentEncoding())) { // input = new GZIPInputStream(input); // } return input; } boolean isExpectedRangeMissing(URLConnection conn, Map<String, String> requestProperties) { final boolean rangeRequested = (requestProperties != null) && (new CI.CIHashMap<String>(requestProperties)).containsKey("Range"); if (!rangeRequested) return false; Map<String, List<String>> headerFields = conn.getHeaderFields(); boolean rangeReceived = (headerFields != null) && (new CI.CIHashMap<List<String>>(headerFields)).containsKey("Content-Range"); return !rangeReceived; } public boolean resourceAvailable(URL url) { log.debug("Checking if resource is available: " + url); if (url.getProtocol().toLowerCase().equals("ftp")) { return FTPUtils.resourceAvailable(url); } else { try { HttpURLConnection conn = openConnectionHeadOrGet(url); int code = conn.getResponseCode(); return code >= 200 && code < 300; } catch (Exception e) { return false; } } } /** * First tries a HEAD request, then a GET request if the HEAD fails. * If the GET fails, the exception is thrown * * @param url * @return * @throws IOException */ private HttpURLConnection openConnectionHeadOrGet(URL url) throws IOException { // Keep track of urls for which "HEAD" does not work (e.g. Amazon with signed urls). boolean tryHead = headURLCache.containsKey(url) ? headURLCache.get(url) : true; if (tryHead) { try { HttpURLConnection conn = openConnection(url, null, "HEAD"); headURLCache.put(url, true); return conn; } catch (IOException e) { if (e instanceof FileNotFoundException) { throw e; } log.info("HEAD request failed for url: " + url.toExternalForm() + ". Trying GET"); headURLCache.put(url, false); } } return openConnection(url, null, "GET"); } public String getHeaderField(URL url, String key) throws IOException { HttpURLConnection conn = openConnectionHeadOrGet(url); if (conn == null) return null; return conn.getHeaderField(key); } public long getLastModified(URL url) throws IOException { HttpURLConnection conn = openConnectionHeadOrGet(url); if (conn == null) return 0; return conn.getLastModified(); } public long getContentLength(URL url) throws IOException { try { String contentLengthString = getHeaderField(url, "Content-Length"); if (contentLengthString == null) { return -1; } else { return Long.parseLong(contentLengthString); } } catch (Exception e) { log.error("Error fetching content length", e); return -1; } } /** * Compare a local and remote resource, returning true if it is believed that the * remote file is newer than the local file * * @param file * @param url * @param compareContentLength Whether to use the content length to compare files. If false, only * the modified date is used * @return true if the files are the same or the local file is newer, false if the remote file has been modified wrt the local one. * @throws IOException */ public boolean remoteIsNewer(File file, URL url, boolean compareContentLength) throws IOException { if (!file.exists()) { return false; } HttpURLConnection conn = openConnection(url, null, "HEAD"); // Check content-length first long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { try { contentLength = Long.parseLong(contentLengthString); } catch (NumberFormatException e) { log.error("Error parsing content-length string: " + contentLengthString + " from URL: " + url.toString()); contentLength = -1; } } if (contentLength != file.length()) { return true; } // Compare last-modified dates String lastModifiedString = conn.getHeaderField("Last-Modified"); if (lastModifiedString == null) { return false; } else { HttpDate date = new HttpDate(); date.parse(lastModifiedString); long remoteModifiedTime = date.getTime(); long localModifiedTime = file.lastModified(); return remoteModifiedTime > localModifiedTime; } } public void updateProxySettings() { boolean useProxy; String proxyHost; int proxyPort = -1; boolean auth = false; String user = null; String pw = null; PreferenceManager prefMgr = PreferenceManager.getInstance(); useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY); proxyHost = prefMgr.get(PreferenceManager.PROXY_HOST, null); try { proxyPort = Integer.parseInt(prefMgr.get(PreferenceManager.PROXY_PORT, "-1")); } catch (NumberFormatException e) { proxyPort = -1; } auth = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE); user = prefMgr.get(PreferenceManager.PROXY_USER, null); String pwString = prefMgr.get(PreferenceManager.PROXY_PW, null); if (pwString != null) { pw = Utilities.base64Decode(pwString); } String proxyTypeString = prefMgr.get(PreferenceManager.PROXY_TYPE, "HTTP"); Proxy.Type type = Proxy.Type.valueOf(proxyTypeString.trim().toUpperCase()); proxySettings = new ProxySettings(useProxy, user, pw, auth, proxyHost, proxyPort, type); } /** * Get the system defined proxy defined for the URI, or null if * not available. May also return a {@code Proxy} object which * represents a direct connection * * @param uri * @return */ private Proxy getSystemProxy(String uri) { try { log.debug("Getting system proxy for " + uri); ProxySelector selector = ProxySelector.getDefault(); List<Proxy> proxyList = selector.select(new URI(uri)); return proxyList.get(0); } catch (URISyntaxException e) { log.error(e.getMessage(), e); return null; } catch (NullPointerException e) { return null; } catch (Exception e) { log.error(e.getMessage(), e); return null; } } /** * Calls {@link #downloadFile(String, java.io.File, Frame, String)} * with {@code dialogsParent = null, title = null} * * @param url * @param outputFile * @return RunnableResult * @throws IOException */ public RunnableResult downloadFile(String url, File outputFile) throws IOException { URLDownloader downloader = downloadFile(url, outputFile, null, null); return downloader.getResult(); } /** * @param url * @param outputFile * @param dialogsParent Parent of dialog to show progress. If null, none shown * @return URLDownloader used to perform download * @throws IOException */ public URLDownloader downloadFile(String url, File outputFile, Frame dialogsParent, String dialogTitle) throws IOException { final URLDownloader urlDownloader = new URLDownloader(url, outputFile); boolean showProgressDialog = dialogsParent != null; if (!showProgressDialog) { urlDownloader.run(); return urlDownloader; } else { ProgressMonitor monitor = new ProgressMonitor(); urlDownloader.setMonitor(monitor); ActionListener buttonListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { urlDownloader.cancel(true); } }; String permText = "Downloading " + url; String title = dialogTitle != null ? dialogTitle : permText; CancellableProgressDialog dialog = CancellableProgressDialog.showCancellableProgressDialog(dialogsParent, title, buttonListener, false, monitor); dialog.setPermText(permText); Dimension dms = new Dimension(600, 150); dialog.setPreferredSize(dms); dialog.setSize(dms); dialog.validate(); LongRunningTask.submit(urlDownloader); return urlDownloader; } } public void uploadGenomeSpaceFile(String uri, File file, Map<String, String> headers) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; URL url = new URL(uri); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); int i; // read byte by byte until end of stream while ((i = bis.read()) > 0) { bos.write(i); } bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. if (responseCode >= 400) { String message = readErrorStream(urlconnection); throw new IOException("Error uploading " + file.getName() + " : " + message); } } public String createGenomeSpaceDirectory(URL url, String body) throws IOException { HttpURLConnection urlconnection = null; OutputStream bos = null; Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("Content-Length", String.valueOf(body.getBytes().length)); urlconnection = openConnection(url, headers, "PUT"); urlconnection.setDoOutput(true); urlconnection.setDoInput(true); bos = new BufferedOutputStream(urlconnection.getOutputStream()); bos.write(body.getBytes()); bos.close(); int responseCode = urlconnection.getResponseCode(); // Error messages below. StringBuffer buf = new StringBuffer(); InputStream inputStream; if (responseCode >= 200 && responseCode < 300) { inputStream = getInputStream(urlconnection); } else { inputStream = urlconnection.getErrorStream(); } BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String nextLine; while ((nextLine = br.readLine()) != null) { buf.append(nextLine); buf.append('\n'); } inputStream.close(); if (responseCode >= 200 && responseCode < 300) { return buf.toString(); } else { throw new IOException("Error creating GS directory: " + buf.toString()); } } /** * Code for disabling SSL certification */ private void disableCertificateValidation() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[0]; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (NoSuchAlgorithmException e) { } catch (KeyManagementException e) { } // Install a callback to allow the igv Amazon and local hosts HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { if (hostname.equals("igv.broadinstitute.org") || hostname.equals("igvdata.broadinstitute.org") || hostname.equals("localhost")) return true; return true; } }); } private String readContents(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b; while ((b = bis.read()) >= 0) { bos.write(b); } return new String(bos.toByteArray()); } private String readErrorStream(HttpURLConnection connection) throws IOException { InputStream inputStream = null; try { inputStream = connection.getErrorStream(); if (inputStream == null) { return null; } return readContents(inputStream); } finally { if (inputStream != null) inputStream.close(); } } public HttpURLConnection delete(URL url) throws IOException { return openConnection(url, Collections.<String, String>emptyMap(), "DELETE"); } HttpURLConnection openConnection(URL url, Map<String, String> requestProperties) throws IOException { return openConnection(url, requestProperties, "GET"); } private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method) throws IOException { return openConnection(url, requestProperties, method, 0); } /** * The "real" connection method * * @param url * @param requestProperties * @param method * @return * @throws java.io.IOException */ private HttpURLConnection openConnection( URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException { //Encode query string portions url = StringUtils.encodeURLQueryString(url); if (log.isTraceEnabled()) { log.trace(url); } //Encode base portions. Right now just spaces, most common case //TODO This is a hack and doesn't work for all characters which need it if (StringUtils.countChar(url.toExternalForm(), ' ') > 0) { String newPath = url.toExternalForm().replaceAll(" ", "%20"); url = new URL(newPath); } Proxy sysProxy = null; boolean igvProxySettingsExist = proxySettings != null && proxySettings.useProxy; //Only check for system proxy if igv proxy settings not found if (!igvProxySettingsExist) { sysProxy = getSystemProxy(url.toExternalForm()); } boolean useProxy = sysProxy != null || igvProxySettingsExist; HttpURLConnection conn; if (useProxy) { Proxy proxy = sysProxy; if (igvProxySettingsExist) { if (proxySettings.type == Proxy.Type.DIRECT) { proxy = Proxy.NO_PROXY; } else { proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort)); } } conn = (HttpURLConnection) url.openConnection(proxy); if (igvProxySettingsExist && proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes(); String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes)); conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd); } } else { conn = (HttpURLConnection) url.openConnection(); } if (GSUtils.isGenomeSpace(url)) { conn.setRequestProperty("Accept", "application/json,text/plain"); } else { if (!"HEAD".equals(method)) conn.setRequestProperty("Accept", "text/plain"); } //------// //There seems to be a bug with JWS caches //So we avoid caching //This default is persistent, really should be available statically but isn't conn.setDefaultUseCaches(false); conn.setUseCaches(false); //------// conn.setConnectTimeout(Globals.CONNECT_TIMEOUT); conn.setReadTimeout(Globals.READ_TIMEOUT); conn.setRequestMethod(method); conn.setRequestProperty("Connection", "Keep-Alive"); if (requestProperties != null) { for (Map.Entry<String, String> prop : requestProperties.entrySet()) { conn.setRequestProperty(prop.getKey(), prop.getValue()); } } conn.setRequestProperty("User-Agent", Globals.applicationString()); if (method.equals("PUT")) { return conn; } else { int code = conn.getResponseCode(); if (log.isDebugEnabled()) { //logHeaders(conn); } // Redirects. These can occur even if followRedirects == true if there is a change in protocol, // for example http -> https. if (code >= 300 && code < 400) { if (redirectCount > MAX_REDIRECTS) { throw new IOException("Too many redirects"); } String newLocation = conn.getHeaderField("Location"); log.debug("Redirecting to " + newLocation); return openConnection(new URL(newLocation), requestProperties, method, ++redirectCount); } // TODO -- handle other response codes. else if (code >= 400) { String message; if (code == 404) { message = "File not found: " + url.toString(); throw new FileNotFoundException(message); } else if (code == 401) { // Looks like this only happens when user hits "Cancel". // message = "Not authorized to view this file"; // JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE); redirectCount = MAX_REDIRECTS + 1; return null; } else { message = conn.getResponseMessage(); } String details = readErrorStream(conn); log.error("URL: " + url.toExternalForm() + ". error stream: " + details); log.error("Code: " + code + ". " + message); HttpResponseException exc = new HttpResponseException(code); throw exc; } } return conn; } //Used for testing sometimes, please do not delete private void logHeaders(HttpURLConnection conn) { Map<String, List<String>> headerFields = conn.getHeaderFields(); log.debug("Headers for " + conn.getURL()); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { log.debug(header.getKey() + ": " + StringUtils.join(header.getValue(), ",")); } } public void setDefaultPassword(String defaultPassword) { this.defaultPassword = defaultPassword.toCharArray(); } public void setDefaultUserName(String defaultUserName) { this.defaultUserName = defaultUserName; } public void clearDefaultCredentials() { this.defaultPassword = null; this.defaultUserName = null; } /** * Test to see if this client can successfully retrieve a portion of a remote file using the byte-range header. * This is not a test of the server, but the client. In some environments the byte-range header gets removed * by filters after the request is made by IGV. * * @return */ public boolean useByteRange(URL url) { if (BYTE_RANGE_DISABLED) return false; // We can test byte-range success for hosts we can reach. synchronized (byteRangeTestMap) { final String host = url.getHost(); if (byteRangeTestMap.containsKey(host)) { return byteRangeTestMap.get(host); } else { SeekableStream str = null; try { boolean byteRangeTestSuccess = true; if (host.contains("broadinstitute.org")) { byteRangeTestSuccess = testBroadHost(host); } else { // Non-broad URL int l = (int) Math.min(1000, HttpUtils.getInstance().getContentLength(url)); if (l > 100) { byte[] firstBytes = new byte[l]; str = new IGVSeekableHTTPStream(url); str.readFully(firstBytes); int end = firstBytes.length; int start = end - 100; str.seek(start); int len = end - start; byte[] buffer = new byte[len]; int n = 0; while (n < len) { int count = str.read(buffer, n, len - n); if (count < 0) throw new EOFException(); n += count; } for (int i = 0; i < len; i++) { if (buffer[i] != firstBytes[i + start]) { byteRangeTestSuccess = false; break; } } } else { // Too small a sample to test, or unknown content length. Return "true" but don't record // this host as tested. return true; } } if (byteRangeTestSuccess) { log.info("Range-byte request succeeded"); } else { log.info("Range-byte test failed -- problem with client network environment."); } byteRangeTestMap.put(host, byteRangeTestSuccess); return byteRangeTestSuccess; } catch (IOException e) { log.error("Error while testing byte range " + e.getMessage()); // We could not reach the test server, so we can't know if this client can do byte-range tests or // not. Take the "optimistic" view. return true; } finally { if (str != null) try { str.close(); } catch (IOException e) { log.error("Error closing stream (" + url.toExternalForm() + ")", e); } } } } } private boolean testBroadHost(String host) throws IOException { // Test broad urls for successful byte range requests. log.info("Testing range-byte request on host: " + host); String testURL; if (host.startsWith("igvdata.broadinstitute.org")) { // Amazon cloud front testURL = "http://igvdata.broadinstitute.org/genomes/seq/hg19/chr12.txt"; } else if (host.startsWith("igv.broadinstitute.org")) { // Amazon S3 testURL = "http://igv.broadinstitute.org/genomes/seq/hg19/chr12.txt"; } else { // All others testURL = "http://www.broadinstitute.org/igvdata/annotations/seq/hg19/chr12.txt"; } byte[] expectedBytes = {'T', 'C', 'G', 'C', 'T', 'T', 'G', 'A', 'A', 'C', 'C', 'C', 'G', 'G', 'G', 'A', 'G', 'A', 'G', 'G'}; IGVSeekableHTTPStream str = null; try { str = new IGVSeekableHTTPStream(new URL(testURL)); str.seek(25350000); byte[] buffer = new byte[80000]; str.read(buffer); String result = new String(buffer); for (int i = 0; i < expectedBytes.length; i++) { if (buffer[i] != expectedBytes[i]) { return false; } } return true; } finally { if (str != null) str.close(); } } public void shutdown() { // Do any cleanup required here } /** * Checks if the string is a URL (not necessarily remote, can be any protocol) * * @param f * @return */ public static boolean isURL(String f) { return f.startsWith("http:") || f.startsWith("ftp:") || f.startsWith("https:") || URLmatcher.matcher(f).matches(); } public static Map<String, String> parseQueryString(String query) { String[] params = query.split("&"); Map<String, String> map = new HashMap<String, String>(); for (String param : params) { String[] name_val = param.split("=", 2); if (name_val.length == 2) { map.put(name_val[0], name_val[1]); } } return map; } public static class ProxySettings { boolean auth = false; String user; String pw; boolean useProxy; String proxyHost; int proxyPort = -1; Proxy.Type type; public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort) { this(useProxy, user, pw, auth, proxyHost, proxyPort, Proxy.Type.HTTP); this.auth = auth; } public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort, Proxy.Type proxyType) { this.auth = auth; this.proxyHost = proxyHost; this.proxyPort = proxyPort; this.pw = pw; this.useProxy = useProxy; this.user = user; this.type = proxyType; } } /** * The default authenticator */ public class IGVAuthenticator extends Authenticator { Hashtable<String, PasswordAuthentication> pwCache = new Hashtable<String, PasswordAuthentication>(); HashSet<String> cacheAttempts = new HashSet<String>(); /** * Called when password authentication is needed. * * @return */ @Override protected synchronized PasswordAuthentication getPasswordAuthentication() { RequestorType type = getRequestorType(); String urlString = getRequestingURL().toString(); boolean isProxyChallenge = type == RequestorType.PROXY; // Cache user entered PWs. In normal use this shouldn't be necessary as credentials are cached upstream, // but if loading many files in parallel (e.g. from sessions) calls to this method can queue up before the // user enters their credentials, causing needless reentry. String pKey = type.toString() + getRequestingProtocol() + getRequestingHost(); PasswordAuthentication pw = pwCache.get(pKey); if (pw != null) { // Prevents infinite loop if credentials are incorrect if (cacheAttempts.contains(urlString)) { cacheAttempts.remove(urlString); } else { cacheAttempts.add(urlString); return pw; } } if (isProxyChallenge) { if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) { return new PasswordAuthentication(proxySettings.user, proxySettings.pw.toCharArray()); } } if (defaultUserName != null && defaultPassword != null) { return new PasswordAuthentication(defaultUserName, defaultPassword); } Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null; boolean isGenomeSpace = GSUtils.isGenomeSpace(getRequestingURL()); if (isGenomeSpace) { // If we are being challenged by GS the token must be bad/expired GSUtils.logout(); } LoginDialog dlg = new LoginDialog(owner, isGenomeSpace, urlString, isProxyChallenge); dlg.setVisible(true); if (dlg.isCanceled()) { return null; } else { final String userString = dlg.getUsername(); final char[] userPass = dlg.getPassword(); if (isProxyChallenge) { proxySettings.user = userString; proxySettings.pw = new String(userPass); } pw = new PasswordAuthentication(userString, userPass); pwCache.put(pKey, pw); return pw; } } } /** * Runnable for downloading a file from a URL. * Downloading is buffered, and can be cancelled (between buffers) * via {@link #cancel(boolean)} */ public class URLDownloader implements Runnable { private ProgressMonitor monitor = null; private final URL srcUrl; private final File outputFile; private volatile boolean started = false; private volatile boolean done = false; private volatile boolean cancelled = false; private volatile RunnableResult result; public URLDownloader(String url, File outputFile) throws MalformedURLException { this.srcUrl = new URL(url); this.outputFile = outputFile; } @Override public void run() { if (this.cancelled) { return; } started = true; try { this.result = doDownload(); } catch (IOException e) { log.error(e.getMessage(), e); } finally { this.done(); } } /** * Return the result. Must be called after run is complete * * @return */ public RunnableResult getResult() { if (!this.done) throw new IllegalStateException("Must wait for run to finish before getting result"); return this.result; } private RunnableResult doDownload() throws IOException { log.info("Downloading " + srcUrl + " to " + outputFile.getAbsolutePath()); HttpURLConnection conn = openConnection(this.srcUrl, null); long contentLength = -1; String contentLengthString = conn.getHeaderField("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } InputStream is = null; OutputStream out = null; long downloaded = 0; long downSinceLast = 0; String curStatus; String msg1 = String.format("downloaded of %s total", contentLength >= 0 ? bytesToByteCountString(contentLength) : "unknown"); int perc = 0; try { is = getInputStream(conn); out = new FileOutputStream(outputFile); byte[] buf = new byte[64 * 1024]; int counter = 0; int interval = 100; int bytesRead = 0; while (!this.cancelled && (bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); downloaded += bytesRead; downSinceLast += bytesRead; counter = (counter + 1) % interval; if (counter == 0 && this.monitor != null) { curStatus = String.format("%s %s", bytesToByteCountString(downloaded), msg1); this.monitor.updateStatus(curStatus); if (contentLength >= 0) { perc = (int) ((downSinceLast * 100) / contentLength); this.monitor.fireProgressChange(perc); if (perc >= 1) downSinceLast = 0; } } } log.info("Download complete. Total bytes downloaded = " + downloaded); } catch (IOException e) { readErrorStream(conn); throw e; } finally { if (is != null) is.close(); if (out != null) { out.flush(); out.close(); } } long fileLength = outputFile.length(); if (this.cancelled) return RunnableResult.CANCELLED; boolean knownComplete = contentLength == fileLength; //Assume success if file length not known if (knownComplete || contentLength < 0) { if (this.monitor != null) { this.monitor.fireProgressChange(100); this.monitor.updateStatus("Done"); } return RunnableResult.SUCCESS; } else { return RunnableResult.FAILURE; } } protected void done() { this.done = true; } public boolean isDone() { return this.done; } /** * See {@link java.util.concurrent.FutureTask#cancel(boolean)} * * @param mayInterruptIfRunning * @return */ public boolean cancel(boolean mayInterruptIfRunning) { if (this.started && !mayInterruptIfRunning) { return false; } this.cancelled = true; return true; } public void setMonitor(ProgressMonitor monitor) { this.monitor = monitor; } /** * Convert bytes to human-readable string. * e.g. 102894 -> 102.89 KB. If too big or too small, * doesn't append a prefix just returns {@code bytes + " B"} * * @param bytes * @return */ public String bytesToByteCountString(long bytes) { int unit = 1000; String prefs = "KMGT"; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); if (exp <= 0 || exp >= prefs.length()) return bytes + " B"; String pre = (prefs).charAt(exp - 1) + ""; return String.format("%.2f %sB", bytes / Math.pow(unit, exp), pre); } } /** * Provide override for unit tests */ public void setAuthenticator(Authenticator authenticator) { Authenticator.setDefault(authenticator); } /** * For unit tests */ public void resetAuthenticator() { Authenticator.setDefault(new IGVAuthenticator()); } /** * Extension of CookieManager that grabs cookies from the GenomeSpace identity server to store locally. * This is to support the GenomeSpace "single sign-on". Examples ... * gs-username=igvtest; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/ * gs-token=HnR9rBShNO4dTXk8cKXVJT98Oe0jWVY+; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/ */ static class IGVCookieManager extends CookieHandler { CookieManager wrappedManager; public IGVCookieManager() { wrappedManager = new CookieManager(); } @Override public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException { Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.putAll(wrappedManager.get(uri, requestHeaders)); if (GSUtils.isGenomeSpace(uri.toURL())) { String token = GSUtils.getGSToken(); if (token != null) { List<String> cookieList = headers.get("Cookie"); boolean needsTokenCookie = true; boolean needsToolCookie = true; if (cookieList == null) { cookieList = new ArrayList<String>(1); headers.put("Cookie", cookieList); } for (String cookie : cookieList) { if (cookie.startsWith("gs-token")) { needsTokenCookie = false; } else if (cookie.startsWith("gs-toolname")) { needsToolCookie = false; } } if (needsTokenCookie) { cookieList.add("gs-token=" + token); } if (needsToolCookie) { cookieList.add("gs-toolname=IGV"); } } } return Collections.unmodifiableMap(headers); } @Override public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException { String urilc = uri.toString().toLowerCase(); if (urilc.contains("identity") && urilc.contains("genomespace")) { List<String> cookies = responseHeaders.get("Set-Cookie"); if (cookies != null) { for (String cstring : cookies) { List<HttpCookie> cookieList = HttpCookie.parse(cstring); for (HttpCookie cookie : cookieList) { String cookieName = cookie.getName(); String value = cookie.getValue(); if (cookieName.equals("gs-token")) { //log.debug("gs-token: " + value); GSUtils.setGSToken(value); } else if (cookieName.equals("gs-username")) { //log.debug("gs-username: " + value); GSUtils.setGSUser(value); } } } } } wrappedManager.put(uri, responseHeaders); } } }
For Java version < 1.8, maintain SSL hack to maintain current behavior.
src/org/broad/igv/util/HttpUtils.java
For Java version < 1.8, maintain SSL hack to maintain current behavior.
<ide><path>rc/org/broad/igv/util/HttpUtils.java <ide> <ide> htsjdk.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class); <ide> <del> // disableCertificateValidation(); <add> if(!Globals.checkJavaVersion("1.8")) { <add> disableCertificateValidation(); <add> } <ide> CookieHandler.setDefault(new IGVCookieManager()); <ide> Authenticator.setDefault(new IGVAuthenticator()); <ide>
Java
apache-2.0
2c394cedea0b3b89d83d88a1690b6e5ec24c89bd
0
apache/incubator-taverna-server,apache/incubator-taverna-server,taverna/taverna-server,taverna/taverna-server,apache/incubator-taverna-server,taverna/taverna-server,taverna/taverna-server
/* * Copyright (C) 2013 The University of Manchester * * See the file "LICENSE" for license terms. */ package org.taverna.server.master.common.version; import static org.taverna.server.master.common.version.Constants.PATCH; import static org.taverna.server.master.common.version.Constants.VERSION; /** * Common location for describing the version of the server. * * @author Donal Fellows */ public interface Version { public static final String JAVA = VERSION + Constants.releaseChar + PATCH; public static final String HTML = VERSION + Constants.releaseHEnt + PATCH; public static final String XML = VERSION + Constants.releaseXEnt + PATCH; } /** * The pieces of a version string. * * @author Donal Fellows */ interface Constants { static final String MAJOR = "2"; static final String MINOR = "5"; static final String PATCH = "1"; static final char alphaChar = '\u03b1'; static final char betaChar = '\u03b2'; static final char releaseChar = '.'; static final String alphaHEnt = "&alpha;"; static final String betaHEnt = "&beta;"; static final String releaseHEnt = "."; static final String alphaXEnt = "&#x03b1;"; static final String betaXEnt = "&#x03b2;"; static final String releaseXEnt = "."; static final String VERSION = MAJOR + "." + MINOR; }
server-webapp/src/main/java/org/taverna/server/master/common/version/Version.java
/* * Copyright (C) 2013 The University of Manchester * * See the file "LICENSE" for license terms. */ package org.taverna.server.master.common.version; import static org.taverna.server.master.common.version.Constants.PATCH; import static org.taverna.server.master.common.version.Constants.VERSION; import static org.taverna.server.master.common.version.Constants.alphaChar; import static org.taverna.server.master.common.version.Constants.alphaHEnt; import static org.taverna.server.master.common.version.Constants.alphaXEnt; /** * Common location for describing the version of the server. * * @author Donal Fellows */ public interface Version { public static final String JAVA = VERSION + alphaChar + PATCH; public static final String HTML = VERSION + alphaHEnt + PATCH; public static final String XML = VERSION + alphaXEnt + PATCH; } /** * The pieces of a version string. * * @author Donal Fellows */ interface Constants { static final String MAJOR = "2"; static final String MINOR = "5"; static final String PATCH = "1"; static final char alphaChar = '\u03b1'; static final char betaChar = '\u03b2'; static final char releaseChar = '.'; static final String alphaHEnt = "&alpha;"; static final String betaHEnt = "&beta;"; static final String releaseHEnt = "."; static final String alphaXEnt = "&#x03b1;"; static final String betaXEnt = "&#x03b2;"; static final String releaseXEnt = "."; static final String VERSION = MAJOR + "." + MINOR; }
Version correction
server-webapp/src/main/java/org/taverna/server/master/common/version/Version.java
Version correction
<ide><path>erver-webapp/src/main/java/org/taverna/server/master/common/version/Version.java <ide> <ide> import static org.taverna.server.master.common.version.Constants.PATCH; <ide> import static org.taverna.server.master.common.version.Constants.VERSION; <del>import static org.taverna.server.master.common.version.Constants.alphaChar; <del>import static org.taverna.server.master.common.version.Constants.alphaHEnt; <del>import static org.taverna.server.master.common.version.Constants.alphaXEnt; <ide> <ide> /** <ide> * Common location for describing the version of the server. <ide> * @author Donal Fellows <ide> */ <ide> public interface Version { <del> public static final String JAVA = VERSION + alphaChar + PATCH; <del> public static final String HTML = VERSION + alphaHEnt + PATCH; <del> public static final String XML = VERSION + alphaXEnt + PATCH; <add> public static final String JAVA = VERSION + Constants.releaseChar + PATCH; <add> public static final String HTML = VERSION + Constants.releaseHEnt + PATCH; <add> public static final String XML = VERSION + Constants.releaseXEnt + PATCH; <ide> } <ide> <ide> /**
Java
apache-2.0
23a7f5c05121c486f6ee9e484adcf10cc01f8d98
0
icirellik/tika,zamattiac/tika,icirellik/tika,smadha/tika,zamattiac/tika,icirellik/tika,icirellik/tika,smadha/tika,zamattiac/tika,smadha/tika,icirellik/tika,zamattiac/tika,smadha/tika,icirellik/tika,smadha/tika,zamattiac/tika,smadha/tika,zamattiac/tika,zamattiac/tika,icirellik/tika,zamattiac/tika,smadha/tika,icirellik/tika,smadha/tika
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tika.parser.microsoft; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hpsf.CustomProperties; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.MSOffice; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.Office; import org.apache.tika.metadata.OfficeOpenXMLCore; import org.apache.tika.metadata.OfficeOpenXMLExtended; import org.apache.tika.metadata.PagedText; import org.apache.tika.metadata.Property; import org.apache.tika.metadata.TikaCoreProperties; /** * Extractor for Common OLE2 (HPSF) metadata */ public class SummaryExtractor { private static final Log logger = LogFactory.getLog(AbstractPOIFSExtractor.class); private static final String SUMMARY_INFORMATION = SummaryInformation.DEFAULT_STREAM_NAME; private static final String DOCUMENT_SUMMARY_INFORMATION = DocumentSummaryInformation.DEFAULT_STREAM_NAME; private final Metadata metadata; public SummaryExtractor(Metadata metadata) { this.metadata = metadata; } public void parseSummaries(NPOIFSFileSystem filesystem) throws IOException, TikaException { parseSummaries(filesystem.getRoot()); } public void parseSummaries(DirectoryNode root) throws IOException, TikaException { parseSummaryEntryIfExists(root, SUMMARY_INFORMATION); parseSummaryEntryIfExists(root, DOCUMENT_SUMMARY_INFORMATION); } private void parseSummaryEntryIfExists( DirectoryNode root, String entryName) throws IOException, TikaException { try { DocumentEntry entry = (DocumentEntry) root.getEntry(entryName); PropertySet properties = new PropertySet(new DocumentInputStream(entry)); if (properties.isSummaryInformation()) { parse(new SummaryInformation(properties)); } if (properties.isDocumentSummaryInformation()) { parse(new DocumentSummaryInformation(properties)); } } catch (FileNotFoundException e) { // entry does not exist, just skip it } catch (NoPropertySetStreamException e) { // no property stream, just skip it } catch (UnexpectedPropertySetTypeException e) { throw new TikaException("Unexpected HPSF document", e); } catch (MarkUnsupportedException e) { throw new TikaException("Invalid DocumentInputStream", e); } catch (Exception e) { logger.warn("Ignoring unexpected exception while parsing summary entry " + entryName, e); } } private void parse(SummaryInformation summary) { set(TikaCoreProperties.TITLE, summary.getTitle()); set(TikaCoreProperties.CREATOR, summary.getAuthor()); set(TikaCoreProperties.KEYWORDS, summary.getKeywords()); // TODO Move to OO subject in Tika 2.0 set(TikaCoreProperties.TRANSITION_SUBJECT_TO_OO_SUBJECT, summary.getSubject()); set(TikaCoreProperties.MODIFIER, summary.getLastAuthor()); set(TikaCoreProperties.COMMENTS, summary.getComments()); set(OfficeOpenXMLExtended.TEMPLATE, summary.getTemplate()); set(OfficeOpenXMLExtended.APPLICATION, summary.getApplicationName()); set(OfficeOpenXMLCore.REVISION, summary.getRevNumber()); set(TikaCoreProperties.CREATED, summary.getCreateDateTime()); set(TikaCoreProperties.MODIFIED, summary.getLastSaveDateTime()); set(TikaCoreProperties.PRINT_DATE, summary.getLastPrinted()); set(Metadata.EDIT_TIME, summary.getEditTime()); set(OfficeOpenXMLExtended.DOC_SECURITY, summary.getSecurity()); // New style counts set(Office.WORD_COUNT, summary.getWordCount()); set(Office.CHARACTER_COUNT, summary.getCharCount()); set(Office.PAGE_COUNT, summary.getPageCount()); if (summary.getPageCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getPageCount()); } // Old style, Tika 1.0 properties // TODO Remove these in Tika 2.0 set(Metadata.TEMPLATE, summary.getTemplate()); set(Metadata.APPLICATION_NAME, summary.getApplicationName()); set(Metadata.REVISION_NUMBER, summary.getRevNumber()); set(Metadata.SECURITY, summary.getSecurity()); set(MSOffice.WORD_COUNT, summary.getWordCount()); set(MSOffice.CHARACTER_COUNT, summary.getCharCount()); set(MSOffice.PAGE_COUNT, summary.getPageCount()); } private void parse(DocumentSummaryInformation summary) { set(OfficeOpenXMLExtended.COMPANY, summary.getCompany()); set(OfficeOpenXMLExtended.MANAGER, summary.getManager()); set(TikaCoreProperties.LANGUAGE, getLanguage(summary)); set(OfficeOpenXMLCore.CATEGORY, summary.getCategory()); // New style counts set(Office.SLIDE_COUNT, summary.getSlideCount()); if (summary.getSlideCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getSlideCount()); } // Old style, Tika 1.0 counts // TODO Remove these in Tika 2.0 set(Metadata.COMPANY, summary.getCompany()); set(Metadata.MANAGER, summary.getManager()); set(MSOffice.SLIDE_COUNT, summary.getSlideCount()); set(Metadata.CATEGORY, summary.getCategory()); parse(summary.getCustomProperties()); } private String getLanguage(DocumentSummaryInformation summary) { CustomProperties customProperties = summary.getCustomProperties(); if (customProperties != null) { Object value = customProperties.get("Language"); if (value instanceof String) { return (String) value; } } return null; } /** * Attempt to parse custom document properties and add to the collection of metadata * @param customProperties */ private void parse(CustomProperties customProperties) { if (customProperties != null) { for (String name : customProperties.nameSet()) { // Apply the custom prefix String key = Metadata.USER_DEFINED_METADATA_NAME_PREFIX + name; // Get, convert and save property value Object value = customProperties.get(name); if (value instanceof String){ set(key, (String)value); } else if (value instanceof Date) { Property prop = Property.externalDate(key); metadata.set(prop, (Date)value); } else if (value instanceof Boolean) { Property prop = Property.externalBoolean(key); metadata.set(prop, ((Boolean)value).toString()); } else if (value instanceof Long) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Long)value).intValue()); } else if (value instanceof Double) { Property prop = Property.externalReal(key); metadata.set(prop, ((Double)value).doubleValue()); } else if (value instanceof Integer) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Integer)value).intValue()); } } } } private void set(String name, String value) { if (value != null) { metadata.set(name, value); } } private void set(Property property, String value) { if (value != null) { metadata.set(property, value); } } private void set(Property property, Date value) { if (value != null) { metadata.set(property, value); } } private void set(Property property, int value) { if (value > 0) { metadata.set(property, value); } } private void set(String name, long value) { if (value > 0) { metadata.set(name, Long.toString(value)); } } }
tika-parsers/src/main/java/org/apache/tika/parser/microsoft/SummaryExtractor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tika.parser.microsoft; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.poi.hpsf.CustomProperties; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.MarkUnsupportedException; import org.apache.poi.hpsf.NoPropertySetStreamException; import org.apache.poi.hpsf.PropertySet; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hpsf.UnexpectedPropertySetTypeException; import org.apache.poi.poifs.filesystem.DirectoryNode; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.MSOffice; import org.apache.tika.metadata.Metadata; import org.apache.tika.metadata.Office; import org.apache.tika.metadata.OfficeOpenXMLCore; import org.apache.tika.metadata.OfficeOpenXMLExtended; import org.apache.tika.metadata.PagedText; import org.apache.tika.metadata.Property; import org.apache.tika.metadata.TikaCoreProperties; /** * Outlook Message Parser. */ class SummaryExtractor { private static final Log logger = LogFactory.getLog(AbstractPOIFSExtractor.class); private static final String SUMMARY_INFORMATION = SummaryInformation.DEFAULT_STREAM_NAME; private static final String DOCUMENT_SUMMARY_INFORMATION = DocumentSummaryInformation.DEFAULT_STREAM_NAME; private final Metadata metadata; public SummaryExtractor(Metadata metadata) { this.metadata = metadata; } public void parseSummaries(NPOIFSFileSystem filesystem) throws IOException, TikaException { parseSummaries(filesystem.getRoot()); } public void parseSummaries(DirectoryNode root) throws IOException, TikaException { parseSummaryEntryIfExists(root, SUMMARY_INFORMATION); parseSummaryEntryIfExists(root, DOCUMENT_SUMMARY_INFORMATION); } private void parseSummaryEntryIfExists( DirectoryNode root, String entryName) throws IOException, TikaException { try { DocumentEntry entry = (DocumentEntry) root.getEntry(entryName); PropertySet properties = new PropertySet(new DocumentInputStream(entry)); if (properties.isSummaryInformation()) { parse(new SummaryInformation(properties)); } if (properties.isDocumentSummaryInformation()) { parse(new DocumentSummaryInformation(properties)); } } catch (FileNotFoundException e) { // entry does not exist, just skip it } catch (NoPropertySetStreamException e) { // no property stream, just skip it } catch (UnexpectedPropertySetTypeException e) { throw new TikaException("Unexpected HPSF document", e); } catch (MarkUnsupportedException e) { throw new TikaException("Invalid DocumentInputStream", e); } catch (Exception e) { logger.warn("Ignoring unexpected exception while parsing summary entry " + entryName, e); } } private void parse(SummaryInformation summary) { set(TikaCoreProperties.TITLE, summary.getTitle()); set(TikaCoreProperties.CREATOR, summary.getAuthor()); set(TikaCoreProperties.KEYWORDS, summary.getKeywords()); // TODO Move to OO subject in Tika 2.0 set(TikaCoreProperties.TRANSITION_SUBJECT_TO_OO_SUBJECT, summary.getSubject()); set(TikaCoreProperties.MODIFIER, summary.getLastAuthor()); set(TikaCoreProperties.COMMENTS, summary.getComments()); set(OfficeOpenXMLExtended.TEMPLATE, summary.getTemplate()); set(OfficeOpenXMLExtended.APPLICATION, summary.getApplicationName()); set(OfficeOpenXMLCore.REVISION, summary.getRevNumber()); set(TikaCoreProperties.CREATED, summary.getCreateDateTime()); set(TikaCoreProperties.MODIFIED, summary.getLastSaveDateTime()); set(TikaCoreProperties.PRINT_DATE, summary.getLastPrinted()); set(Metadata.EDIT_TIME, summary.getEditTime()); set(OfficeOpenXMLExtended.DOC_SECURITY, summary.getSecurity()); // New style counts set(Office.WORD_COUNT, summary.getWordCount()); set(Office.CHARACTER_COUNT, summary.getCharCount()); set(Office.PAGE_COUNT, summary.getPageCount()); if (summary.getPageCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getPageCount()); } // Old style, Tika 1.0 properties // TODO Remove these in Tika 2.0 set(Metadata.TEMPLATE, summary.getTemplate()); set(Metadata.APPLICATION_NAME, summary.getApplicationName()); set(Metadata.REVISION_NUMBER, summary.getRevNumber()); set(Metadata.SECURITY, summary.getSecurity()); set(MSOffice.WORD_COUNT, summary.getWordCount()); set(MSOffice.CHARACTER_COUNT, summary.getCharCount()); set(MSOffice.PAGE_COUNT, summary.getPageCount()); } private void parse(DocumentSummaryInformation summary) { set(OfficeOpenXMLExtended.COMPANY, summary.getCompany()); set(OfficeOpenXMLExtended.MANAGER, summary.getManager()); set(TikaCoreProperties.LANGUAGE, getLanguage(summary)); set(OfficeOpenXMLCore.CATEGORY, summary.getCategory()); // New style counts set(Office.SLIDE_COUNT, summary.getSlideCount()); if (summary.getSlideCount() > 0) { metadata.set(PagedText.N_PAGES, summary.getSlideCount()); } // Old style, Tika 1.0 counts // TODO Remove these in Tika 2.0 set(Metadata.COMPANY, summary.getCompany()); set(Metadata.MANAGER, summary.getManager()); set(MSOffice.SLIDE_COUNT, summary.getSlideCount()); set(Metadata.CATEGORY, summary.getCategory()); parse(summary.getCustomProperties()); } private String getLanguage(DocumentSummaryInformation summary) { CustomProperties customProperties = summary.getCustomProperties(); if (customProperties != null) { Object value = customProperties.get("Language"); if (value instanceof String) { return (String) value; } } return null; } /** * Attempt to parse custom document properties and add to the collection of metadata * @param customProperties */ private void parse(CustomProperties customProperties) { if (customProperties != null) { for (String name : customProperties.nameSet()) { // Apply the custom prefix String key = Metadata.USER_DEFINED_METADATA_NAME_PREFIX + name; // Get, convert and save property value Object value = customProperties.get(name); if (value instanceof String){ set(key, (String)value); } else if (value instanceof Date) { Property prop = Property.externalDate(key); metadata.set(prop, (Date)value); } else if (value instanceof Boolean) { Property prop = Property.externalBoolean(key); metadata.set(prop, ((Boolean)value).toString()); } else if (value instanceof Long) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Long)value).intValue()); } else if (value instanceof Double) { Property prop = Property.externalReal(key); metadata.set(prop, ((Double)value).doubleValue()); } else if (value instanceof Integer) { Property prop = Property.externalInteger(key); metadata.set(prop, ((Integer)value).intValue()); } } } } private void set(String name, String value) { if (value != null) { metadata.set(name, value); } } private void set(Property property, String value) { if (value != null) { metadata.set(property, value); } } private void set(Property property, Date value) { if (value != null) { metadata.set(property, value); } } private void set(Property property, int value) { if (value > 0) { metadata.set(property, value); } } private void set(String name, long value) { if (value > 0) { metadata.set(name, Long.toString(value)); } } }
TIKA-1188 Other parsers may be working on OLE2 files, and hence may want to be able to call the common OLE2 metadata extraction code, so make it public not package git-svn-id: de575e320ab8ef6bd6941acfb783cdb8d8307cc1@1535395 13f79535-47bb-0310-9956-ffa450edef68
tika-parsers/src/main/java/org/apache/tika/parser/microsoft/SummaryExtractor.java
TIKA-1188 Other parsers may be working on OLE2 files, and hence may want to be able to call the common OLE2 metadata extraction code, so make it public not package
<ide><path>ika-parsers/src/main/java/org/apache/tika/parser/microsoft/SummaryExtractor.java <ide> import org.apache.tika.metadata.TikaCoreProperties; <ide> <ide> /** <del> * Outlook Message Parser. <add> * Extractor for Common OLE2 (HPSF) metadata <ide> */ <del>class SummaryExtractor { <del> <add>public class SummaryExtractor { <ide> private static final Log logger = LogFactory.getLog(AbstractPOIFSExtractor.class); <ide> <ide> private static final String SUMMARY_INFORMATION = <ide> } <ide> <ide> // Old style, Tika 1.0 properties <del> // TODO Remove these in Tika 2.0 <add> // TODO Remove these in Tika 2.0 <ide> set(Metadata.TEMPLATE, summary.getTemplate()); <ide> set(Metadata.APPLICATION_NAME, summary.getApplicationName()); <ide> set(Metadata.REVISION_NUMBER, summary.getRevNumber()); <ide> metadata.set(PagedText.N_PAGES, summary.getSlideCount()); <ide> } <ide> // Old style, Tika 1.0 counts <del> // TODO Remove these in Tika 2.0 <add> // TODO Remove these in Tika 2.0 <ide> set(Metadata.COMPANY, summary.getCompany()); <ide> set(Metadata.MANAGER, summary.getManager()); <ide> set(MSOffice.SLIDE_COUNT, summary.getSlideCount()); <ide> metadata.set(name, Long.toString(value)); <ide> } <ide> } <del> <ide> }
Java
apache-2.0
1e5a597654e5aba705f44d766ce929b30b486d66
0
alibaba/nacos,alibaba/nacos,alibaba/nacos,alibaba/nacos
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.client; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.AbstractListener; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.common.utils.ThreadUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.Properties; import java.util.concurrent.atomic.AtomicBoolean; @Ignore public class ConfigTest { private static ConfigService configService; @Before public void before() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); configService = NacosFactory.createConfigService(properties); } @After public void cleanup() throws Exception { configService.shutDown(); } @Test public void test() throws Exception { // set config final String dataId = "lessspring"; final String group = "lessspring"; final String content = "lessspring-" + System.currentTimeMillis(); boolean result = configService.publishConfig(dataId, group, content); Assert.assertTrue(result); ThreadUtils.sleep(10000L); // set change listener final AtomicBoolean hasListener = new AtomicBoolean(false); final AtomicBoolean hasChangedCallback = new AtomicBoolean(false); final String[] changedTmpContent = {""}; String response = configService.getConfigAndSignListener(dataId, group, 5000, new AbstractListener() { @Override public void receiveConfigInfo(String configInfo) { System.out.println("receiveConfigInfo:" + configInfo); changedTmpContent[0] = configInfo; hasChangedCallback.set(true); } }); hasListener.set(true); Assert.assertEquals(content, response); // new thread to publish config final String newRawContent = "nacosnewconfig-" + System.currentTimeMillis(); new Thread(new Runnable() { @Override public void run() { while (hasListener.get()) { try { configService.publishConfig(dataId, group, newRawContent); hasListener.set(false); break; } catch (NacosException e) { e.printStackTrace(); } } } }).start(); // spin do { if (hasChangedCallback.get()) { System.out.println(newRawContent + "==> " + changedTmpContent[0]); Assert.assertEquals(newRawContent, changedTmpContent[0]); break; } } while (!hasChangedCallback.get()); } }
client/src/test/java/com/alibaba/nacos/client/ConfigTest.java
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.client; import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.PropertyKeyConst; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.listener.AbstractListener; import com.alibaba.nacos.common.utils.ThreadUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import java.util.Properties; import java.util.Scanner; @Ignore public class ConfigTest { private static ConfigService configService; @Before public static void before() throws Exception { Properties properties = new Properties(); properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); configService = NacosFactory.createConfigService(properties); } @After public void cleanup() throws Exception { configService.shutDown(); } @Test public static void test() throws Exception { final String dataId = "lessspring"; final String group = "lessspring"; final String content = "lessspring-" + System.currentTimeMillis(); boolean result = configService.publishConfig(dataId, group, content); Assert.assertTrue(result); ThreadUtils.sleep(10000L); String response = configService.getConfigAndSignListener(dataId, group, 5000, new AbstractListener() { @Override public void receiveConfigInfo(String configInfo) { System.err.println(configInfo); } }); Assert.assertEquals(content, response); Scanner scanner = new Scanner(System.in); System.out.println("input content"); while (scanner.hasNextLine()) { String s = scanner.next(); if ("exit".equals(s)) { scanner.close(); return; } configService.publishConfig(dataId, group, s); } } }
[ISSUE #3613] Fix `unit test method not be static` & update publish config listener in `ConfigTest.java` (#3614) * fix `unit test method not be static` & update publish config listener in `ConfigTest.java` * fix `unit test method not be static` & update publish config listener in `ConfigTest.java`
client/src/test/java/com/alibaba/nacos/client/ConfigTest.java
[ISSUE #3613] Fix `unit test method not be static` & update publish config listener in `ConfigTest.java` (#3614)
<ide><path>lient/src/test/java/com/alibaba/nacos/client/ConfigTest.java <ide> import com.alibaba.nacos.api.PropertyKeyConst; <ide> import com.alibaba.nacos.api.config.ConfigService; <ide> import com.alibaba.nacos.api.config.listener.AbstractListener; <add>import com.alibaba.nacos.api.exception.NacosException; <ide> import com.alibaba.nacos.common.utils.ThreadUtils; <ide> import org.junit.After; <ide> import org.junit.Assert; <ide> import org.junit.Test; <ide> <ide> import java.util.Properties; <del>import java.util.Scanner; <add>import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> @Ignore <ide> public class ConfigTest { <ide> private static ConfigService configService; <ide> <ide> @Before <del> public static void before() throws Exception { <add> public void before() throws Exception { <ide> Properties properties = new Properties(); <ide> properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848"); <ide> configService = NacosFactory.createConfigService(properties); <ide> } <ide> <ide> @Test <del> public static void test() throws Exception { <add> public void test() throws Exception { <add> // set config <ide> final String dataId = "lessspring"; <ide> final String group = "lessspring"; <ide> final String content = "lessspring-" + System.currentTimeMillis(); <ide> <ide> ThreadUtils.sleep(10000L); <ide> <add> // set change listener <add> final AtomicBoolean hasListener = new AtomicBoolean(false); <add> final AtomicBoolean hasChangedCallback = new AtomicBoolean(false); <add> final String[] changedTmpContent = {""}; <ide> String response = configService.getConfigAndSignListener(dataId, group, 5000, new AbstractListener() { <ide> @Override <ide> public void receiveConfigInfo(String configInfo) { <del> System.err.println(configInfo); <add> System.out.println("receiveConfigInfo:" + configInfo); <add> changedTmpContent[0] = configInfo; <add> hasChangedCallback.set(true); <ide> } <ide> }); <add> hasListener.set(true); <ide> Assert.assertEquals(content, response); <ide> <del> Scanner scanner = new Scanner(System.in); <del> System.out.println("input content"); <del> while (scanner.hasNextLine()) { <del> String s = scanner.next(); <del> if ("exit".equals(s)) { <del> scanner.close(); <del> return; <add> // new thread to publish config <add> final String newRawContent = "nacosnewconfig-" + System.currentTimeMillis(); <add> new Thread(new Runnable() { <add> @Override <add> public void run() { <add> while (hasListener.get()) { <add> try { <add> configService.publishConfig(dataId, group, newRawContent); <add> hasListener.set(false); <add> break; <add> } catch (NacosException e) { <add> e.printStackTrace(); <add> } <add> } <ide> } <del> configService.publishConfig(dataId, group, s); <del> } <add> }).start(); <add> <add> // spin <add> do { <add> if (hasChangedCallback.get()) { <add> System.out.println(newRawContent + "==> " + changedTmpContent[0]); <add> Assert.assertEquals(newRawContent, changedTmpContent[0]); <add> break; <add> } <add> } while (!hasChangedCallback.get()); <ide> } <ide> <ide> }
Java
apache-2.0
7828895e2ea537268c8d2dbd1a2e0249dfc13bc4
0
webanno/webanno,webanno/webanno,webanno/webanno,webanno/webanno
/******************************************************************************* * Copyright 2012 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getLastSentenceAddressInDisplayWindow; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectByAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectSentenceAt; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.uima.UIMAException; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.jcas.JCas; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnLoadHeaderItem; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.NumberTextField; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.security.core.context.SecurityContextHolder; import org.wicketstuff.annotation.mount.MountPath; import wicket.contrib.input.events.EventType; import wicket.contrib.input.events.InputBehavior; import wicket.contrib.input.events.key.KeyType; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationService; import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService; import de.tudarmstadt.ukp.clarin.webanno.api.UserDao; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotator; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotatorModel; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.component.AnnotationDetailEditorPanel; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAnnotationException; import de.tudarmstadt.ukp.clarin.webanno.brat.project.PreferencesUtil; import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ConstraintsGrammar; import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ParseException; import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.syntaxtree.Parse; import de.tudarmstadt.ukp.clarin.webanno.constraints.model.ParsedConstraints; import de.tudarmstadt.ukp.clarin.webanno.constraints.model.Scope; import de.tudarmstadt.ukp.clarin.webanno.constraints.visitor.ParserVisitor; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.ConstraintSet; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.ScriptDirection; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentStateTransition; import de.tudarmstadt.ukp.clarin.webanno.model.User; import de.tudarmstadt.ukp.clarin.webanno.webapp.dialog.OpenModalWindowPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.home.page.ApplicationPageBase; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.AnnotationLayersModalPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.DocumentNamePanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.ExportModalPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.FinishImage; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.FinishLink; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.GuidelineModalPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.welcome.WelcomePage; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; /** * A wicket page for the Brat Annotation/Visualization page. Included components for pagination, * annotation layer configuration, and Exporting document * * */ @MountPath("/annotation.html") public class AnnotationPage extends ApplicationPageBase { private static final Log LOG = LogFactory.getLog(AnnotationPage.class); private static final long serialVersionUID = 1378872465851908515L; @SpringBean(name = "documentRepository") private RepositoryService repository; @SpringBean(name = "annotationService") private AnnotationService annotationService; @SpringBean(name = "userRepository") private UserDao userRepository; private BratAnnotator annotator; private FinishImage finish; private NumberTextField<Integer> gotoPageTextField; private AnnotationDetailEditorPanel editor; private int gotoPageAddress; // Open the dialog window on first load private boolean firstLoad = true; private Label numberOfPages; private DocumentNamePanel documentNamePanel; private long currentprojectId; private int totalNumberOfSentence; private boolean closeButtonClicked; private BratAnnotatorModel bModel = new BratAnnotatorModel(); private WebMarkupContainer sidebarCell; private WebMarkupContainer annotationViewCell; public AnnotationPage() { sidebarCell = new WebMarkupContainer("sidebarCell") { private static final long serialVersionUID = 1L; @Override protected void onComponentTag(ComponentTag aTag) { super.onComponentTag(aTag); aTag.put("width", bModel.getPreferences().getSidebarSize()+"%"); } }; sidebarCell.setOutputMarkupId(true); add(sidebarCell); annotationViewCell = new WebMarkupContainer("annotationViewCell") { private static final long serialVersionUID = 1L; @Override protected void onComponentTag(ComponentTag aTag) { super.onComponentTag(aTag); aTag.put("width", (100-bModel.getPreferences().getSidebarSize())+"%"); } }; annotationViewCell.setOutputMarkupId(true); add(annotationViewCell); editor = new AnnotationDetailEditorPanel( "annotationDetailEditorPanel", new Model<BratAnnotatorModel>(bModel)) { private static final long serialVersionUID = 2857345299480098279L; @Override protected void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { aTarget.addChildren(getPage(), FeedbackPanel.class); try { annotator.bratRender(aTarget, getCas(aBModel)); } catch (UIMAException | ClassNotFoundException | IOException e) { LOG.info("Error reading CAS " + e.getMessage()); error("Error reading CAS " + e.getMessage()); return; } annotator.bratSetHighlight(aTarget, aBModel.getSelection().getAnnotation()); annotator.onChange(aTarget, aBModel); } @Override protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { try { annotator.autoForward(aTarget, getCas(aBModel)); } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { LOG.info("Error reading CAS " + e.getMessage()); error("Error reading CAS " + e.getMessage()); return; } } }; editor.setOutputMarkupId(true); sidebarCell.add(editor); annotator = new BratAnnotator("embedder1", new Model<BratAnnotatorModel>(bModel), editor) { private static final long serialVersionUID = 7279648231521710155L; @Override public void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBratAnnotatorModel) { bModel = aBratAnnotatorModel; aTarget.add(numberOfPages); } @Override public void renderHead(IHeaderResponse aResponse) { super.renderHead(aResponse); // If the page is reloaded in the browser and a document was already open, we need // to render it. We use the "later" commands here to avoid polluting the Javascript // header items with document data and because loading times are not that critical // on a reload. if (getModelObject().getProject() != null) { // We want to trigger a late rendering only on a page reload, but not on a // Ajax request. if (!aResponse.getResponse().getClass().getName().endsWith("AjaxResponse")) { aResponse.render(OnLoadHeaderItem.forScript(bratInitLaterCommand())); aResponse.render(OnLoadHeaderItem.forScript(bratRenderLaterCommand())); } } } }; annotationViewCell.add(annotator); // This is an Annotation Operation, set model to ANNOTATION mode bModel.setMode(Mode.ANNOTATION); add(documentNamePanel = (DocumentNamePanel) new DocumentNamePanel("documentNamePanel", new Model<BratAnnotatorModel>(bModel)).setOutputMarkupId(true)); numberOfPages = new Label("numberOfPages", new Model<String>()); numberOfPages.setOutputMarkupId(true); add(numberOfPages); final ModalWindow openDocumentsModal; add(openDocumentsModal = new ModalWindow("openDocumentsModal")); openDocumentsModal.setOutputMarkupId(true); openDocumentsModal.setInitialWidth(500); openDocumentsModal.setInitialHeight(300); openDocumentsModal.setResizable(true); openDocumentsModal.setWidthUnit("px"); openDocumentsModal.setHeightUnit("px"); openDocumentsModal.setTitle("Open document"); openDocumentsModal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { private static final long serialVersionUID = -5423095433535634321L; @Override public boolean onCloseButtonClicked(AjaxRequestTarget aTarget) { closeButtonClicked = true; return true; } }); add(new AjaxLink<Void>("showOpenDocumentModal") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { bModel.getSelection().clear(); closeButtonClicked = false; openDocumentsModal.setContent(new OpenModalWindowPanel(openDocumentsModal .getContentId(), bModel, openDocumentsModal, Mode.ANNOTATION) { private static final long serialVersionUID = -3434069761864809703L; @Override protected void onCancel(AjaxRequestTarget aTarget) { closeButtonClicked = true; }; }); openDocumentsModal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { private static final long serialVersionUID = -1746088901018629567L; @Override public void onClose(AjaxRequestTarget target) { // A hack, the dialog opens for the first time, and if no document is // selected window will be "blind down". Something in the brat js causes // this! if (bModel.getProject() == null || bModel.getDocument() == null) { setResponsePage(WelcomePage.class); } // Dialog was cancelled rather that a document was selected. if (closeButtonClicked) { return; } loadDocumentAction(target); try { editor.reloadLayer(target); } catch (BratAnnotationException e) { error("Error loading layers"+e.getMessage()); } } }); // target.appendJavaScript("Wicket.Window.unloadConfirmation = false;"); openDocumentsModal.show(aTarget); } }); add(new AnnotationLayersModalPanel("annotationLayersModalPanel", new Model<BratAnnotatorModel>(bModel), editor) { private static final long serialVersionUID = -4657965743173979437L; @Override protected void onChange(AjaxRequestTarget aTarget) { try { // Re-render the whole page because the width of the sidebar may have changed aTarget.add(AnnotationPage.this); JCas jCas = getJCas(); annotator.bratRender(aTarget, jCas); updateSentenceAddress(jCas, aTarget); } catch (UIMAException | ClassNotFoundException | IOException e) { LOG.info("Error reading CAS " + e.getMessage()); error("Error reading CAS " + e.getMessage()); return; } } }); add(new ExportModalPanel("exportModalPanel", new Model<BratAnnotatorModel>(bModel))); // Show the previous document, if exist add(new AjaxLink<Void>("showPreviousDocument") { private static final long serialVersionUID = 7496156015186497496L; /** * Get the current beginning sentence address and add on it the size of the display * window */ @Override public void onClick(AjaxRequestTarget aTarget) { editor.reset(aTarget); // List of all Source Documents in the project List<SourceDocument> listOfSourceDocuements= getListOfDocs(); // Index of the current source document in the list int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument()); // If the first the document if (currentDocumentIndex == 0) { aTarget.appendJavaScript("alert('This is the first document!')"); return; } bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex - 1) .getName()); bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1)); loadDocumentAction(aTarget); } }.add(new InputBehavior(new KeyType[] { KeyType.Shift, KeyType.Page_up }, EventType.click))); // Show the next document if exist add(new AjaxLink<Void>("showNextDocument") { private static final long serialVersionUID = 7496156015186497496L; /** * Get the current beginning sentence address and add on it the size of the display * window */ @Override public void onClick(AjaxRequestTarget aTarget) { editor.reset(aTarget); // List of all Source Documents in the project List<SourceDocument> listOfSourceDocuements= getListOfDocs(); // Index of the current source document in the list int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument()); // If the first document if (currentDocumentIndex == listOfSourceDocuements.size() - 1) { aTarget.appendJavaScript("alert('This is the last document!')"); return; } bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex + 1) .getName()); bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex + 1)); loadDocumentAction(aTarget); } }.add(new InputBehavior(new KeyType[] { KeyType.Shift, KeyType.Page_down }, EventType.click))); // Show the next page of this document add(new AjaxLink<Void>("showNext") { private static final long serialVersionUID = 7496156015186497496L; /** * Get the current beginning sentence address and add on it the size of the display * window */ @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); int nextSentenceAddress = BratAjaxCasUtil.getNextPageFirstSentenceAddress( jCas, bModel.getSentenceAddress(), bModel.getPreferences() .getWindowSize()); if (bModel.getSentenceAddress() != nextSentenceAddress) { updateSentenceNumber(jCas, nextSentenceAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is last page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.Page_down }, EventType.click))); // Show the previous page of this document add(new AjaxLink<Void>("showPrevious") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); int previousSentenceAddress = BratAjaxCasUtil .getPreviousDisplayWindowSentenceBeginAddress(jCas, bModel .getSentenceAddress(), bModel.getPreferences() .getWindowSize()); //Since BratAjaxCasUtil.getPreviousDisplayWindowSentenceBeginAddress returns same address //if there are not much sentences to go back to as defined in windowSize if(previousSentenceAddress==bModel.getSentenceAddress() //Check whether it's not the beginning of document && bModel.getSentenceAddress()!=bModel.getFirstSentenceAddress()){ previousSentenceAddress = bModel.getFirstSentenceAddress(); } if (bModel.getSentenceAddress() != previousSentenceAddress) { updateSentenceNumber(jCas, previousSentenceAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is First Page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.Page_up }, EventType.click))); add(new AjaxLink<Void>("showFirst") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); if (bModel.getFirstSentenceAddress() != bModel.getSentenceAddress()) { updateSentenceNumber(jCas, bModel.getFirstSentenceAddress()); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is first page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.Home }, EventType.click))); add(new AjaxLink<Void>("showLast") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); int lastDisplayWindowBeginingSentenceAddress = BratAjaxCasUtil .getLastDisplayWindowFirstSentenceAddress(jCas, bModel .getPreferences().getWindowSize()); if (lastDisplayWindowBeginingSentenceAddress != bModel.getSentenceAddress()) { updateSentenceNumber(jCas, lastDisplayWindowBeginingSentenceAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is last Page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.End }, EventType.click))); add(new AjaxLink<Void>("toggleScriptDirection") { private static final long serialVersionUID = -4332566542278611728L; @Override public void onClick(AjaxRequestTarget aTarget) { if (ScriptDirection.LTR.equals(bModel.getScriptDirection())) { bModel.setScriptDirection(ScriptDirection.RTL); } else { bModel.setScriptDirection(ScriptDirection.LTR); } annotator.bratRenderLater(aTarget); } }); add(new GuidelineModalPanel("guidelineModalPanel", new Model<BratAnnotatorModel>(bModel))); gotoPageTextField = (NumberTextField<Integer>) new NumberTextField<Integer>("gotoPageText", new Model<Integer>(0)); Form<Void> gotoPageTextFieldForm = new Form<Void>("gotoPageTextFieldForm"); gotoPageTextFieldForm.add(new AjaxFormSubmitBehavior(gotoPageTextFieldForm, "onsubmit") { private static final long serialVersionUID = -4549805321484461545L; @Override protected void onSubmit(AjaxRequestTarget aTarget) { try { if (gotoPageAddress == 0) { aTarget.appendJavaScript("alert('The sentence number entered is not valid')"); return; } if (bModel.getSentenceAddress() != gotoPageAddress) { JCas jCas = getJCas(); updateSentenceNumber(jCas, gotoPageAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); aTarget.add(numberOfPages); gotoPageTextField.setModelObject(BratAjaxCasUtil.getFirstSentenceNumber( jCas, bModel.getSentenceAddress()) + 1); aTarget.add(gotoPageTextField); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }); gotoPageTextField.setType(Integer.class); gotoPageTextField.setMinimum(1); gotoPageTextField.setDefaultModelObject(1); add(gotoPageTextFieldForm.add(gotoPageTextField)); gotoPageTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 56637289242712170L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { try { if (gotoPageTextField.getModelObject() < 1) { aTarget.appendJavaScript("alert('Page number shouldn't be less than 1')"); } else { updateSentenceAddress(getJCas(), aTarget); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }); add(new AjaxLink<Void>("gotoPageLink") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (gotoPageAddress == 0) { aTarget.appendJavaScript("alert('The sentence number entered is not valid')"); return; } if (bModel.getDocument() == null) { aTarget.appendJavaScript("alert('Please open a document first!')"); return; } if (bModel.getSentenceAddress() != gotoPageAddress) { JCas jCas = getJCas(); updateSentenceNumber(jCas, gotoPageAddress); updateSentenceAddress(jCas, aTarget); annotator.bratRenderLater(aTarget); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }); finish = new FinishImage("finishImage", new Model<BratAnnotatorModel>(bModel)); finish.setOutputMarkupId(true); add(new FinishLink("showYesNoModalPanel", new Model<BratAnnotatorModel>(bModel), finish) { private static final long serialVersionUID = -4657965743173979437L; @Override public void onClose(AjaxRequestTarget aTarget) { super.onClose(aTarget); aTarget.add(editor); } }); } private List<SourceDocument> getListOfDocs() { String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); // List of all Source Documents in the project List<SourceDocument> listOfSourceDocuements = repository.listSourceDocuments(bModel.getProject()); List<SourceDocument> sourceDocumentsinIgnoreState = new ArrayList<SourceDocument>(); for (SourceDocument sourceDocument : listOfSourceDocuements) { if (repository.existsAnnotationDocument(sourceDocument, user) && repository .getAnnotationDocument(sourceDocument, user).getState().equals(AnnotationDocumentState.IGNORE)) { sourceDocumentsinIgnoreState.add(sourceDocument); } } listOfSourceDocuements.removeAll(sourceDocumentsinIgnoreState); return listOfSourceDocuements; } private void updateSentenceAddress(JCas aJCas, AjaxRequestTarget aTarget) throws UIMAException, IOException, ClassNotFoundException { gotoPageAddress = BratAjaxCasUtil.getSentenceAddress(aJCas, gotoPageTextField.getModelObject()); String labelText = ""; if (bModel.getDocument() != null) { List<SourceDocument> listofDoc = getListOfDocs(); int docIndex = listofDoc.indexOf(bModel.getDocument())+1; totalNumberOfSentence = BratAjaxCasUtil.getNumberOfPages(aJCas); // If only one page, start displaying from sentence 1 if (totalNumberOfSentence == 1) { bModel.setSentenceAddress(bModel.getFirstSentenceAddress()); } int sentenceNumber = BratAjaxCasUtil.getFirstSentenceNumber(aJCas, bModel.getSentenceAddress()); int firstSentenceNumber = sentenceNumber + 1; int lastSentenceNumber; if (firstSentenceNumber + bModel.getPreferences().getWindowSize() - 1 < totalNumberOfSentence) { lastSentenceNumber = firstSentenceNumber + bModel.getPreferences().getWindowSize() - 1; } else { lastSentenceNumber = totalNumberOfSentence; } labelText = "showing " + firstSentenceNumber + "-" + lastSentenceNumber + " of " + totalNumberOfSentence + " sentences [document " + docIndex +" of "+ listofDoc.size()+"]"; } else { labelText = "";// no document yet selected } numberOfPages.setDefaultModelObject(labelText); aTarget.add(numberOfPages); aTarget.add(gotoPageTextField); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); String jQueryString = ""; if (firstLoad) { jQueryString += "jQuery('#showOpenDocumentModal').trigger('click');"; firstLoad = false; } response.render(OnLoadHeaderItem.forScript(jQueryString)); } private JCas getJCas() throws UIMAException, IOException, ClassNotFoundException { String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); SourceDocument aDocument = bModel.getDocument(); AnnotationDocument annotationDocument = repository.getAnnotationDocument(aDocument, user); // If there is no CAS yet for the annotation document, create one. return repository.readAnnotationCas(annotationDocument); } private void updateSentenceNumber(JCas aJCas, int aAddress) { bModel.setSentenceAddress(aAddress); Sentence sentence = selectByAddr(aJCas, Sentence.class, aAddress); bModel.setSentenceBeginOffset(sentence.getBegin()); bModel.setSentenceEndOffset(sentence.getEnd()); bModel.setSentenceNumber(BratAjaxCasUtil.getSentenceNumber(aJCas, sentence.getBegin())); Sentence firstSentence = selectSentenceAt(aJCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()); int lastAddressInPage = getLastSentenceAddressInDisplayWindow(aJCas, getAddr(firstSentence), bModel.getPreferences().getWindowSize()); // the last sentence address in the display window Sentence lastSentenceInPage = (Sentence) selectByAddr(aJCas, FeatureStructure.class, lastAddressInPage); bModel.setFSN(BratAjaxCasUtil.getSentenceNumber(aJCas, firstSentence.getBegin())); bModel.setLSN(BratAjaxCasUtil.getSentenceNumber(aJCas, lastSentenceInPage.getBegin())); } private void loadDocumentAction(AjaxRequestTarget aTarget) { LOG.info("BEGIN LOAD_DOCUMENT_ACTION"); String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); // Update dynamic elements in action bar aTarget.add(finish); aTarget.add(numberOfPages); aTarget.add(documentNamePanel); bModel.setUser(userRepository.get(username)); try { // Check if there is an annotation document entry in the database. If there is none, // create one. AnnotationDocument annotationDocument = repository.createOrGetAnnotationDocument( bModel.getDocument(), user); // Read the CAS JCas jcas = repository.readAnnotationCas(annotationDocument); // Update the annotation document CAS repository.upgradeCas(jcas.getCas(), annotationDocument); // After creating an new CAS or upgrading the CAS, we need to save it repository.writeAnnotationCas(jcas.getCas().getJCas(), annotationDocument.getDocument(), user); // (Re)initialize brat model after potential creating / upgrading CAS bModel.initForDocument(jcas, repository); // Load constraints bModel.setConstraints(loadConstraints(aTarget, bModel.getProject())); // Load user preferences PreferencesUtil.setAnnotationPreference(username, repository, annotationService, bModel, Mode.ANNOTATION); // Resize areas according to preferences aTarget.add(sidebarCell); aTarget.add(annotationViewCell); // if project is changed, reset some project specific settings if (currentprojectId != bModel.getProject().getId()) { bModel.initForProject(); } currentprojectId = bModel.getProject().getId(); LOG.debug("Configured BratAnnotatorModel for user [" + bModel.getUser() + "] f:[" + bModel.getFirstSentenceAddress() + "] l:[" + bModel.getLastSentenceAddress() + "] s:[" + bModel.getSentenceAddress() + "]"); gotoPageTextField.setModelObject(1); updateSentenceAddress(jcas, aTarget); // Wicket-level rendering of annotator because it becomes visible // after selecting a document aTarget.add(annotator); // brat-level initialization and rendering of document annotator.bratInit(aTarget); annotator.bratRender(aTarget, jcas); // Update document state if (bModel.getDocument().getState().equals(SourceDocumentState.NEW)) { bModel.getDocument().setState(SourceDocumentStateTransition.transition( SourceDocumentStateTransition.NEW_TO_ANNOTATION_IN_PROGRESS)); repository.createSourceDocument(bModel.getDocument(), user); } } catch (DataRetrievalFailureException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } catch (IOException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } catch (UIMAException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(ExceptionUtils.getRootCauseMessage(e)); } catch (ClassNotFoundException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } LOG.info("END LOAD_DOCUMENT_ACTION"); } private ParsedConstraints loadConstraints(AjaxRequestTarget aTarget, Project aProject) throws IOException { ParsedConstraints merged = null; for (ConstraintSet set : repository.listConstraintSets(aProject)) { try { String script = repository.readConstrainSet(set); ConstraintsGrammar parser = new ConstraintsGrammar(new StringReader(script)); Parse p = parser.Parse(); ParsedConstraints constraints = p.accept(new ParserVisitor()); if (merged == null) { merged = constraints; } else { // Merge imports for(Entry<String,String> e: constraints.getImports().entrySet()){ //Check if the value already points to some other feature in previous constraint file(s). if(merged.getImports().containsKey(e.getKey()) && !e.getValue().equalsIgnoreCase(merged.getImports().get(e.getKey()))){ //If detected, notify user with proper message and abort merging StringBuffer errorMessage = new StringBuffer(); errorMessage.append("Conflict detected in imports for key \""); errorMessage.append(e.getKey()); errorMessage.append("\", conflicting values are \""); errorMessage.append(e.getValue()); errorMessage.append("\" & \""); errorMessage.append(merged.getImports().get(e.getKey())); errorMessage.append("\". Please contact Project Admin for correcting this. Constraints feature may not work."); errorMessage.append("\nAborting Constraint rules merge!"); LOG.error(errorMessage.toString()); error(errorMessage.toString()); break; } } merged.getImports().putAll(constraints.getImports()); // Merge scopes for (Scope scope : constraints.getScopes()) { Scope target = merged.getScopeByName(scope.getScopeName()); if (target == null) { // Scope does not exist yet merged.getScopes().add(scope); } else { // Scope already exists target.getRules().addAll(scope.getRules()); } } } } catch (ParseException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } } return merged; } }
webanno-webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/page/annotation/AnnotationPage.java
/******************************************************************************* * Copyright 2012 * Ubiquitous Knowledge Processing (UKP) Lab and FG Language Technology * Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.getLastSentenceAddressInDisplayWindow; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectByAddr; import static de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil.selectSentenceAt; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.uima.UIMAException; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.jcas.JCas; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior; import org.apache.wicket.ajax.markup.html.AjaxLink; import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.IHeaderResponse; import org.apache.wicket.markup.head.OnLoadHeaderItem; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.NumberTextField; import org.apache.wicket.markup.html.panel.FeedbackPanel; import org.apache.wicket.model.Model; import org.apache.wicket.spring.injection.annot.SpringBean; import org.springframework.dao.DataRetrievalFailureException; import org.springframework.security.core.context.SecurityContextHolder; import org.wicketstuff.annotation.mount.MountPath; import wicket.contrib.input.events.EventType; import wicket.contrib.input.events.InputBehavior; import wicket.contrib.input.events.key.KeyType; import de.tudarmstadt.ukp.clarin.webanno.api.AnnotationService; import de.tudarmstadt.ukp.clarin.webanno.api.RepositoryService; import de.tudarmstadt.ukp.clarin.webanno.api.UserDao; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotator; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.BratAnnotatorModel; import de.tudarmstadt.ukp.clarin.webanno.brat.annotation.component.AnnotationDetailEditorPanel; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAjaxCasUtil; import de.tudarmstadt.ukp.clarin.webanno.brat.controller.BratAnnotationException; import de.tudarmstadt.ukp.clarin.webanno.brat.project.PreferencesUtil; import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ConstraintsGrammar; import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.ParseException; import de.tudarmstadt.ukp.clarin.webanno.constraints.grammar.syntaxtree.Parse; import de.tudarmstadt.ukp.clarin.webanno.constraints.model.ParsedConstraints; import de.tudarmstadt.ukp.clarin.webanno.constraints.model.Scope; import de.tudarmstadt.ukp.clarin.webanno.constraints.visitor.ParserVisitor; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument; import de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.ConstraintSet; import de.tudarmstadt.ukp.clarin.webanno.model.Mode; import de.tudarmstadt.ukp.clarin.webanno.model.Project; import de.tudarmstadt.ukp.clarin.webanno.model.ScriptDirection; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentState; import de.tudarmstadt.ukp.clarin.webanno.model.SourceDocumentStateTransition; import de.tudarmstadt.ukp.clarin.webanno.model.User; import de.tudarmstadt.ukp.clarin.webanno.webapp.dialog.OpenModalWindowPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.home.page.ApplicationPageBase; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.AnnotationLayersModalPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.DocumentNamePanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.ExportModalPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.FinishImage; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.FinishLink; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.annotation.component.GuidelineModalPanel; import de.tudarmstadt.ukp.clarin.webanno.webapp.page.welcome.WelcomePage; import de.tudarmstadt.ukp.dkpro.core.api.segmentation.type.Sentence; /** * A wicket page for the Brat Annotation/Visualization page. Included components for pagination, * annotation layer configuration, and Exporting document * * */ @MountPath("/annotation.html") public class AnnotationPage extends ApplicationPageBase { private static final Log LOG = LogFactory.getLog(AnnotationPage.class); private static final long serialVersionUID = 1378872465851908515L; @SpringBean(name = "documentRepository") private RepositoryService repository; @SpringBean(name = "annotationService") private AnnotationService annotationService; @SpringBean(name = "userRepository") private UserDao userRepository; private BratAnnotator annotator; private FinishImage finish; private NumberTextField<Integer> gotoPageTextField; private AnnotationDetailEditorPanel editor; private int gotoPageAddress; // Open the dialog window on first load private boolean firstLoad = true; private Label numberOfPages; private DocumentNamePanel documentNamePanel; private long currentprojectId; private int totalNumberOfSentence; private boolean closeButtonClicked; private BratAnnotatorModel bModel = new BratAnnotatorModel(); private WebMarkupContainer sidebarCell; private WebMarkupContainer annotationViewCell; public AnnotationPage() { sidebarCell = new WebMarkupContainer("sidebarCell") { private static final long serialVersionUID = 1L; @Override protected void onComponentTag(ComponentTag aTag) { super.onComponentTag(aTag); aTag.put("width", bModel.getPreferences().getSidebarSize()+"%"); } }; sidebarCell.setOutputMarkupId(true); add(sidebarCell); annotationViewCell = new WebMarkupContainer("annotationViewCell") { private static final long serialVersionUID = 1L; @Override protected void onComponentTag(ComponentTag aTag) { super.onComponentTag(aTag); aTag.put("width", (100-bModel.getPreferences().getSidebarSize())+"%"); } }; annotationViewCell.setOutputMarkupId(true); add(annotationViewCell); editor = new AnnotationDetailEditorPanel( "annotationDetailEditorPanel", new Model<BratAnnotatorModel>(bModel)) { private static final long serialVersionUID = 2857345299480098279L; @Override protected void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { aTarget.addChildren(getPage(), FeedbackPanel.class); try { annotator.bratRender(aTarget, getCas(aBModel)); } catch (UIMAException | ClassNotFoundException | IOException e) { LOG.info("Error reading CAS " + e.getMessage()); error("Error reading CAS " + e.getMessage()); return; } annotator.bratSetHighlight(aTarget, aBModel.getSelection().getAnnotation()); annotator.onChange(aTarget, aBModel); } @Override protected void onAutoForward(AjaxRequestTarget aTarget, BratAnnotatorModel aBModel) { try { annotator.autoForward(aTarget, getCas(aBModel)); } catch (UIMAException | ClassNotFoundException | IOException | BratAnnotationException e) { LOG.info("Error reading CAS " + e.getMessage()); error("Error reading CAS " + e.getMessage()); return; } } }; editor.setOutputMarkupId(true); sidebarCell.add(editor); annotator = new BratAnnotator("embedder1", new Model<BratAnnotatorModel>(bModel), editor) { private static final long serialVersionUID = 7279648231521710155L; @Override public void onChange(AjaxRequestTarget aTarget, BratAnnotatorModel aBratAnnotatorModel) { bModel = aBratAnnotatorModel; aTarget.add(numberOfPages); } @Override public void renderHead(IHeaderResponse aResponse) { super.renderHead(aResponse); // If the page is reloaded in the browser and a document was already open, we need // to render it. We use the "later" commands here to avoid polluting the Javascript // header items with document data and because loading times are not that critical // on a reload. if (getModelObject().getProject() != null) { // We want to trigger a late rendering only on a page reload, but not on a // Ajax request. if (!aResponse.getResponse().getClass().getName().endsWith("AjaxResponse")) { aResponse.render(OnLoadHeaderItem.forScript(bratInitLaterCommand())); aResponse.render(OnLoadHeaderItem.forScript(bratRenderLaterCommand())); } } } }; annotationViewCell.add(annotator); // This is an Annotation Operation, set model to ANNOTATION mode bModel.setMode(Mode.ANNOTATION); add(documentNamePanel = (DocumentNamePanel) new DocumentNamePanel("documentNamePanel", new Model<BratAnnotatorModel>(bModel)).setOutputMarkupId(true)); numberOfPages = new Label("numberOfPages", new Model<String>()); numberOfPages.setOutputMarkupId(true); add(numberOfPages); final ModalWindow openDocumentsModal; add(openDocumentsModal = new ModalWindow("openDocumentsModal")); openDocumentsModal.setOutputMarkupId(true); openDocumentsModal.setInitialWidth(500); openDocumentsModal.setInitialHeight(300); openDocumentsModal.setResizable(true); openDocumentsModal.setWidthUnit("px"); openDocumentsModal.setHeightUnit("px"); openDocumentsModal.setTitle("Open document"); openDocumentsModal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { private static final long serialVersionUID = -5423095433535634321L; @Override public boolean onCloseButtonClicked(AjaxRequestTarget aTarget) { closeButtonClicked = true; return true; } }); add(new AjaxLink<Void>("showOpenDocumentModal") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { bModel.getSelection().clear(); closeButtonClicked = false; openDocumentsModal.setContent(new OpenModalWindowPanel(openDocumentsModal .getContentId(), bModel, openDocumentsModal, Mode.ANNOTATION) { private static final long serialVersionUID = -3434069761864809703L; @Override protected void onCancel(AjaxRequestTarget aTarget) { closeButtonClicked = true; }; }); openDocumentsModal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { private static final long serialVersionUID = -1746088901018629567L; @Override public void onClose(AjaxRequestTarget target) { // A hack, the dialog opens for the first time, and if no document is // selected window will be "blind down". Something in the brat js causes // this! if (bModel.getProject() == null || bModel.getDocument() == null) { setResponsePage(WelcomePage.class); } // Dialog was cancelled rather that a document was selected. if (closeButtonClicked) { return; } loadDocumentAction(target); try { editor.reloadLayer(target); } catch (BratAnnotationException e) { error("Error loading layers"+e.getMessage()); } } }); // target.appendJavaScript("Wicket.Window.unloadConfirmation = false;"); openDocumentsModal.show(aTarget); } }); add(new AnnotationLayersModalPanel("annotationLayersModalPanel", new Model<BratAnnotatorModel>(bModel), editor) { private static final long serialVersionUID = -4657965743173979437L; @Override protected void onChange(AjaxRequestTarget aTarget) { try { // Re-render the whole page because the width of the sidebar may have changed aTarget.add(AnnotationPage.this); JCas jCas = getJCas(); annotator.bratRender(aTarget, jCas); updateSentenceAddress(jCas, aTarget); } catch (UIMAException | ClassNotFoundException | IOException e) { LOG.info("Error reading CAS " + e.getMessage()); error("Error reading CAS " + e.getMessage()); return; } } }); add(new ExportModalPanel("exportModalPanel", new Model<BratAnnotatorModel>(bModel))); // Show the previous document, if exist add(new AjaxLink<Void>("showPreviousDocument") { private static final long serialVersionUID = 7496156015186497496L; /** * Get the current beginning sentence address and add on it the size of the display * window */ @Override public void onClick(AjaxRequestTarget aTarget) { editor.reset(aTarget); // List of all Source Documents in the project List<SourceDocument> listOfSourceDocuements = repository.listSourceDocuments(bModel .getProject()); String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); List<SourceDocument> sourceDocumentsinIgnorState = new ArrayList<SourceDocument>(); for (SourceDocument sourceDocument : listOfSourceDocuements) { if (repository.existsAnnotationDocument(sourceDocument, user) && repository.getAnnotationDocument(sourceDocument, user).getState() .equals(AnnotationDocumentState.IGNORE)) { sourceDocumentsinIgnorState.add(sourceDocument); } } listOfSourceDocuements.removeAll(sourceDocumentsinIgnorState); // Index of the current source document in the list int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument()); // If the first the document if (currentDocumentIndex == 0) { aTarget.appendJavaScript("alert('This is the first document!')"); return; } bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex - 1) .getName()); bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex - 1)); loadDocumentAction(aTarget); } }.add(new InputBehavior(new KeyType[] { KeyType.Shift, KeyType.Page_up }, EventType.click))); // Show the next document if exist add(new AjaxLink<Void>("showNextDocument") { private static final long serialVersionUID = 7496156015186497496L; /** * Get the current beginning sentence address and add on it the size of the display * window */ @Override public void onClick(AjaxRequestTarget aTarget) { editor.reset(aTarget); // List of all Source Documents in the project List<SourceDocument> listOfSourceDocuements = repository.listSourceDocuments(bModel .getProject()); String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); List<SourceDocument> sourceDocumentsinIgnoreState = new ArrayList<SourceDocument>(); for (SourceDocument sourceDocument : listOfSourceDocuements) { if (repository.existsAnnotationDocument(sourceDocument, user) && repository.getAnnotationDocument(sourceDocument, user).getState() .equals(AnnotationDocumentState.IGNORE)) { sourceDocumentsinIgnoreState.add(sourceDocument); } } listOfSourceDocuements.removeAll(sourceDocumentsinIgnoreState); // Index of the current source document in the list int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument()); // If the first document if (currentDocumentIndex == listOfSourceDocuements.size() - 1) { aTarget.appendJavaScript("alert('This is the last document!')"); return; } bModel.setDocumentName(listOfSourceDocuements.get(currentDocumentIndex + 1) .getName()); bModel.setDocument(listOfSourceDocuements.get(currentDocumentIndex + 1)); loadDocumentAction(aTarget); } }.add(new InputBehavior(new KeyType[] { KeyType.Shift, KeyType.Page_down }, EventType.click))); // Show the next page of this document add(new AjaxLink<Void>("showNext") { private static final long serialVersionUID = 7496156015186497496L; /** * Get the current beginning sentence address and add on it the size of the display * window */ @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); int nextSentenceAddress = BratAjaxCasUtil.getNextPageFirstSentenceAddress( jCas, bModel.getSentenceAddress(), bModel.getPreferences() .getWindowSize()); if (bModel.getSentenceAddress() != nextSentenceAddress) { updateSentenceNumber(jCas, nextSentenceAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is last page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.Page_down }, EventType.click))); // Show the previous page of this document add(new AjaxLink<Void>("showPrevious") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); int previousSentenceAddress = BratAjaxCasUtil .getPreviousDisplayWindowSentenceBeginAddress(jCas, bModel .getSentenceAddress(), bModel.getPreferences() .getWindowSize()); //Since BratAjaxCasUtil.getPreviousDisplayWindowSentenceBeginAddress returns same address //if there are not much sentences to go back to as defined in windowSize if(previousSentenceAddress==bModel.getSentenceAddress() //Check whether it's not the beginning of document && bModel.getSentenceAddress()!=bModel.getFirstSentenceAddress()){ previousSentenceAddress = bModel.getFirstSentenceAddress(); } if (bModel.getSentenceAddress() != previousSentenceAddress) { updateSentenceNumber(jCas, previousSentenceAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is First Page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.Page_up }, EventType.click))); add(new AjaxLink<Void>("showFirst") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); if (bModel.getFirstSentenceAddress() != bModel.getSentenceAddress()) { updateSentenceNumber(jCas, bModel.getFirstSentenceAddress()); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is first page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.Home }, EventType.click))); add(new AjaxLink<Void>("showLast") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (bModel.getDocument() != null) { JCas jCas = getJCas(); int lastDisplayWindowBeginingSentenceAddress = BratAjaxCasUtil .getLastDisplayWindowFirstSentenceAddress(jCas, bModel .getPreferences().getWindowSize()); if (lastDisplayWindowBeginingSentenceAddress != bModel.getSentenceAddress()) { updateSentenceNumber(jCas, lastDisplayWindowBeginingSentenceAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); gotoPageTextField.setModelObject(BratAjaxCasUtil .getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1); updateSentenceAddress(jCas, aTarget); } else { aTarget.appendJavaScript("alert('This is last Page!')"); } } else { aTarget.appendJavaScript("alert('Please open a document first!')"); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }.add(new InputBehavior(new KeyType[] { KeyType.End }, EventType.click))); add(new AjaxLink<Void>("toggleScriptDirection") { private static final long serialVersionUID = -4332566542278611728L; @Override public void onClick(AjaxRequestTarget aTarget) { if (ScriptDirection.LTR.equals(bModel.getScriptDirection())) { bModel.setScriptDirection(ScriptDirection.RTL); } else { bModel.setScriptDirection(ScriptDirection.LTR); } annotator.bratRenderLater(aTarget); } }); add(new GuidelineModalPanel("guidelineModalPanel", new Model<BratAnnotatorModel>(bModel))); gotoPageTextField = (NumberTextField<Integer>) new NumberTextField<Integer>("gotoPageText", new Model<Integer>(0)); Form<Void> gotoPageTextFieldForm = new Form<Void>("gotoPageTextFieldForm"); gotoPageTextFieldForm.add(new AjaxFormSubmitBehavior(gotoPageTextFieldForm, "onsubmit") { private static final long serialVersionUID = -4549805321484461545L; @Override protected void onSubmit(AjaxRequestTarget aTarget) { try { if (gotoPageAddress == 0) { aTarget.appendJavaScript("alert('The sentence number entered is not valid')"); return; } if (bModel.getSentenceAddress() != gotoPageAddress) { JCas jCas = getJCas(); updateSentenceNumber(jCas, gotoPageAddress); aTarget.addChildren(getPage(), FeedbackPanel.class); annotator.bratRenderLater(aTarget); aTarget.add(numberOfPages); gotoPageTextField.setModelObject(BratAjaxCasUtil.getFirstSentenceNumber( jCas, bModel.getSentenceAddress()) + 1); aTarget.add(gotoPageTextField); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }); gotoPageTextField.setType(Integer.class); gotoPageTextField.setMinimum(1); gotoPageTextField.setDefaultModelObject(1); add(gotoPageTextFieldForm.add(gotoPageTextField)); gotoPageTextField.add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 56637289242712170L; @Override protected void onUpdate(AjaxRequestTarget aTarget) { try { if (gotoPageTextField.getModelObject() < 1) { aTarget.appendJavaScript("alert('Page number shouldn't be less than 1')"); } else { updateSentenceAddress(getJCas(), aTarget); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }); add(new AjaxLink<Void>("gotoPageLink") { private static final long serialVersionUID = 7496156015186497496L; @Override public void onClick(AjaxRequestTarget aTarget) { try { if (gotoPageAddress == 0) { aTarget.appendJavaScript("alert('The sentence number entered is not valid')"); return; } if (bModel.getDocument() == null) { aTarget.appendJavaScript("alert('Please open a document first!')"); return; } if (bModel.getSentenceAddress() != gotoPageAddress) { JCas jCas = getJCas(); updateSentenceNumber(jCas, gotoPageAddress); updateSentenceAddress(jCas, aTarget); annotator.bratRenderLater(aTarget); } } catch (Exception e) { error(e.getMessage()); aTarget.addChildren(getPage(), FeedbackPanel.class); } } }); finish = new FinishImage("finishImage", new Model<BratAnnotatorModel>(bModel)); finish.setOutputMarkupId(true); add(new FinishLink("showYesNoModalPanel", new Model<BratAnnotatorModel>(bModel), finish) { private static final long serialVersionUID = -4657965743173979437L; @Override public void onClose(AjaxRequestTarget aTarget) { super.onClose(aTarget); aTarget.add(editor); } }); } private void updateSentenceAddress(JCas aJCas, AjaxRequestTarget aTarget) throws UIMAException, IOException, ClassNotFoundException { gotoPageAddress = BratAjaxCasUtil.getSentenceAddress(aJCas, gotoPageTextField.getModelObject()); String labelText = ""; if (bModel.getDocument() != null) { totalNumberOfSentence = BratAjaxCasUtil.getNumberOfPages(aJCas); // If only one page, start displaying from sentence 1 if (totalNumberOfSentence == 1) { bModel.setSentenceAddress(bModel.getFirstSentenceAddress()); } int sentenceNumber = BratAjaxCasUtil.getFirstSentenceNumber(aJCas, bModel.getSentenceAddress()); int firstSentenceNumber = sentenceNumber + 1; int lastSentenceNumber; if (firstSentenceNumber + bModel.getPreferences().getWindowSize() - 1 < totalNumberOfSentence) { lastSentenceNumber = firstSentenceNumber + bModel.getPreferences().getWindowSize() - 1; } else { lastSentenceNumber = totalNumberOfSentence; } labelText = "showing " + firstSentenceNumber + "-" + lastSentenceNumber + " of " + totalNumberOfSentence + " sentences"; } else { labelText = "";// no document yet selected } numberOfPages.setDefaultModelObject(labelText); aTarget.add(numberOfPages); aTarget.add(gotoPageTextField); } @Override public void renderHead(IHeaderResponse response) { super.renderHead(response); String jQueryString = ""; if (firstLoad) { jQueryString += "jQuery('#showOpenDocumentModal').trigger('click');"; firstLoad = false; } response.render(OnLoadHeaderItem.forScript(jQueryString)); } private JCas getJCas() throws UIMAException, IOException, ClassNotFoundException { String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); SourceDocument aDocument = bModel.getDocument(); AnnotationDocument annotationDocument = repository.getAnnotationDocument(aDocument, user); // If there is no CAS yet for the annotation document, create one. return repository.readAnnotationCas(annotationDocument); } private void updateSentenceNumber(JCas aJCas, int aAddress) { bModel.setSentenceAddress(aAddress); Sentence sentence = selectByAddr(aJCas, Sentence.class, aAddress); bModel.setSentenceBeginOffset(sentence.getBegin()); bModel.setSentenceEndOffset(sentence.getEnd()); bModel.setSentenceNumber(BratAjaxCasUtil.getSentenceNumber(aJCas, sentence.getBegin())); Sentence firstSentence = selectSentenceAt(aJCas, bModel.getSentenceBeginOffset(), bModel.getSentenceEndOffset()); int lastAddressInPage = getLastSentenceAddressInDisplayWindow(aJCas, getAddr(firstSentence), bModel.getPreferences().getWindowSize()); // the last sentence address in the display window Sentence lastSentenceInPage = (Sentence) selectByAddr(aJCas, FeatureStructure.class, lastAddressInPage); bModel.setFSN(BratAjaxCasUtil.getSentenceNumber(aJCas, firstSentence.getBegin())); bModel.setLSN(BratAjaxCasUtil.getSentenceNumber(aJCas, lastSentenceInPage.getBegin())); } private void loadDocumentAction(AjaxRequestTarget aTarget) { LOG.info("BEGIN LOAD_DOCUMENT_ACTION"); String username = SecurityContextHolder.getContext().getAuthentication().getName(); User user = userRepository.get(username); // Update dynamic elements in action bar aTarget.add(finish); aTarget.add(numberOfPages); aTarget.add(documentNamePanel); bModel.setUser(userRepository.get(username)); try { // Check if there is an annotation document entry in the database. If there is none, // create one. AnnotationDocument annotationDocument = repository.createOrGetAnnotationDocument( bModel.getDocument(), user); // Read the CAS JCas jcas = repository.readAnnotationCas(annotationDocument); // Update the annotation document CAS repository.upgradeCas(jcas.getCas(), annotationDocument); // After creating an new CAS or upgrading the CAS, we need to save it repository.writeAnnotationCas(jcas.getCas().getJCas(), annotationDocument.getDocument(), user); // (Re)initialize brat model after potential creating / upgrading CAS bModel.initForDocument(jcas, repository); // Load constraints bModel.setConstraints(loadConstraints(aTarget, bModel.getProject())); // Load user preferences PreferencesUtil.setAnnotationPreference(username, repository, annotationService, bModel, Mode.ANNOTATION); // Resize areas according to preferences aTarget.add(sidebarCell); aTarget.add(annotationViewCell); // if project is changed, reset some project specific settings if (currentprojectId != bModel.getProject().getId()) { bModel.initForProject(); } currentprojectId = bModel.getProject().getId(); LOG.debug("Configured BratAnnotatorModel for user [" + bModel.getUser() + "] f:[" + bModel.getFirstSentenceAddress() + "] l:[" + bModel.getLastSentenceAddress() + "] s:[" + bModel.getSentenceAddress() + "]"); gotoPageTextField.setModelObject(1); updateSentenceAddress(jcas, aTarget); // Wicket-level rendering of annotator because it becomes visible // after selecting a document aTarget.add(annotator); // brat-level initialization and rendering of document annotator.bratInit(aTarget); annotator.bratRender(aTarget, jcas); // Update document state if (bModel.getDocument().getState().equals(SourceDocumentState.NEW)) { bModel.getDocument().setState(SourceDocumentStateTransition.transition( SourceDocumentStateTransition.NEW_TO_ANNOTATION_IN_PROGRESS)); repository.createSourceDocument(bModel.getDocument(), user); } } catch (DataRetrievalFailureException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } catch (IOException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } catch (UIMAException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(ExceptionUtils.getRootCauseMessage(e)); } catch (ClassNotFoundException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } LOG.info("END LOAD_DOCUMENT_ACTION"); } private ParsedConstraints loadConstraints(AjaxRequestTarget aTarget, Project aProject) throws IOException { ParsedConstraints merged = null; for (ConstraintSet set : repository.listConstraintSets(aProject)) { try { String script = repository.readConstrainSet(set); ConstraintsGrammar parser = new ConstraintsGrammar(new StringReader(script)); Parse p = parser.Parse(); ParsedConstraints constraints = p.accept(new ParserVisitor()); if (merged == null) { merged = constraints; } else { // Merge imports for(Entry<String,String> e: constraints.getImports().entrySet()){ //Check if the value already points to some other feature in previous constraint file(s). if(merged.getImports().containsKey(e.getKey()) && !e.getValue().equalsIgnoreCase(merged.getImports().get(e.getKey()))){ //If detected, notify user with proper message and abort merging StringBuffer errorMessage = new StringBuffer(); errorMessage.append("Conflict detected in imports for key \""); errorMessage.append(e.getKey()); errorMessage.append("\", conflicting values are \""); errorMessage.append(e.getValue()); errorMessage.append("\" & \""); errorMessage.append(merged.getImports().get(e.getKey())); errorMessage.append("\". Please contact Project Admin for correcting this. Constraints feature may not work."); errorMessage.append("\nAborting Constraint rules merge!"); LOG.error(errorMessage.toString()); error(errorMessage.toString()); break; } } merged.getImports().putAll(constraints.getImports()); // Merge scopes for (Scope scope : constraints.getScopes()) { Scope target = merged.getScopeByName(scope.getScopeName()); if (target == null) { // Scope does not exist yet merged.getScopes().add(scope); } else { // Scope already exists target.getRules().addAll(scope.getRules()); } } } } catch (ParseException e) { LOG.error("Error", e); aTarget.addChildren(getPage(), FeedbackPanel.class); error(e.getMessage()); } } return merged; } }
Showing x of y documents feature #357
webanno-webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/page/annotation/AnnotationPage.java
Showing x of y documents feature #357
<ide><path>ebanno-webapp/src/main/java/de/tudarmstadt/ukp/clarin/webanno/webapp/page/annotation/AnnotationPage.java <ide> { <ide> editor.reset(aTarget); <ide> // List of all Source Documents in the project <del> List<SourceDocument> listOfSourceDocuements = repository.listSourceDocuments(bModel <del> .getProject()); <del> <del> String username = SecurityContextHolder.getContext().getAuthentication().getName(); <del> User user = userRepository.get(username); <del> <del> List<SourceDocument> sourceDocumentsinIgnorState = new ArrayList<SourceDocument>(); <del> for (SourceDocument sourceDocument : listOfSourceDocuements) { <del> if (repository.existsAnnotationDocument(sourceDocument, user) <del> && repository.getAnnotationDocument(sourceDocument, user).getState() <del> .equals(AnnotationDocumentState.IGNORE)) { <del> sourceDocumentsinIgnorState.add(sourceDocument); <del> } <del> } <del> <del> listOfSourceDocuements.removeAll(sourceDocumentsinIgnorState); <add> List<SourceDocument> listOfSourceDocuements= getListOfDocs(); <ide> <ide> // Index of the current source document in the list <ide> int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument()); <ide> { <ide> editor.reset(aTarget); <ide> // List of all Source Documents in the project <del> List<SourceDocument> listOfSourceDocuements = repository.listSourceDocuments(bModel <del> .getProject()); <del> <del> String username = SecurityContextHolder.getContext().getAuthentication().getName(); <del> User user = userRepository.get(username); <del> <del> List<SourceDocument> sourceDocumentsinIgnoreState = new ArrayList<SourceDocument>(); <del> for (SourceDocument sourceDocument : listOfSourceDocuements) { <del> if (repository.existsAnnotationDocument(sourceDocument, user) <del> && repository.getAnnotationDocument(sourceDocument, user).getState() <del> .equals(AnnotationDocumentState.IGNORE)) { <del> sourceDocumentsinIgnoreState.add(sourceDocument); <del> } <del> } <del> <del> listOfSourceDocuements.removeAll(sourceDocumentsinIgnoreState); <add> List<SourceDocument> listOfSourceDocuements= getListOfDocs(); <ide> <ide> // Index of the current source document in the list <ide> int currentDocumentIndex = listOfSourceDocuements.indexOf(bModel.getDocument()); <ide> } <ide> }); <ide> } <add> <add> private List<SourceDocument> getListOfDocs() { <add> String username = SecurityContextHolder.getContext().getAuthentication().getName(); <add> User user = userRepository.get(username); <add> // List of all Source Documents in the project <add> List<SourceDocument> listOfSourceDocuements = repository.listSourceDocuments(bModel.getProject()); <add> List<SourceDocument> sourceDocumentsinIgnoreState = new ArrayList<SourceDocument>(); <add> for (SourceDocument sourceDocument : listOfSourceDocuements) { <add> if (repository.existsAnnotationDocument(sourceDocument, user) && repository <add> .getAnnotationDocument(sourceDocument, user).getState().equals(AnnotationDocumentState.IGNORE)) { <add> sourceDocumentsinIgnoreState.add(sourceDocument); <add> } <add> } <add> <add> listOfSourceDocuements.removeAll(sourceDocumentsinIgnoreState); <add> return listOfSourceDocuements; <add> } <ide> <ide> private void updateSentenceAddress(JCas aJCas, AjaxRequestTarget aTarget) <ide> throws UIMAException, IOException, ClassNotFoundException <ide> <ide> String labelText = ""; <ide> if (bModel.getDocument() != null) { <add> <add> List<SourceDocument> listofDoc = getListOfDocs(); <add> <add> int docIndex = listofDoc.indexOf(bModel.getDocument())+1; <add> <ide> totalNumberOfSentence = BratAjaxCasUtil.getNumberOfPages(aJCas); <ide> <ide> // If only one page, start displaying from sentence 1 <ide> } <ide> <ide> labelText = "showing " + firstSentenceNumber + "-" + lastSentenceNumber + " of " <del> + totalNumberOfSentence + " sentences"; <add> + totalNumberOfSentence + " sentences [document " <add> + docIndex +" of "+ listofDoc.size()+"]"; <ide> <ide> } <ide> else {
Java
apache-2.0
299c9da651faf2487d1c6c3c07d2567c36696270
0
Orange-OpenSource/wro4j-taglib
/* * Copyright 2011 France Télécom * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * This file was first taken from Spring 3.0.2, and then modified. * * Original copyright is : * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.francetelecom.saasstore.wro4j.taglib; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Package-protected helper class for {@link AntPathMatcher}. Tests whether or * not a string matches against a pattern using a regular expression. * * <p> * The pattern may contain special characters: '*' means zero or more * characters; '?' means one and only one character; '{' and '}' indicate a URI * template pattern. * * @author Arjen Poutsma * @since 3.0 */ public class AntPathStringMatcher { private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*\\*?"); private final Pattern pattern; /** Construct a new instance of the <code>AntPatchStringMatcher</code>. */ public AntPathStringMatcher(String pattern) { this.pattern = createPattern(pattern); } private Pattern createPattern(String pattern) { StringBuilder patternBuilder = new StringBuilder(); Matcher m = GLOB_PATTERN.matcher(pattern); int end = 0; while (m.find()) { patternBuilder.append(quote(pattern, end, m.start())); String match = m.group(); if ("?".equals(match)) { patternBuilder.append('.'); } else if ("**".equals(match)) { patternBuilder.append(".*"); } else if ("*".equals(match)) { patternBuilder.append("[^/]*"); } end = m.end(); } patternBuilder.append(quote(pattern, end, pattern.length())); return Pattern.compile(patternBuilder.toString()); } private String quote(String s, int start, int end) { if (start == end) { return ""; } return Pattern.quote(s.substring(start, end)); } /** * Main entry point. * * @return <code>true</code> if the string matches against the pattern, or * <code>false</code> otherwise. */ public boolean match(String str) { Matcher matcher = pattern.matcher(str); return matcher.matches(); } }
src/main/java/com/francetelecom/saasstore/wro4j/taglib/AntPathStringMatcher.java
/* * Copyright 2011 France Télécom * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * This file was first taken from Spring 3.0.2, and then modified. * * Original copyright is : * Copyright 2002-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.francetelecom.saasstore.wro4j.taglib; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Package-protected helper class for {@link AntPathMatcher}. Tests whether or * not a string matches against a pattern using a regular expression. * * <p> * The pattern may contain special characters: '*' means zero or more * characters; '?' means one and only one character; '{' and '}' indicate a URI * template pattern. * * @author Arjen Poutsma * @since 3.0 */ public class AntPathStringMatcher { private static final Pattern GLOB_PATTERN = Pattern.compile("\\?|\\*\\*?"); private final Pattern pattern; /** Construct a new instance of the <code>AntPatchStringMatcher</code>. */ public AntPathStringMatcher(String pattern) { this.pattern = createPattern(pattern); } private Pattern createPattern(String pattern) { StringBuilder patternBuilder = new StringBuilder(); Matcher m = GLOB_PATTERN.matcher(pattern); int end = 0; while (m.find()) { patternBuilder.append(quote(pattern, end, m.start())); String match = m.group(); if ("?".equals(match)) { patternBuilder.append('.'); } else if ("**".equals(match)) { patternBuilder.append(".*"); } else if ("*".equals(match)) { patternBuilder.append("[^/]*"); } end = m.end(); } patternBuilder.append(quote(pattern, end, pattern.length())); return Pattern.compile(patternBuilder.toString()); } private String quote(String s, int start, int end) { if (start == end) { return ""; } return Pattern.quote(s.substring(start, end)); } /** * Main entry point. * * @return <code>true</code> if the string matches against the pattern, or * <code>false</code> otherwise. */ public boolean match(String str) { Matcher matcher = pattern.matcher(str); return matcher.matches(); } }
remove unused imports
src/main/java/com/francetelecom/saasstore/wro4j/taglib/AntPathStringMatcher.java
remove unused imports
<ide><path>rc/main/java/com/francetelecom/saasstore/wro4j/taglib/AntPathStringMatcher.java <ide> <ide> package com.francetelecom.saasstore.wro4j.taglib; <ide> <del>import java.util.LinkedList; <del>import java.util.List; <del>import java.util.Map; <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide>
Java
apache-2.0
ac9ea05a89d4a06b86592943ffe45580ec886e4b
0
weld/core,manovotn/core,antoinesd/weld-core,manovotn/core,manovotn/core,antoinesd/weld-core,weld/core,antoinesd/weld-core
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.resources; import static org.jboss.weld.logging.LoggerFactory.loggerFactory; import static org.jboss.weld.logging.messages.BeanManagerMessage.CANNOT_LOCATE_BEAN_MANAGER; import java.util.Hashtable; import java.util.Map.Entry; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.spi.ObjectFactory; import org.jboss.weld.Container; import org.jboss.weld.bootstrap.api.helpers.RegistrySingletonProvider; import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive; import org.jboss.weld.manager.BeanManagerImpl; import ch.qos.cal10n.IMessageConveyor; public class ManagerObjectFactory implements ObjectFactory { private final String contextId; public ManagerObjectFactory() { this(RegistrySingletonProvider.STATIC_INSTANCE); } public ManagerObjectFactory(String contextId) { this.contextId = contextId; } // Exception messages private static final IMessageConveyor messageConveyor = loggerFactory().getMessageConveyor(); public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { if (Container.available(contextId)) { for (Entry<BeanDeploymentArchive, BeanManagerImpl> entry : Container.instance(contextId).beanDeploymentArchives().entrySet()) { if (entry.getKey().getId().equals("flat")) { return entry.getValue().getCurrent(); } } throw new NamingException(messageConveyor.getMessage(CANNOT_LOCATE_BEAN_MANAGER)); } else { throw new NamingException(messageConveyor.getMessage(CANNOT_LOCATE_BEAN_MANAGER)); } } }
impl/src/main/java/org/jboss/weld/resources/ManagerObjectFactory.java
/* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.weld.resources; import ch.qos.cal10n.IMessageConveyor; import org.jboss.weld.Container; import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive; import org.jboss.weld.manager.BeanManagerImpl; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; import javax.naming.spi.ObjectFactory; import java.util.Hashtable; import java.util.Map.Entry; import static org.jboss.weld.logging.LoggerFactory.loggerFactory; import static org.jboss.weld.logging.messages.BeanManagerMessage.CANNOT_LOCATE_BEAN_MANAGER; public class ManagerObjectFactory implements ObjectFactory { private final String contextId; public ManagerObjectFactory(String contextId) { this.contextId = contextId; } // Exception messages private static final IMessageConveyor messageConveyor = loggerFactory().getMessageConveyor(); public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception { if (Container.available(contextId)) { for (Entry<BeanDeploymentArchive, BeanManagerImpl> entry : Container.instance(contextId).beanDeploymentArchives().entrySet()) { if (entry.getKey().getId().equals("flat")) { return entry.getValue().getCurrent(); } } throw new NamingException(messageConveyor.getMessage(CANNOT_LOCATE_BEAN_MANAGER)); } else { throw new NamingException(messageConveyor.getMessage(CANNOT_LOCATE_BEAN_MANAGER)); } } }
Fix failing servlet tests
impl/src/main/java/org/jboss/weld/resources/ManagerObjectFactory.java
Fix failing servlet tests
<ide><path>mpl/src/main/java/org/jboss/weld/resources/ManagerObjectFactory.java <ide> */ <ide> package org.jboss.weld.resources; <ide> <del>import ch.qos.cal10n.IMessageConveyor; <del>import org.jboss.weld.Container; <del>import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive; <del>import org.jboss.weld.manager.BeanManagerImpl; <add>import static org.jboss.weld.logging.LoggerFactory.loggerFactory; <add>import static org.jboss.weld.logging.messages.BeanManagerMessage.CANNOT_LOCATE_BEAN_MANAGER; <add> <add>import java.util.Hashtable; <add>import java.util.Map.Entry; <ide> <ide> import javax.naming.Context; <ide> import javax.naming.Name; <ide> import javax.naming.NamingException; <ide> import javax.naming.spi.ObjectFactory; <del>import java.util.Hashtable; <del>import java.util.Map.Entry; <ide> <del>import static org.jboss.weld.logging.LoggerFactory.loggerFactory; <del>import static org.jboss.weld.logging.messages.BeanManagerMessage.CANNOT_LOCATE_BEAN_MANAGER; <add>import org.jboss.weld.Container; <add>import org.jboss.weld.bootstrap.api.helpers.RegistrySingletonProvider; <add>import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive; <add>import org.jboss.weld.manager.BeanManagerImpl; <add> <add>import ch.qos.cal10n.IMessageConveyor; <ide> <ide> public class ManagerObjectFactory implements ObjectFactory { <ide> private final String contextId; <add> <add> public ManagerObjectFactory() { <add> this(RegistrySingletonProvider.STATIC_INSTANCE); <add> } <ide> <ide> public ManagerObjectFactory(String contextId) { <ide> this.contextId = contextId;
Java
agpl-3.0
d214c94157df57f54b697e91344da87a16979516
0
aihua/opennms,rdkgit/opennms,rdkgit/opennms,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,tdefilip/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,rdkgit/opennms,roskens/opennms-pre-github,aihua/opennms,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms
// // Copyright (C) 2002 Sortova Consulting Group, Inc. All rights reserved. // Parts Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.sortova.com/ // // // // Tab Size = 8 // // SnmpPduTrap.java,v 1.1.1.1 2001/11/11 17:27:22 ben Exp // // // // RFC 1902: Structure of Management Information for SNMPv2 // // PDU ::= // SEQUENCE { // request-id INTEGER32 // error-status INTEGER // error-index INTEGER // Variable Bindings // } // // BulkPDU ::= // SEQUENCE { // request-id INTEGER32 // non-repeaters INTEGER // max-repetitions INTEGER // Variable Bindings // } // // // RFC 1157: A Simple Network Management Protocol (SNMP) // // PDU ::= // SEQUENCE { // request-id INTEGER // error-status INTEGER // error-index INTEGER // Variable Bindings // } // // TrapPDU ::= // SEQUENCE { // enterprise OBJECTID // agent-address NetworkAddress // generic-trap INTEGER // specific-trap INTEGER // time-stamp TIMETICKS // Variable Bindings // } // package org.opennms.protocols.snmp; import java.lang.*; import java.util.*; import org.opennms.protocols.snmp.asn1.AsnEncoder; import org.opennms.protocols.snmp.asn1.AsnEncodingException; import org.opennms.protocols.snmp.asn1.AsnDecodingException; import org.opennms.protocols.snmp.asn1.ASN1; import org.opennms.protocols.snmp.SnmpSMI; import org.opennms.protocols.snmp.SnmpSyntax; import org.opennms.protocols.snmp.SnmpUtil; import org.opennms.protocols.snmp.SnmpInt32; import org.opennms.protocols.snmp.SnmpVarBind; import org.opennms.protocols.snmp.SnmpPduPacket; /** * The SnmpPduTrap object represents the SNMP Protoco Data Unit * for an SNMP Trap. The PDU format for a TRAP is not similar * to the PDU format for other V1 types, and thus the SnmpPduTrap * object does not extend the SnmpPduPacket class. * * @author <a href="mailto:[email protected]">Brian Weaver</a> * @author <a href="http://www.opennms.org">OpenNMS</a> * @version 1.1.1.1 * */ public class SnmpPduTrap extends Object implements SnmpSyntax, Cloneable { /** * The trap's enterprise object identifier */ private SnmpObjectId m_enterprise; /** * The IP Address of the remote agent sending the * trap. */ private SnmpIPAddress m_agentAddr; /** * The generic trap number. */ private int m_generic; /** * The specific trap number. */ private int m_specific; /** * The timestamp for when the trap occured. This * should be the sysUpTime from the remote system. */ private long m_tstamp; /** * The list of variable bindings for the trap. */ private ArrayList m_variables; /** * The ASN.1 type for the SNMPv1 Trap. */ public final static int TRAP = (int)(ASN1.CONTEXT | ASN1.CONSTRUCTOR | 4) + 256; /** * Generic trap type: cold start. */ public final static int GenericColdStart = 0; /** * Generic trap type: warm start. */ public final static int GenericWarmStart = 1; /** * Generic trap type: link down. */ public final static int GenericLinkDown = 2; /** * Generic trap type: link up. */ public final static int GenericLinkUp = 3; /** * Generic trap type: authentication-failure. */ public final static int GenericAuthenticationFailure = 4; /** * Generic trap type: EGP Neighbor Loss. */ public final static int GenericEgpNeighborLoss = 5; /** * Generic trap type: Enterprise Specific. */ public final static int GenericEnterpriseSpecific = 6; /** * Constructs a new SnmpPduTrap with the default values. * */ public SnmpPduTrap( ) { m_enterprise = new SnmpObjectId(); m_agentAddr = new SnmpIPAddress(); m_generic = 0; m_specific = 0; m_tstamp = 0L; m_variables = new ArrayList(); } /** * Constructs a new trap pdu that is identical to the * passed pdu. * * @param second The object to copy. * */ protected SnmpPduTrap(SnmpPduTrap second) { m_enterprise = second.m_enterprise; m_agentAddr = second.m_agentAddr; m_generic = second.m_generic; m_specific = second.m_specific; m_tstamp = second.m_tstamp; m_variables = new ArrayList(second.m_variables.size()); for(int x = second.m_variables.size() - 1; x >= 0; x--) { m_variables.set(x, ((SnmpVarBind)(second.m_variables.get(x))).duplicate()); } } /** * Used to get the enterpise identifier * of the trap. * */ public SnmpObjectId getEnterprise() { return m_enterprise; } /** * Sets the enterprise identifier for the trap. * * @param id The object identifier. */ public void setEnterprise(SnmpObjectId id) { m_enterprise = (SnmpObjectId)id.clone(); } /** * Sets the enterprise identifier for the trap. * The string must be in the format of a dotted * decimal object identifier. * * @param id The new identifier. * */ public void setEnterprise(String id) { m_enterprise = new SnmpObjectId(id); } /** * Gets the remote agent's IP address. * */ public SnmpIPAddress getAgentAddress() { return m_agentAddr; } /** * Sets the remote agent's IP address. * * @param addr The remote agent's ip address. */ public void setAgentAddress(SnmpIPAddress addr) { m_agentAddr = addr; } /** * Returns the generic code for the trap. */ public int getGeneric( ) { return m_generic; } /** * Sets the generic code for the trap. * * @param generic The new generic code for the trap. */ public void setGeneric(int generic) { m_generic = generic; } /** * Returns the specific code for the trap. * */ public int getSpecific() { return m_specific; } /** * Sets the specific type for the trap. * * @param spec The new specific identifier. * */ public void setSpecific(int spec) { m_specific = spec; } /** * Returns the timeticks from the trap. * */ public long getTimeStamp( ) { return m_tstamp; } /** * Set's the timeticks in the trap. * * @param ts The timeticks for the trap. * */ public void setTimeStamp(long ts) { m_tstamp = ts; } /** * Returns the number of variables contained * in the PDU. * */ public int getLength() { return m_variables.size(); } /** * Adds a new variable to the protocol data unit. * The variable is added at the end of the list * * @param vb The new variable to add */ public void addVarBind(SnmpVarBind vb) { m_variables.add(vb); } /** * Adds a variable at a specific index. * * @param ndx The index of the variable * @param vb The new variable. * */ public void addVarBindAt(int ndx, SnmpVarBind vb) { m_variables.add(ndx, vb); } /** * Retrieves the variable at the specific * index. * * @param ndx The index of the variable * * @return The variable at the specified index * */ public SnmpVarBind getVarBindAt(int ndx) { return ((SnmpVarBind)(m_variables.get(ndx))); } /** * Sets the specific variable at the requested * location. * * @param ndx The location to set * @param vb The new variable * */ public void setVarBindAt(int ndx, SnmpVarBind vb) { m_variables.set(ndx, vb); } /** * Removes the variable as defined by the index * * @param ndx The index of the variable to remove * * @return The removed variable * */ public SnmpVarBind removeVarBindAt(int ndx) { return (SnmpVarBind) m_variables.remove(ndx); } /** * Returns a list of all the variables managed by * this protocol data unit. * * @return An array of the internal variable. * */ public SnmpVarBind[] toVarBindArray( ) { SnmpVarBind[] vblist = new SnmpVarBind[m_variables.size()]; return (SnmpVarBind[]) m_variables.toArray(vblist); } /** * Returns the PDU commmand in an 8-bit format * * @return The pdu command */ public byte typeId() { return (byte)(TRAP & 0xff); } /** * Encodes the protocol data unit using the passed encoder and stores * the results in the passed buffer. An exception is thrown if an * error occurs with the encoding of the information. * * @param buf The buffer to write the encoded information. * @param offset The offset to start writing information * @param encoder The encoder object. * * @return The offset of the byte immediantly after the last encoded byte. * * @exception AsnEncodingException Thrown if the encoder finds an error in the * buffer. */ public int encodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnEncodingException { int begin = offset; // // encode the enterprise id & address // offset = m_enterprise.encodeASN(buf, offset, encoder); offset = m_agentAddr.encodeASN(buf, offset, encoder); // // encode the request id, error status (non-repeaters), // and error index (max-repititions). // { SnmpInt32 val = new SnmpInt32(m_generic); offset = val.encodeASN(buf, offset, encoder); val.setValue(m_specific); offset = val.encodeASN(buf, offset, encoder); } // // next is the timestamp // { SnmpTimeTicks val = new SnmpTimeTicks(m_tstamp); offset = val.encodeASN(buf, offset, encoder); } // // mark the beginning of the vblist // int vbbegin = offset; // // Now encode the SnmpVarBinds! // int sz = m_variables.size(); for(int x = 0; x < sz; x++) { SnmpVarBind ref = (SnmpVarBind) m_variables.get(x); offset = ref.encodeASN(buf, offset, encoder); } // // now mark the end of the varbinds // int pivot = offset; // // build the header for the varbind list // offset = encoder.buildHeader(buf, offset, SnmpVarBind.ASNTYPE, pivot - vbbegin); // // rotate the varbind header to the front. // Then reset the pivot point // SnmpUtil.rotate(buf, vbbegin, pivot, offset); pivot = offset; // // Now encode the header for the PDU, // then rotate the header to the front. // offset = encoder.buildHeader(buf, offset, typeId(), pivot - begin); SnmpUtil.rotate(buf, begin, pivot, offset); return offset; } /** * Decodes the protocol data unit from the passed buffer. If an error * occurs during the decoding sequence then an AsnDecodingException is * thrown by the method. The value is decoded using the AsnEncoder * passed to the object. * * @param buf The encode buffer * @param offset The offset byte to begin decoding * @param encoder The decoder object. * * @return The index of the byte immediantly after the last decoded * byte of information. * * @exception AsnDecodingException Thrown by the encoder if an error * occurs trying to decode the data buffer. */ public int decodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnDecodingException { Object[] rVals = encoder.parseHeader(buf, offset); offset = ((Integer)rVals[0]).intValue(); int cmd = ((Byte)rVals[1]).intValue(); int length = ((Integer)rVals[2]).intValue(); int begin = offset; // // set the command // if(cmd < 0) cmd += 256; // wrap the value to a positive quantity! if(TRAP != cmd) throw new AsnDecodingException("Invalid SNMP command, Not a Trap"); offset = m_enterprise.decodeASN(buf, offset, encoder); offset = m_agentAddr.decodeASN(buf, offset, encoder); // // get an 32-bit integer to decode values // { SnmpInt32 val = new SnmpInt32(); offset = val.decodeASN(buf, offset, encoder); m_generic = val.getValue(); offset = val.decodeASN(buf, offset, encoder); m_specific = val.getValue(); } // // Get the timestamp // { SnmpTimeTicks val = new SnmpTimeTicks(); offset = val.decodeASN(buf, offset, encoder); m_tstamp = val.getValue(); } // // get the total length of all // the variables // rVals = encoder.parseHeader(buf, offset); offset = ((Integer)rVals[0]).intValue(); length = ((Integer)rVals[2]).intValue(); byte asnType = ((Byte)rVals[1]).byteValue(); // // check the ASN.1 type // if(asnType != SnmpVarBind.ASNTYPE) throw new AsnDecodingException("Invalid SNMP variable list"); // // set the beginning // begin = offset; // // clean out the current variables // m_variables.clear(); // // decode the SnmpVarBinds // SnmpVarBind vb = new SnmpVarBind(); while(length > 0) { offset = vb.decodeASN(buf, offset, encoder); length-= (offset - begin); begin = offset; // // add the varbind // m_variables.add(vb.duplicate()); } return offset; } public SnmpSyntax duplicate() { return new SnmpPduTrap(this); } public Object clone( ) { return new SnmpPduTrap(this); } }
src/joesnmp/org/opennms/protocols/snmp/SnmpPduTrap.java
// // Copyright (C) 2002 Sortova Consulting Group, Inc. All rights reserved. // Parts Copyright (C) 1999-2001 Oculan Corp. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // For more information contact: // OpenNMS Licensing <[email protected]> // http://www.opennms.org/ // http://www.sortova.com/ // // // // Tab Size = 8 // // SnmpPduTrap.java,v 1.1.1.1 2001/11/11 17:27:22 ben Exp // // // // RFC 1902: Structure of Management Information for SNMPv2 // // PDU ::= // SEQUENCE { // request-id INTEGER32 // error-status INTEGER // error-index INTEGER // Variable Bindings // } // // BulkPDU ::= // SEQUENCE { // request-id INTEGER32 // non-repeaters INTEGER // max-repetitions INTEGER // Variable Bindings // } // // // RFC 1157: A Simple Network Management Protocol (SNMP) // // PDU ::= // SEQUENCE { // request-id INTEGER // error-status INTEGER // error-index INTEGER // Variable Bindings // } // // TrapPDU ::= // SEQUENCE { // enterprise OBJECTID // agent-address NetworkAddress // generic-trap INTEGER // specific-trap INTEGER // time-stamp TIMETICKS // Variable Bindings // } // package org.opennms.protocols.snmp; import java.lang.*; import java.util.*; import org.opennms.protocols.snmp.asn1.AsnEncoder; import org.opennms.protocols.snmp.asn1.AsnEncodingException; import org.opennms.protocols.snmp.asn1.AsnDecodingException; import org.opennms.protocols.snmp.asn1.ASN1; import org.opennms.protocols.snmp.SnmpSMI; import org.opennms.protocols.snmp.SnmpSyntax; import org.opennms.protocols.snmp.SnmpUtil; import org.opennms.protocols.snmp.SnmpInt32; import org.opennms.protocols.snmp.SnmpVarBind; import org.opennms.protocols.snmp.SnmpPduPacket; /** * The SnmpPduTrap object represents the SNMP Protoco Data Unit * for an SNMP Trap. The PDU format for a TRAP is not similar * to the PDU format for other V1 types, and thus the SnmpPduTrap * object does not extend the SnmpPduPacket class. * * @author <a href="mailto:[email protected]">Brian Weaver</a> * @author <a href="http://www.opennms.org">OpenNMS</a> * @version 1.1.1.1 * */ public class SnmpPduTrap extends Object implements SnmpSyntax, Cloneable { /** * The trap's enterprise object identifier */ private SnmpObjectId m_enterprise; /** * The IP Address of the remote agent sending the * trap. */ private SnmpIPAddress m_agentAddr; /** * The generic trap number. */ private int m_generic; /** * The specific trap number. */ private int m_specific; /** * The timestamp for when the trap occured. This * should be the sysUpTime from the remote system. */ private long m_tstamp; /** * The list of variable bindings for the trap. */ private ArrayList m_variables; /** * The ASN.1 type for the SNMPv1 Trap. */ public final static int TRAP = (int)(ASN1.CONTEXT | ASN1.CONSTRUCTOR | 4) + 256; /** * Generic trap type: cold start. */ public final static int GenericColdStart = 0; /** * Generic trap type: warm start. */ public final static int GenericWarmStart = 1; /** * Generic trap type: link down. */ public final static int GenericLinkDown = 2; /** * Generic trap type: link up. */ public final static int GenericLinkUp = 3; /** * Generic trap type: authentication-failure. */ public final static int GenericAuthenticationFailure = 4; /** * Generic trap type: EGP Neighbor Loss. */ public final static int GenericEgpNeighborLoss = 5; /** * Generic trap type: Enterprise Specific. */ public final static int GenericEnterpriseSpecific = 6; /** * Constructs a new SnmpPduTrap with the default values. * */ public SnmpPduTrap( ) { m_enterprise = new SnmpObjectId(); m_agentAddr = new SnmpIPAddress(); m_generic = 0; m_specific = 0; m_tstamp = 0L; m_variables = new ArrayList(); } /** * Constructs a new trap pdu that is identical to the * passed pdu. * * @param second The object to copy. * */ protected SnmpPduTrap(SnmpPduTrap second) { m_enterprise = second.m_enterprise; m_agentAddr = second.m_agentAddr; m_generic = second.m_generic; m_specific = second.m_specific; m_tstamp = second.m_tstamp; m_variables = new ArrayList(second.m_variables.size()); for(int x = second.m_variables.size() - 1; x >= 0; --x) { m_variables.set(x, ((SnmpVarBind)(second.m_variables.get(x))).duplicate()); } } /** * Used to get the enterpise identifier * of the trap. * */ public SnmpObjectId getEnterprise() { return m_enterprise; } /** * Sets the enterprise identifier for the trap. * * @param id The object identifier. */ public void setEnterprise(SnmpObjectId id) { m_enterprise = (SnmpObjectId)id.clone(); } /** * Sets the enterprise identifier for the trap. * The string must be in the format of a dotted * decimal object identifier. * * @param id The new identifier. * */ public void setEnterprise(String id) { m_enterprise = new SnmpObjectId(id); } /** * Gets the remote agent's IP address. * */ public SnmpIPAddress getAgentAddress() { return m_agentAddr; } /** * Sets the remote agent's IP address. * * @param addr The remote agent's ip address. */ public void setAgentAddress(SnmpIPAddress addr) { m_agentAddr = addr; } /** * Returns the generic code for the trap. */ public int getGeneric( ) { return m_generic; } /** * Sets the generic code for the trap. * * @param generic The new generic code for the trap. */ public void setGeneric(int generic) { m_generic = generic; } /** * Returns the specific code for the trap. * */ public int getSpecific() { return m_specific; } /** * Sets the specific type for the trap. * * @param spec The new specific identifier. * */ public void setSpecific(int spec) { m_specific = spec; } /** * Returns the timeticks from the trap. * */ public long getTimeStamp( ) { return m_tstamp; } /** * Set's the timeticks in the trap. * * @param ts The timeticks for the trap. * */ public void setTimeStamp(long ts) { m_tstamp = ts; } /** * Returns the number of variables contained * in the PDU. * */ public int getLength() { return m_variables.size(); } /** * Adds a new variable to the protocol data unit. * The variable is added at the end of the list * * @param vb The new variable to add */ public void addVarBind(SnmpVarBind vb) { m_variables.add(vb); } /** * Adds a variable at a specific index. * * @param ndx The index of the variable * @param vb The new variable. * */ public void addVarBindAt(int ndx, SnmpVarBind vb) { m_variables.add(ndx, vb); } /** * Retrieves the variable at the specific * index. * * @param ndx The index of the variable * * @return The variable at the specified index * */ public SnmpVarBind getVarBindAt(int ndx) { return ((SnmpVarBind)(m_variables.get(ndx))); } /** * Sets the specific variable at the requested * location. * * @param ndx The location to set * @param vb The new variable * */ public void setVarBindAt(int ndx, SnmpVarBind vb) { m_variables.set(ndx, vb); } /** * Removes the variable as defined by the index * * @param ndx The index of the variable to remove * * @return The removed variable * */ public SnmpVarBind removeVarBindAt(int ndx) { return (SnmpVarBind) m_variables.remove(ndx); } /** * Returns a list of all the variables managed by * this protocol data unit. * * @return An array of the internal variable. * */ public SnmpVarBind[] toVarBindArray( ) { SnmpVarBind[] vblist = new SnmpVarBind[m_variables.size()]; return (SnmpVarBind[]) m_variables.toArray(vblist); } /** * Returns the PDU commmand in an 8-bit format * * @return The pdu command */ public byte typeId() { return (byte)(TRAP & 0xff); } /** * Encodes the protocol data unit using the passed encoder and stores * the results in the passed buffer. An exception is thrown if an * error occurs with the encoding of the information. * * @param buf The buffer to write the encoded information. * @param offset The offset to start writing information * @param encoder The encoder object. * * @return The offset of the byte immediantly after the last encoded byte. * * @exception AsnEncodingException Thrown if the encoder finds an error in the * buffer. */ public int encodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnEncodingException { int begin = offset; // // encode the enterprise id & address // offset = m_enterprise.encodeASN(buf, offset, encoder); offset = m_agentAddr.encodeASN(buf, offset, encoder); // // encode the request id, error status (non-repeaters), // and error index (max-repititions). // { SnmpInt32 val = new SnmpInt32(m_generic); offset = val.encodeASN(buf, offset, encoder); val.setValue(m_specific); offset = val.encodeASN(buf, offset, encoder); } // // next is the timestamp // { SnmpTimeTicks val = new SnmpTimeTicks(m_tstamp); offset = val.encodeASN(buf, offset, encoder); } // // mark the beginning of the vblist // int vbbegin = offset; // // Now encode the SnmpVarBinds! // int sz = m_variables.size(); for(int x = 0; x < sz; x++) { SnmpVarBind ref = (SnmpVarBind) m_variables.get(x); offset = ref.encodeASN(buf, offset, encoder); } // // now mark the end of the varbinds // int pivot = offset; // // build the header for the varbind list // offset = encoder.buildHeader(buf, offset, SnmpVarBind.ASNTYPE, pivot - vbbegin); // // rotate the varbind header to the front. // Then reset the pivot point // SnmpUtil.rotate(buf, vbbegin, pivot, offset); pivot = offset; // // Now encode the header for the PDU, // then rotate the header to the front. // offset = encoder.buildHeader(buf, offset, typeId(), pivot - begin); SnmpUtil.rotate(buf, begin, pivot, offset); return offset; } /** * Decodes the protocol data unit from the passed buffer. If an error * occurs during the decoding sequence then an AsnDecodingException is * thrown by the method. The value is decoded using the AsnEncoder * passed to the object. * * @param buf The encode buffer * @param offset The offset byte to begin decoding * @param encoder The decoder object. * * @return The index of the byte immediantly after the last decoded * byte of information. * * @exception AsnDecodingException Thrown by the encoder if an error * occurs trying to decode the data buffer. */ public int decodeASN(byte[] buf, int offset, AsnEncoder encoder) throws AsnDecodingException { Object[] rVals = encoder.parseHeader(buf, offset); offset = ((Integer)rVals[0]).intValue(); int cmd = ((Byte)rVals[1]).intValue(); int length = ((Integer)rVals[2]).intValue(); int begin = offset; // // set the command // if(cmd < 0) cmd += 256; // wrap the value to a positive quantity! if(TRAP != cmd) throw new AsnDecodingException("Invalid SNMP command, Not a Trap"); offset = m_enterprise.decodeASN(buf, offset, encoder); offset = m_agentAddr.decodeASN(buf, offset, encoder); // // get an 32-bit integer to decode values // { SnmpInt32 val = new SnmpInt32(); offset = val.decodeASN(buf, offset, encoder); m_generic = val.getValue(); offset = val.decodeASN(buf, offset, encoder); m_specific = val.getValue(); } // // Get the timestamp // { SnmpTimeTicks val = new SnmpTimeTicks(); offset = val.decodeASN(buf, offset, encoder); m_tstamp = val.getValue(); } // // get the total length of all // the variables // rVals = encoder.parseHeader(buf, offset); offset = ((Integer)rVals[0]).intValue(); length = ((Integer)rVals[2]).intValue(); byte asnType = ((Byte)rVals[1]).byteValue(); // // check the ASN.1 type // if(asnType != SnmpVarBind.ASNTYPE) throw new AsnDecodingException("Invalid SNMP variable list"); // // set the beginning // begin = offset; // // clean out the current variables // m_variables.clear(); // // decode the SnmpVarBinds // SnmpVarBind vb = new SnmpVarBind(); while(length > 0) { offset = vb.decodeASN(buf, offset, encoder); length-= (offset - begin); begin = offset; // // add the varbind // m_variables.add(vb.duplicate()); } return offset; } public SnmpSyntax duplicate() { return new SnmpPduTrap(this); } public Object clone( ) { return new SnmpPduTrap(this); } }
Fixed bad increment in for loop. Bug 764
src/joesnmp/org/opennms/protocols/snmp/SnmpPduTrap.java
Fixed bad increment in for loop. Bug 764
<ide><path>rc/joesnmp/org/opennms/protocols/snmp/SnmpPduTrap.java <ide> m_specific = second.m_specific; <ide> m_tstamp = second.m_tstamp; <ide> m_variables = new ArrayList(second.m_variables.size()); <del> for(int x = second.m_variables.size() - 1; x >= 0; --x) <add> for(int x = second.m_variables.size() - 1; x >= 0; x--) <ide> { <ide> m_variables.set(x, ((SnmpVarBind)(second.m_variables.get(x))).duplicate()); <ide> }
Java
apache-2.0
476c24d45a556b625946319f4464a0916cfa3fef
0
crate/crate,crate/crate,crate/crate,EvilMcJerkface/crate,EvilMcJerkface/crate,EvilMcJerkface/crate
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.Query; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryShardContext; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue; /** * A mapper that indexes the field names of a document under <code>_field_names</code>. This mapper is typically useful in order * to have fast <code>exists</code> and <code>missing</code> queries/filters. * * Added in Elasticsearch 1.3. */ public class FieldNamesFieldMapper extends MetadataFieldMapper { public static final String NAME = "_field_names"; public static final String CONTENT_TYPE = "_field_names"; public static class Defaults { public static final String NAME = FieldNamesFieldMapper.NAME; public static final boolean ENABLED = true; public static final MappedFieldType FIELD_TYPE = new FieldNamesFieldType(); static { FIELD_TYPE.setIndexOptions(IndexOptions.DOCS); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setStored(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.setSearchAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.setName(NAME); FIELD_TYPE.freeze(); } } public static class Builder extends MetadataFieldMapper.Builder<Builder, FieldNamesFieldMapper> { private boolean enabled = Defaults.ENABLED; public Builder(MappedFieldType existing) { super(Defaults.NAME, existing == null ? Defaults.FIELD_TYPE : existing, Defaults.FIELD_TYPE); } @Override @Deprecated public Builder index(boolean index) { enabled(index); return super.index(index); } public Builder enabled(boolean enabled) { this.enabled = enabled; return this; } @Override public FieldNamesFieldMapper build(BuilderContext context) { setupFieldType(context); fieldType.setHasDocValues(false); FieldNamesFieldType fieldNamesFieldType = (FieldNamesFieldType)fieldType; fieldNamesFieldType.setEnabled(enabled); return new FieldNamesFieldMapper(fieldType, context.indexSettings()); } } public static class TypeParser implements MetadataFieldMapper.TypeParser { @Override public MetadataFieldMapper.Builder<?,?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Builder builder = new Builder(parserContext.mapperService().fullName(NAME)); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String fieldName = entry.getKey(); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { builder.enabled(nodeBooleanValue(fieldNode, name + ".enabled")); iterator.remove(); } } return builder; } @Override public MetadataFieldMapper getDefault(MappedFieldType fieldType, ParserContext context) { final Settings indexSettings = context.mapperService().getIndexSettings().getSettings(); if (fieldType != null) { return new FieldNamesFieldMapper(indexSettings, fieldType); } else { return parse(NAME, Collections.emptyMap(), context) .build(new BuilderContext(indexSettings, new ContentPath(1))); } } } public static final class FieldNamesFieldType extends TermBasedFieldType { private boolean enabled = Defaults.ENABLED; public FieldNamesFieldType() { } protected FieldNamesFieldType(FieldNamesFieldType ref) { super(ref); this.enabled = ref.enabled; } @Override public FieldNamesFieldType clone() { return new FieldNamesFieldType(this); } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; FieldNamesFieldType that = (FieldNamesFieldType) o; return enabled == that.enabled; } @Override public int hashCode() { return Objects.hash(super.hashCode(), enabled); } @Override public String typeName() { return CONTENT_TYPE; } @Override public void checkCompatibility(MappedFieldType fieldType, List<String> conflicts, boolean strict) { super.checkCompatibility(fieldType, conflicts, strict); if (strict) { FieldNamesFieldType other = (FieldNamesFieldType)fieldType; if (isEnabled() != other.isEnabled()) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [enabled] across all types."); } } } public void setEnabled(boolean enabled) { checkIfFrozen(); this.enabled = enabled; } public boolean isEnabled() { return enabled; } @Override public Query existsQuery(QueryShardContext context) { throw new UnsupportedOperationException("Cannot run exists query on _field_names"); } @Override public Query termQuery(Object value, QueryShardContext context) { throw new UnsupportedOperationException("Terms query on _field_names is no longer supported"); } } private FieldNamesFieldMapper(Settings indexSettings, MappedFieldType existing) { this(existing.clone(), indexSettings); } private FieldNamesFieldMapper(MappedFieldType fieldType, Settings indexSettings) { super(NAME, null, fieldType, Defaults.FIELD_TYPE, indexSettings); } @Override public FieldNamesFieldType fieldType() { return (FieldNamesFieldType) super.fieldType(); } @Override public void preParse(ParseContext context) { } @Override public void postParse(ParseContext context) throws IOException { } @Override public void parse(ParseContext context) throws IOException { // Adding values to the _field_names field is handled by the mappers for each field type } static Iterable<String> extractFieldNames(final String fullPath) { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { int endIndex = nextEndIndex(0); private int nextEndIndex(int index) { while (index < fullPath.length() && fullPath.charAt(index) != '.') { index += 1; } return index; } @Override public boolean hasNext() { return endIndex <= fullPath.length(); } @Override public String next() { final String result = fullPath.substring(0, endIndex); endIndex = nextEndIndex(endIndex + 1); return result; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } @Override protected void parseCreateField(ParseContext context, List<IndexableField> fields) throws IOException { if (fieldType().isEnabled() == false) { return; } for (ParseContext.Document document : context) { final List<String> paths = new ArrayList<>(document.getFields().size()); String previousPath = ""; // used as a sentinel - field names can't be empty for (IndexableField field : document.getFields()) { final String path = field.name(); if (path.equals(previousPath)) { // Sometimes mappers create multiple Lucene fields, eg. one for indexing, // one for doc values and one for storing. Deduplicating is not required // for correctness but this simple check helps save utf-8 conversions and // gives Lucene fewer values to deal with. continue; } paths.add(path); previousPath = path; } for (String path : paths) { for (String fieldName : extractFieldNames(path)) { if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { document.add(new Field(fieldType().name(), fieldName, fieldType())); } } } } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { boolean includeDefaults = params.paramAsBoolean("include_defaults", false); if (includeDefaults == false && fieldType().isEnabled() == Defaults.ENABLED) { return builder; } builder.startObject(NAME); if (includeDefaults || fieldType().isEnabled() != Defaults.ENABLED) { builder.field("enabled", fieldType().isEnabled()); } builder.endObject(); return builder; } }
es/es-server/src/main/java/org/elasticsearch/index/mapper/FieldNamesFieldMapper.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.apache.logging.log4j.LogManager; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.Query; import org.elasticsearch.common.logging.DeprecationLogger; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.query.QueryShardContext; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeBooleanValue; /** * A mapper that indexes the field names of a document under <code>_field_names</code>. This mapper is typically useful in order * to have fast <code>exists</code> and <code>missing</code> queries/filters. * * Added in Elasticsearch 1.3. */ public class FieldNamesFieldMapper extends MetadataFieldMapper { private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger( LogManager.getLogger(FieldNamesFieldMapper.class)); public static final String NAME = "_field_names"; public static final String CONTENT_TYPE = "_field_names"; public static class Defaults { public static final String NAME = FieldNamesFieldMapper.NAME; public static final boolean ENABLED = true; public static final MappedFieldType FIELD_TYPE = new FieldNamesFieldType(); static { FIELD_TYPE.setIndexOptions(IndexOptions.DOCS); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setStored(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.setSearchAnalyzer(Lucene.KEYWORD_ANALYZER); FIELD_TYPE.setName(NAME); FIELD_TYPE.freeze(); } } public static class Builder extends MetadataFieldMapper.Builder<Builder, FieldNamesFieldMapper> { private boolean enabled = Defaults.ENABLED; public Builder(MappedFieldType existing) { super(Defaults.NAME, existing == null ? Defaults.FIELD_TYPE : existing, Defaults.FIELD_TYPE); } @Override @Deprecated public Builder index(boolean index) { enabled(index); return super.index(index); } public Builder enabled(boolean enabled) { this.enabled = enabled; return this; } @Override public FieldNamesFieldMapper build(BuilderContext context) { setupFieldType(context); fieldType.setHasDocValues(false); FieldNamesFieldType fieldNamesFieldType = (FieldNamesFieldType)fieldType; fieldNamesFieldType.setEnabled(enabled); return new FieldNamesFieldMapper(fieldType, context.indexSettings()); } } public static class TypeParser implements MetadataFieldMapper.TypeParser { @Override public MetadataFieldMapper.Builder<?,?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Builder builder = new Builder(parserContext.mapperService().fullName(NAME)); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String fieldName = entry.getKey(); Object fieldNode = entry.getValue(); if (fieldName.equals("enabled")) { builder.enabled(nodeBooleanValue(fieldNode, name + ".enabled")); iterator.remove(); } } return builder; } @Override public MetadataFieldMapper getDefault(MappedFieldType fieldType, ParserContext context) { final Settings indexSettings = context.mapperService().getIndexSettings().getSettings(); if (fieldType != null) { return new FieldNamesFieldMapper(indexSettings, fieldType); } else { return parse(NAME, Collections.emptyMap(), context) .build(new BuilderContext(indexSettings, new ContentPath(1))); } } } public static final class FieldNamesFieldType extends TermBasedFieldType { private boolean enabled = Defaults.ENABLED; public FieldNamesFieldType() { } protected FieldNamesFieldType(FieldNamesFieldType ref) { super(ref); this.enabled = ref.enabled; } @Override public FieldNamesFieldType clone() { return new FieldNamesFieldType(this); } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; FieldNamesFieldType that = (FieldNamesFieldType) o; return enabled == that.enabled; } @Override public int hashCode() { return Objects.hash(super.hashCode(), enabled); } @Override public String typeName() { return CONTENT_TYPE; } @Override public void checkCompatibility(MappedFieldType fieldType, List<String> conflicts, boolean strict) { super.checkCompatibility(fieldType, conflicts, strict); if (strict) { FieldNamesFieldType other = (FieldNamesFieldType)fieldType; if (isEnabled() != other.isEnabled()) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [enabled] across all types."); } } } public void setEnabled(boolean enabled) { checkIfFrozen(); this.enabled = enabled; } public boolean isEnabled() { return enabled; } @Override public Query existsQuery(QueryShardContext context) { throw new UnsupportedOperationException("Cannot run exists query on _field_names"); } @Override public Query termQuery(Object value, QueryShardContext context) { if (isEnabled() == false) { throw new IllegalStateException("Cannot run [exists] queries if the [_field_names] field is disabled"); } DEPRECATION_LOGGER.deprecated( "terms query on the _field_names field is deprecated and will be removed, use exists query instead"); return super.termQuery(value, context); } } private FieldNamesFieldMapper(Settings indexSettings, MappedFieldType existing) { this(existing.clone(), indexSettings); } private FieldNamesFieldMapper(MappedFieldType fieldType, Settings indexSettings) { super(NAME, null, fieldType, Defaults.FIELD_TYPE, indexSettings); } @Override public FieldNamesFieldType fieldType() { return (FieldNamesFieldType) super.fieldType(); } @Override public void preParse(ParseContext context) { } @Override public void postParse(ParseContext context) throws IOException { } @Override public void parse(ParseContext context) throws IOException { // Adding values to the _field_names field is handled by the mappers for each field type } static Iterable<String> extractFieldNames(final String fullPath) { return new Iterable<String>() { @Override public Iterator<String> iterator() { return new Iterator<String>() { int endIndex = nextEndIndex(0); private int nextEndIndex(int index) { while (index < fullPath.length() && fullPath.charAt(index) != '.') { index += 1; } return index; } @Override public boolean hasNext() { return endIndex <= fullPath.length(); } @Override public String next() { final String result = fullPath.substring(0, endIndex); endIndex = nextEndIndex(endIndex + 1); return result; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }; } @Override protected void parseCreateField(ParseContext context, List<IndexableField> fields) throws IOException { if (fieldType().isEnabled() == false) { return; } for (ParseContext.Document document : context) { final List<String> paths = new ArrayList<>(document.getFields().size()); String previousPath = ""; // used as a sentinel - field names can't be empty for (IndexableField field : document.getFields()) { final String path = field.name(); if (path.equals(previousPath)) { // Sometimes mappers create multiple Lucene fields, eg. one for indexing, // one for doc values and one for storing. Deduplicating is not required // for correctness but this simple check helps save utf-8 conversions and // gives Lucene fewer values to deal with. continue; } paths.add(path); previousPath = path; } for (String path : paths) { for (String fieldName : extractFieldNames(path)) { if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { document.add(new Field(fieldType().name(), fieldName, fieldType())); } } } } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { boolean includeDefaults = params.paramAsBoolean("include_defaults", false); if (includeDefaults == false && fieldType().isEnabled() == Defaults.ENABLED) { return builder; } builder.startObject(NAME); if (includeDefaults || fieldType().isEnabled() != Defaults.ENABLED) { builder.field("enabled", fieldType().isEnabled()); } builder.endObject(); return builder; } }
Make sure we don't utilize FieldNamesFieldMapper.termQuery
es/es-server/src/main/java/org/elasticsearch/index/mapper/FieldNamesFieldMapper.java
Make sure we don't utilize FieldNamesFieldMapper.termQuery
<ide><path>s/es-server/src/main/java/org/elasticsearch/index/mapper/FieldNamesFieldMapper.java <ide> <ide> package org.elasticsearch.index.mapper; <ide> <del>import org.apache.logging.log4j.LogManager; <ide> import org.apache.lucene.document.Field; <ide> import org.apache.lucene.index.IndexOptions; <ide> import org.apache.lucene.index.IndexableField; <ide> import org.apache.lucene.search.Query; <del>import org.elasticsearch.common.logging.DeprecationLogger; <ide> import org.elasticsearch.common.lucene.Lucene; <ide> import org.elasticsearch.common.settings.Settings; <ide> import org.elasticsearch.common.xcontent.XContentBuilder; <ide> * Added in Elasticsearch 1.3. <ide> */ <ide> public class FieldNamesFieldMapper extends MetadataFieldMapper { <del> <del> private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger( <del> LogManager.getLogger(FieldNamesFieldMapper.class)); <ide> <ide> public static final String NAME = "_field_names"; <ide> <ide> <ide> @Override <ide> public Query termQuery(Object value, QueryShardContext context) { <del> if (isEnabled() == false) { <del> throw new IllegalStateException("Cannot run [exists] queries if the [_field_names] field is disabled"); <del> } <del> DEPRECATION_LOGGER.deprecated( <del> "terms query on the _field_names field is deprecated and will be removed, use exists query instead"); <del> return super.termQuery(value, context); <add> throw new UnsupportedOperationException("Terms query on _field_names is no longer supported"); <ide> } <ide> } <ide>
JavaScript
mit
36c30558012165f0392718882eb70d9636541136
0
past/nodify
$(document).ready(function() { // Fetch the user data. $.get('/api/init', function (data) { var projects, project, handlers, handler, h, p, edit, env; window.data = data; projects = data.user.projects; for (p in projects) { if (projects.hasOwnProperty(p) && p !== 'length') { project = projects[p]; log('project=' + project.name); if (data.user.lastProject && project.name === data.user.lastProject.name) $('#projects').append('<option value="value" selected>' + project.name + '</option>'); else $('#projects').append('<option value="value">' + project.name + '</option>'); } } handlers = projects['MyProject'].handlers; for (h in handlers) { if (handlers.hasOwnProperty(h) && h !== 'length') { handler = handlers[h]; log('method=' + handler.method + ',uri=' + handler.uri); // Get the DOM node with the Bespin instance inside edit = document.getElementById("editor1"); // Get the environment variable. env = edit.bespin; // Get the editor. if (env && env.editor) env.editor.value = data.user.projects['MyProject'].handlers['GET /'].code; } }; }); // Register the loading indicator on ajax events. $.loading({onAjax:true, text: 'Working...', effect: 'fade', delay: 100}); function nodifyMsg(msg, type) { var backgroundColor = ""; if (type === "error") { backgroundColor = "red"; // This will not work //$("#message_from_top").css("color","black"); } else { backgroundColor = "#4C4A41"; // This will not work // $("#message_from_top").css("color","#E2BE38"); } var options = {id: 'message_from_top', position: 'top', size: 20, backgroundColor: backgroundColor, delay: 3500, speed: 500, fontSize: '16px' }; $.showMessage(msg, options) } function consoleAppend (msg, type) { if (type === 'error') { msg = 'Error:\n------\n' + msg; } else { msg = 'Output:\n-------\n' + msg; } var c = $("#console"); var contents = c.val(); c.val(contents + '\n' + msg); c.css("display", "block"); // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) env.editor.dimensionsChanged(); } $('#save-btn').click(function() { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; $.ajax({ url: '/api/init', type: 'PUT', data: { method: 'GET', project: 'MyProject', code: encodeURIComponent(editor.value), uri: '/' }, success: function () { nodifyMsg("The contents were saved"); editor.focus = true; }, dataType: "text", error: function(request, status, error) { nodifyMsg("Error while saving file: " + error, "error"); } }); }); $('#revert-btn').click(function() { $.get('/api/init', function (data) { window.data = data; // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; editor.value = data.user.projects['MyProject'].handlers['GET /'].code; nodifyMsg("The contents were reverted"); editor.focus = true; }); }); $('#lnk-start').click(function() { $.ajax({ url: '/api/deploy', type: 'POST', data: {'project': 'MyProject'}, success: function (data) { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; consoleAppend(data); editor.focus = true; }, error: function(request, status, error) { consoleAppend(error, "error"); }, dataType: 'text' }); }); $('#lnk-stop').click(function() { $.ajax({ url: '/api/terminate', type: 'POST', data: {'project': 'MyProject'}, success: function (data) { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; nodifyMsg("The program was terminated"); editor.focus = true; }, error: function(request, status, error) { consoleAppend(error, "error"); }, dataType: 'text' }); }); $('#lnk-new').click(function() { $("#dialog-project-new").dialog('open'); }); $('#btn-project-new-cancel').click(function() { $("#dialog-project-new").dialog('close'); }); $('#btn-project-new-submit').click(function() { var newProjectName = $("btn-project-new-name").val(); $.ajax({ url: '/api/init', type: 'PUT', data: { project: encodeURIComponent(newProjectName) }, success: function () { $("#dialog-project-new").dialog('close'); nodifyMsg("The new project was saved"); }, dataType: "text", error: function(request, status, error) { $("#dialog-project-new").dialog('close'); nodifyMsg("Error while saving file: " + error, "error"); } }); }); $("#dialog-project-new").dialog({ autoOpen: false }); $("btn-project-new-submit").button(); }); window.onBespinLoad = function() { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. var editor = env.editor; env.settings.set("tabstop", 4); editor.syntax = "js"; editor.focus = true; if (window.data) editor.value = window.data.user.projects['MyProject'].handlers['GET /'].code; }
public/js/client.js
$(document).ready(function() { // Fetch the user data. $.get('/api/init', function (data) { var projects, project, handlers, handler, h, p, edit, env; window.data = data; projects = data.user.projects; // TODO: iterate over the projects and fill the combo box. for (p in projects) { if (projects.hasOwnProperty(p) && p !== 'length') { project = projects[p]; log('project=' + project.name); $('#projects').append('<option value="value">' + project.name + '</option>'); } } handlers = projects['MyProject'].handlers; for (h in handlers) { if (handlers.hasOwnProperty(h) && h !== 'length') { handler = handlers[h]; log('method=' + handler.method + ',uri=' + handler.uri); // Get the DOM node with the Bespin instance inside edit = document.getElementById("editor1"); // Get the environment variable. env = edit.bespin; // Get the editor. if (env && env.editor) env.editor.value = data.user.projects['MyProject'].handlers['GET /'].code; } }; }); // Register the loading indicator on ajax events. $.loading({onAjax:true, text: 'Working...', effect: 'fade', delay: 100}); function nodifyMsg(msg, type) { var backgroundColor = ""; if (type === "error") { backgroundColor = "red"; // This will not work //$("#message_from_top").css("color","black"); } else { backgroundColor = "#4C4A41"; // This will not work // $("#message_from_top").css("color","#E2BE38"); } var options = {id: 'message_from_top', position: 'top', size: 20, backgroundColor: backgroundColor, delay: 3500, speed: 500, fontSize: '16px' }; $.showMessage(msg, options) } function consoleAppend (msg, type) { if (type === 'error') { msg = 'Error:\n------\n' + msg; } else { msg = 'Output:\n-------\n' + msg; } var c = $("#console"); var contents = c.val(); c.val(contents + '\n' + msg); c.css("display", "block"); // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) env.editor.dimensionsChanged(); } $('#save-btn').click(function() { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; $.ajax({ url: '/api/init', type: 'PUT', data: { method: 'GET', project: 'MyProject', code: encodeURIComponent(editor.value), uri: '/' }, success: function () { nodifyMsg("The contents were saved"); editor.focus = true; }, dataType: "text", error: function(request, status, error) { nodifyMsg("Error while saving file: " + error, "error"); } }); }); $('#revert-btn').click(function() { $.get('/api/init', function (data) { window.data = data; // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; editor.value = data.user.projects['MyProject'].handlers['GET /'].code; nodifyMsg("The contents were reverted"); editor.focus = true; }); }); $('#lnk-start').click(function() { $.ajax({ url: '/api/deploy', type: 'POST', data: {'project': 'MyProject'}, success: function (data) { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; consoleAppend(data); editor.focus = true; }, error: function(request, status, error) { consoleAppend(error, "error"); }, dataType: 'text' }); }); $('#lnk-stop').click(function() { $.ajax({ url: '/api/terminate', type: 'POST', data: {'project': 'MyProject'}, success: function (data) { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. if (env && env.editor) var editor = env.editor; nodifyMsg("The program was terminated"); editor.focus = true; }, error: function(request, status, error) { consoleAppend(error, "error"); }, dataType: 'text' }); }); $('#lnk-new').click(function() { $("#dialog-project-new").dialog('open'); }); $('#btn-project-new-cancel').click(function() { $("#dialog-project-new").dialog('close'); }); $('#btn-project-new-submit').click(function() { var newProjectName = $("btn-project-new-name").val(); $.ajax({ url: '/api/init', type: 'PUT', data: { project: encodeURIComponent(newProjectName) }, success: function () { $("#dialog-project-new").dialog('close'); nodifyMsg("The new project was saved"); }, dataType: "text", error: function(request, status, error) { $("#dialog-project-new").dialog('close'); nodifyMsg("Error while saving file: " + error, "error"); } }); }); $("#dialog-project-new").dialog({ autoOpen: false }); $("btn-project-new-submit").button(); }); window.onBespinLoad = function() { // Get the DOM node with the Bespin instance inside var edit = document.getElementById("editor1"); // Get the environment variable. var env = edit.bespin; // Get the editor. var editor = env.editor; env.settings.set("tabstop", 4); editor.syntax = "js"; editor.focus = true; if (window.data) editor.value = window.data.user.projects['MyProject'].handlers['GET /'].code; }
Select the last edited project.
public/js/client.js
Select the last edited project.
<ide><path>ublic/js/client.js <ide> var projects, project, handlers, handler, h, p, edit, env; <ide> window.data = data; <ide> projects = data.user.projects; <del> // TODO: iterate over the projects and fill the combo box. <ide> for (p in projects) { <ide> if (projects.hasOwnProperty(p) && p !== 'length') { <ide> project = projects[p]; <ide> log('project=' + project.name); <del> $('#projects').append('<option value="value">' + project.name + '</option>'); <add> if (data.user.lastProject && project.name === data.user.lastProject.name) <add> $('#projects').append('<option value="value" selected>' + project.name + '</option>'); <add> else <add> $('#projects').append('<option value="value">' + project.name + '</option>'); <ide> } <ide> } <ide> handlers = projects['MyProject'].handlers;
Java
apache-2.0
08a3debe989621d64607ca4678e58e3d34375981
0
tomason/drooms,triceo/drooms
package org.drooms.impl; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.drooms.api.Collectible; import org.drooms.api.GameReport; import org.drooms.api.Move; import org.drooms.api.Node; import org.drooms.api.Player; import org.drooms.impl.collectibles.CheapCollectible; import org.drooms.impl.collectibles.ExtremeCollectible; import org.drooms.impl.collectibles.GoodCollectible; public class DefaultGame extends GameController { private static String getTimestamp() { final Date date = new java.util.Date(); return new Timestamp(date.getTime()).toString(); } public static void main(final String[] args) { GameReport report = null; final Properties gameConfig = new Properties(); final Properties playerConfig = new Properties(); File reportFolder = null; // play the game try (Reader gameConfigFile = new FileReader(args[0]); Reader playerConfigFile = new FileReader(args[1])) { // prepare configs gameConfig.load(gameConfigFile); playerConfig.load(playerConfigFile); // play and report final DefaultGame g = new DefaultGame(new File( gameConfig.getProperty("reports.dir")), DefaultGame.getTimestamp()); reportFolder = g.getReportFolder(); if (!reportFolder.exists()) { reportFolder.mkdirs(); } report = g.play(gameConfig, playerConfig); } catch (final IOException e) { throw new IllegalStateException("Failed reading config files.", e); } // report try (Writer w = new FileWriter(new File(reportFolder, gameConfig.getProperty("report.file", "report.xml")))) { report.write(w); } catch (final IOException e) { throw new IllegalStateException("Failed writing report file.", e); } } public DefaultGame(final File reportFolder, final String timestamp) { super(reportFolder, timestamp); } @Override protected Map<Collectible, Player> performCollectibleCollection( final Collection<Player> players) { final Map<Collectible, Player> collections = new HashMap<Collectible, Player>(); for (final Player p : players) { final Node headPosition = this.getPlayerPosition(p).getFirst(); final Collectible c = this.getCollectible(headPosition); if (c != null) { // successfully collected collections.put(c, p); } } return Collections.unmodifiableMap(collections); } @Override protected Map<Collectible, Node> performCollectibleDistribution( final Properties gameConfig, final DefaultPlayground playground, final Collection<Player> players, final int currentTurnNumber) { final Map<Collectible, Node> collectibles = new HashMap<Collectible, Node>(); for (final CollectibleType ct : CollectibleType.values()) { final BigDecimal probability = ct .getProbabilityOfAppearance(gameConfig); final BigDecimal chosen = BigDecimal.valueOf(GameController.RANDOM .nextDouble()); if (probability.compareTo(chosen) > 0) { final int expiration = currentTurnNumber + ct.getExpiration(gameConfig); final int points = ct.getPoints(gameConfig); Collectible c = null; switch (ct) { case CHEAP: c = new CheapCollectible(points, expiration); break; case GOOD: c = new GoodCollectible(points, expiration); break; case EXTREME: c = new ExtremeCollectible(points, expiration); break; default: throw new IllegalStateException( "Unknown collectible type!"); } collectibles.put(c, this.pickRandomUnusedNode(playground, players)); } } return Collections.unmodifiableMap(collectibles); } @Override protected Set<Player> performCollisionDetection( final DefaultPlayground playground, final Collection<Player> currentPlayers) { final Set<Player> collisions = new HashSet<Player>(); for (final Player p1 : currentPlayers) { final Deque<Node> position = this.getPlayerPosition(p1); final Node firstPosition = position.getFirst(); if (!playground.isAvailable(firstPosition.getX(), firstPosition.getY())) { collisions.add(p1); continue; } else { // make sure the worm didn't crash into itself final Set<Node> nodes = new HashSet<Node>(position); if (nodes.size() < position.size()) { // a worm occupies one node twice = a crash into itself collisions.add(p1); } } for (final Player p2 : currentPlayers) { if (p1 == p2) { // the same worm continue; } final Node secondPosition = this.getPlayerPosition(p2) .getFirst(); if (firstPosition.equals(secondPosition)) { // head-on-head collision collisions.add(p1); collisions.add(p2); } else if (position.contains(secondPosition)) { // head-on-body collision collisions.add(p2); } } } return Collections.unmodifiableSet(collisions); } @Override protected Set<Player> performInactivityDetection( final Collection<Player> currentPlayers, final int currentTurnNumber, final int allowedInactiveTurns) { final Set<Player> inactiveWorms = new HashSet<Player>(); if (currentTurnNumber > allowedInactiveTurns) { for (final Player p : currentPlayers) { final Move[] moves = this.getDecisionRecord(p).toArray( new Move[] {}); boolean active = false; for (int i = moves.length - allowedInactiveTurns - 1; i < moves.length; i++) { if (moves[i] != Move.STAY) { // the worm has been active active = true; break; } } if (!active) { inactiveWorms.add(p); } } } return Collections.unmodifiableSet(inactiveWorms); } @Override protected Deque<Node> performPlayerMove(final Player player, final Move decision) { // move the head of the worm final Deque<Node> currentPos = this.getPlayerPosition(player); final Node currentHeadPos = currentPos.getFirst(); Node newHeadPos; switch (decision) { case UP: newHeadPos = Node.getNode(currentHeadPos.getX(), currentHeadPos.getY() + 1); break; case DOWN: newHeadPos = Node.getNode(currentHeadPos.getX(), currentHeadPos.getY() - 1); break; case LEFT: newHeadPos = Node.getNode(currentHeadPos.getX() - 1, currentHeadPos.getY()); break; case RIGHT: newHeadPos = Node.getNode(currentHeadPos.getX() + 1, currentHeadPos.getY()); break; case STAY: newHeadPos = currentHeadPos; break; default: throw new IllegalStateException("Unknown move!"); } // move the head of the snake final Deque<Node> newPosition = new LinkedList<Node>(currentPos); if (decision != Move.STAY) { newPosition.push(newHeadPos); } // make sure the snake is as long as it should be while (newPosition.size() > this.getPlayerLength(player)) { newPosition.removeLast(); } // notify return newPosition; } private Node pickRandomUnusedNode(final DefaultPlayground p, final Collection<Player> players) { final List<Node> nodes = new LinkedList<Node>(); // locate available nodes for (int x = 0; x < p.getWidth(); x++) { for (int y = 0; y < p.getHeight(); y++) { if (p.isAvailable(x, y)) { nodes.add(Node.getNode(x, y)); } } } // exclude nodes where worms are for (final Player player : players) { nodes.removeAll(this.getPlayerPosition(player)); } // exclude nodes where collectibles are final List<Node> nodesCopy = new LinkedList<Node>(nodes); for (final Node n : nodesCopy) { if (this.getCollectible(n) != null) { nodes.remove(n); } } if (nodes.size() == 0) { return null; } else { return nodes.get(GameController.RANDOM.nextInt(nodes.size())); } } }
drooms-game-impl/src/main/java/org/drooms/impl/DefaultGame.java
package org.drooms.impl; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.drooms.api.Collectible; import org.drooms.api.GameReport; import org.drooms.api.Move; import org.drooms.api.Node; import org.drooms.api.Player; import org.drooms.impl.collectibles.CheapCollectible; import org.drooms.impl.collectibles.ExtremeCollectible; import org.drooms.impl.collectibles.GoodCollectible; public class DefaultGame extends GameController { private static String getTimestamp() { final Date date = new java.util.Date(); return new Timestamp(date.getTime()).toString(); } public static void main(final String[] args) { GameReport report = null; final Properties gameConfig = new Properties(); final Properties playerConfig = new Properties(); File reportFolder = null; // play the game try (Reader gameConfigFile = new FileReader(args[0]); Reader playerConfigFile = new FileReader(args[1]); FileOutputStream fos = new FileOutputStream(new File(args[2]))) { // prepare configs gameConfig.load(gameConfigFile); playerConfig.load(playerConfigFile); // play and report final DefaultGame g = new DefaultGame(new File( gameConfig.getProperty("reports.dir")), DefaultGame.getTimestamp()); reportFolder = g.getReportFolder(); if (!reportFolder.exists()) { reportFolder.mkdirs(); } report = g.play(gameConfig, playerConfig); } catch (final IOException e) { throw new IllegalStateException("Failed reading config files.", e); } // report try (Writer w = new FileWriter(new File(reportFolder, gameConfig.getProperty("report.file", "report.xml")))) { report.write(w); } catch (final IOException e) { throw new IllegalStateException("Failed writing report file.", e); } } public DefaultGame(final File reportFolder, final String timestamp) { super(reportFolder, timestamp); } @Override protected Map<Collectible, Player> performCollectibleCollection( final Collection<Player> players) { final Map<Collectible, Player> collections = new HashMap<Collectible, Player>(); for (final Player p : players) { final Node headPosition = this.getPlayerPosition(p).getFirst(); final Collectible c = this.getCollectible(headPosition); if (c != null) { // successfully collected collections.put(c, p); } } return Collections.unmodifiableMap(collections); } @Override protected Map<Collectible, Node> performCollectibleDistribution( final Properties gameConfig, final DefaultPlayground playground, final Collection<Player> players, final int currentTurnNumber) { final Map<Collectible, Node> collectibles = new HashMap<Collectible, Node>(); for (final CollectibleType ct : CollectibleType.values()) { final BigDecimal probability = ct .getProbabilityOfAppearance(gameConfig); final BigDecimal chosen = BigDecimal.valueOf(GameController.RANDOM .nextDouble()); if (probability.compareTo(chosen) > 0) { final int expiration = currentTurnNumber + ct.getExpiration(gameConfig); final int points = ct.getPoints(gameConfig); Collectible c = null; switch (ct) { case CHEAP: c = new CheapCollectible(points, expiration); break; case GOOD: c = new GoodCollectible(points, expiration); break; case EXTREME: c = new ExtremeCollectible(points, expiration); break; default: throw new IllegalStateException( "Unknown collectible type!"); } collectibles.put(c, this.pickRandomUnusedNode(playground, players)); } } return Collections.unmodifiableMap(collectibles); } @Override protected Set<Player> performCollisionDetection( final DefaultPlayground playground, final Collection<Player> currentPlayers) { final Set<Player> collisions = new HashSet<Player>(); for (final Player p1 : currentPlayers) { final Deque<Node> position = this.getPlayerPosition(p1); final Node firstPosition = position.getFirst(); if (!playground.isAvailable(firstPosition.getX(), firstPosition.getY())) { collisions.add(p1); continue; } else { // make sure the worm didn't crash into itself final Set<Node> nodes = new HashSet<Node>(position); if (nodes.size() < position.size()) { // a worm occupies one node twice = a crash into itself collisions.add(p1); } } for (final Player p2 : currentPlayers) { if (p1 == p2) { // the same worm continue; } final Node secondPosition = this.getPlayerPosition(p2) .getFirst(); if (firstPosition.equals(secondPosition)) { // head-on-head collision collisions.add(p1); collisions.add(p2); } else if (position.contains(secondPosition)) { // head-on-body collision collisions.add(p2); } } } return Collections.unmodifiableSet(collisions); } @Override protected Set<Player> performInactivityDetection( final Collection<Player> currentPlayers, final int currentTurnNumber, final int allowedInactiveTurns) { final Set<Player> inactiveWorms = new HashSet<Player>(); if (currentTurnNumber > allowedInactiveTurns) { for (final Player p : currentPlayers) { final Move[] moves = this.getDecisionRecord(p).toArray( new Move[] {}); boolean active = false; for (int i = moves.length - allowedInactiveTurns - 1; i < moves.length; i++) { if (moves[i] != Move.STAY) { // the worm has been active active = true; break; } } if (!active) { inactiveWorms.add(p); } } } return Collections.unmodifiableSet(inactiveWorms); } @Override protected Deque<Node> performPlayerMove(final Player player, final Move decision) { // move the head of the worm final Deque<Node> currentPos = this.getPlayerPosition(player); final Node currentHeadPos = currentPos.getFirst(); Node newHeadPos; switch (decision) { case UP: newHeadPos = Node.getNode(currentHeadPos.getX(), currentHeadPos.getY() + 1); break; case DOWN: newHeadPos = Node.getNode(currentHeadPos.getX(), currentHeadPos.getY() - 1); break; case LEFT: newHeadPos = Node.getNode(currentHeadPos.getX() - 1, currentHeadPos.getY()); break; case RIGHT: newHeadPos = Node.getNode(currentHeadPos.getX() + 1, currentHeadPos.getY()); break; case STAY: newHeadPos = currentHeadPos; break; default: throw new IllegalStateException("Unknown move!"); } // move the head of the snake final Deque<Node> newPosition = new LinkedList<Node>(currentPos); if (decision != Move.STAY) { newPosition.push(newHeadPos); } // make sure the snake is as long as it should be while (newPosition.size() > this.getPlayerLength(player)) { newPosition.removeLast(); } // notify return newPosition; } private Node pickRandomUnusedNode(final DefaultPlayground p, final Collection<Player> players) { final List<Node> nodes = new LinkedList<Node>(); // locate available nodes for (int x = 0; x < p.getWidth(); x++) { for (int y = 0; y < p.getHeight(); y++) { if (p.isAvailable(x, y)) { nodes.add(Node.getNode(x, y)); } } } // exclude nodes where worms are for (final Player player : players) { nodes.removeAll(this.getPlayerPosition(player)); } // exclude nodes where collectibles are final List<Node> nodesCopy = new LinkedList<Node>(nodes); for (final Node n : nodesCopy) { if (this.getCollectible(n) != null) { nodes.remove(n); } } if (nodes.size() == 0) { return null; } else { return nodes.get(GameController.RANDOM.nextInt(nodes.size())); } } }
Remove unnecessary argument.
drooms-game-impl/src/main/java/org/drooms/impl/DefaultGame.java
Remove unnecessary argument.
<ide><path>rooms-game-impl/src/main/java/org/drooms/impl/DefaultGame.java <ide> package org.drooms.impl; <ide> <ide> import java.io.File; <del>import java.io.FileOutputStream; <ide> import java.io.FileReader; <ide> import java.io.FileWriter; <ide> import java.io.IOException; <ide> File reportFolder = null; <ide> // play the game <ide> try (Reader gameConfigFile = new FileReader(args[0]); <del> Reader playerConfigFile = new FileReader(args[1]); <del> FileOutputStream fos = new FileOutputStream(new File(args[2]))) { <add> Reader playerConfigFile = new FileReader(args[1])) { <ide> // prepare configs <ide> gameConfig.load(gameConfigFile); <ide> playerConfig.load(playerConfigFile);
Java
apache-2.0
9ef4e36fccd10421c74643f9ec119001d1589bc4
0
gradle/gradle,gradle/gradle,gradle/gradle,blindpirate/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,robinverduijn/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,gradle/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.caching.internal.controller; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.io.IOUtils; import org.gradle.api.Action; import org.gradle.api.GradleException; import org.gradle.api.UncheckedIOException; import org.gradle.caching.BuildCacheKey; import org.gradle.caching.BuildCacheService; import org.gradle.caching.internal.controller.operations.PackOperationDetails; import org.gradle.caching.internal.controller.operations.PackOperationResult; import org.gradle.caching.internal.controller.operations.UnpackOperationDetails; import org.gradle.caching.internal.controller.operations.UnpackOperationResult; import org.gradle.caching.internal.controller.service.BaseBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.BuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.BuildCacheServiceRole; import org.gradle.caching.internal.controller.service.BuildCacheServicesConfiguration; import org.gradle.caching.internal.controller.service.DefaultLocalBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.LoadTarget; import org.gradle.caching.internal.controller.service.LocalBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.NullBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.NullLocalBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.OpFiringBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.StoreTarget; import org.gradle.caching.local.internal.BuildCacheTempFileStore; import org.gradle.caching.local.internal.DefaultBuildCacheTempFileStore; import org.gradle.caching.local.internal.LocalBuildCacheService; import org.gradle.internal.UncheckedException; import org.gradle.internal.concurrent.CompositeStoppable; import org.gradle.internal.operations.BuildOperationContext; import org.gradle.internal.operations.BuildOperationExecutor; import org.gradle.internal.operations.RunnableBuildOperation; import org.gradle.internal.progress.BuildOperationDescriptor; import javax.annotation.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class DefaultBuildCacheController implements BuildCacheController { @VisibleForTesting final BuildCacheServiceHandle legacyLocal; @VisibleForTesting final BuildCacheServiceHandle remote; @VisibleForTesting final LocalBuildCacheServiceHandle local; private final BuildCacheTempFileStore tmp; private final BuildOperationExecutor buildOperationExecutor; private boolean closed; public DefaultBuildCacheController( BuildCacheServicesConfiguration config, BuildOperationExecutor buildOperationExecutor, File gradleUserHomeDir, boolean logStackTraces ) { this.buildOperationExecutor = buildOperationExecutor; if (config.local instanceof LocalBuildCacheService) { LocalBuildCacheService castLocal = (LocalBuildCacheService) config.local; this.local = toHandle(castLocal, config.localPush); this.tmp = castLocal; this.legacyLocal = NullBuildCacheServiceHandle.INSTANCE; } else { this.local = NullLocalBuildCacheServiceHandle.INSTANCE; this.legacyLocal = toHandle(config.local, config.localPush, BuildCacheServiceRole.LOCAL, buildOperationExecutor, logStackTraces); this.tmp = new DefaultBuildCacheTempFileStore(new File(gradleUserHomeDir, "build-cache-tmp")); } this.remote = toHandle(config.remote, config.remotePush, BuildCacheServiceRole.REMOTE, buildOperationExecutor, logStackTraces); } @Nullable @Override public <T> T load(final BuildCacheLoadCommand<T> command) { final Unpack<T> unpack = new Unpack<T>(command); if (local.canLoad()) { try { local.load(command.getKey(), unpack); } catch (Exception e) { throw new GradleException("Build cache entry " + command.getKey() + " from local build cache is invalid", e); } if (unpack.result != null) { return unpack.result.getMetadata(); } } if (legacyLocal.canLoad() || remote.canLoad()) { tmp.allocateTempFile(command.getKey(), new Action<File>() { @Override public void execute(File file) { LoadTarget loadTarget = new LoadTarget(file); BuildCacheServiceRole loadedRole = null; if (legacyLocal.canLoad()) { loadedRole = BuildCacheServiceRole.LOCAL; legacyLocal.load(command.getKey(), loadTarget); } if (remote.canLoad() && !loadTarget.isLoaded()) { loadedRole = BuildCacheServiceRole.REMOTE; remote.load(command.getKey(), loadTarget); } if (loadTarget.isLoaded()) { try { unpack.execute(file); } catch (Exception e) { @SuppressWarnings("ConstantConditions") String roleDisplayName = loadedRole.getDisplayName(); throw new GradleException("Build cache entry " + command.getKey() + " from " + roleDisplayName + " build cache is invalid", e); } if (local.canStore()) { local.store(command.getKey(), file); } } } }); } BuildCacheLoadCommand.Result<T> result = unpack.result; if (result == null) { return null; } else { return result.getMetadata(); } } private class Unpack<T> implements Action<File> { private final BuildCacheLoadCommand<T> command; private BuildCacheLoadCommand.Result<T> result; private Unpack(BuildCacheLoadCommand<T> command) { this.command = command; } @Override public void execute(final File file) { buildOperationExecutor.run(new RunnableBuildOperation() { @Override public void run(BuildOperationContext context) { InputStream input; try { input = new FileInputStream(file); } catch (FileNotFoundException e) { throw new UncheckedIOException(e); } try { result = command.load(input); } catch (IOException e) { throw new UncheckedIOException(e); } finally { IOUtils.closeQuietly(input); } context.setResult(new UnpackOperationResult( result.getArtifactEntryCount() )); } @Override public BuildOperationDescriptor.Builder description() { return BuildOperationDescriptor.displayName("Unpack build cache entry " + command.getKey()) .details(new UnpackOperationDetails(command.getKey(), file.length())) .progressDisplayName("Unpacking build cache entry"); } }); } } @Override public void store(final BuildCacheStoreCommand command) { boolean anyStore = local.canStore() || legacyLocal.canStore() || remote.canStore(); if (!anyStore) { return; } final BuildCacheKey key = command.getKey(); final Pack pack = new Pack(command); tmp.allocateTempFile(command.getKey(), new Action<File>() { @Override public void execute(File file) { pack.execute(file); if (legacyLocal.canStore()) { legacyLocal.store(key, new StoreTarget(file)); } if (remote.canStore()) { remote.store(key, new StoreTarget(file)); } if (local.canStore()) { local.store(key, file); } } }); } private class Pack implements Action<File> { private final BuildCacheStoreCommand command; private Pack(BuildCacheStoreCommand command) { this.command = command; } @Override public void execute(final File file) { buildOperationExecutor.run(new RunnableBuildOperation() { @Override public void run(BuildOperationContext context) { try { BuildCacheStoreCommand.Result result = command.store(new FileOutputStream(file)); context.setResult(new PackOperationResult( result.getArtifactEntryCount(), file.length() )); } catch (IOException e) { throw UncheckedException.throwAsUncheckedException(e); } } @Override public BuildOperationDescriptor.Builder description() { return BuildOperationDescriptor.displayName("Pack build cache entry " + command.getKey()) .details(new PackOperationDetails(command.getKey())) .progressDisplayName("Packing build cache entry"); } }); } } @Override public void close() { if (!closed) { closed = true; CompositeStoppable.stoppable(legacyLocal, local, remote).stop(); } } private static BuildCacheServiceHandle toHandle(BuildCacheService service, boolean push, BuildCacheServiceRole role, BuildOperationExecutor buildOperationExecutor, boolean logStackTraces) { return service == null ? NullBuildCacheServiceHandle.INSTANCE : toNonNullHandle(service, push, role, buildOperationExecutor, logStackTraces); } private static BuildCacheServiceHandle toNonNullHandle(BuildCacheService service, boolean push, BuildCacheServiceRole role, BuildOperationExecutor buildOperationExecutor, boolean logStackTraces) { if (role == BuildCacheServiceRole.LOCAL) { return new BaseBuildCacheServiceHandle(service, push, role, logStackTraces); } else { return new OpFiringBuildCacheServiceHandle(service, push, role, buildOperationExecutor, logStackTraces); } } private static LocalBuildCacheServiceHandle toHandle(LocalBuildCacheService local, boolean localPush) { if (local == null) { return NullLocalBuildCacheServiceHandle.INSTANCE; } else { return new DefaultLocalBuildCacheServiceHandle(local, localPush); } } }
subprojects/core/src/main/java/org/gradle/caching/internal/controller/DefaultBuildCacheController.java
/* * Copyright 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.caching.internal.controller; import com.google.common.annotations.VisibleForTesting; import org.apache.commons.io.IOUtils; import org.gradle.api.Action; import org.gradle.api.GradleException; import org.gradle.caching.BuildCacheKey; import org.gradle.caching.BuildCacheService; import org.gradle.caching.internal.controller.operations.PackOperationDetails; import org.gradle.caching.internal.controller.operations.PackOperationResult; import org.gradle.caching.internal.controller.operations.UnpackOperationDetails; import org.gradle.caching.internal.controller.operations.UnpackOperationResult; import org.gradle.caching.internal.controller.service.BaseBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.BuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.BuildCacheServiceRole; import org.gradle.caching.internal.controller.service.BuildCacheServicesConfiguration; import org.gradle.caching.internal.controller.service.DefaultLocalBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.LoadTarget; import org.gradle.caching.internal.controller.service.LocalBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.NullBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.NullLocalBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.OpFiringBuildCacheServiceHandle; import org.gradle.caching.internal.controller.service.StoreTarget; import org.gradle.caching.local.internal.BuildCacheTempFileStore; import org.gradle.caching.local.internal.DefaultBuildCacheTempFileStore; import org.gradle.caching.local.internal.LocalBuildCacheService; import org.gradle.internal.UncheckedException; import org.gradle.internal.concurrent.CompositeStoppable; import org.gradle.internal.operations.BuildOperationContext; import org.gradle.internal.operations.BuildOperationExecutor; import org.gradle.internal.operations.RunnableBuildOperation; import org.gradle.internal.progress.BuildOperationDescriptor; import javax.annotation.Nullable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; public class DefaultBuildCacheController implements BuildCacheController { @VisibleForTesting final BuildCacheServiceHandle legacyLocal; @VisibleForTesting final BuildCacheServiceHandle remote; @VisibleForTesting final LocalBuildCacheServiceHandle local; private final BuildCacheTempFileStore tmp; private final BuildOperationExecutor buildOperationExecutor; private boolean closed; public DefaultBuildCacheController( BuildCacheServicesConfiguration config, BuildOperationExecutor buildOperationExecutor, File gradleUserHomeDir, boolean logStackTraces ) { this.buildOperationExecutor = buildOperationExecutor; if (config.local instanceof LocalBuildCacheService) { LocalBuildCacheService castLocal = (LocalBuildCacheService) config.local; this.local = toHandle(castLocal, config.localPush); this.tmp = castLocal; this.legacyLocal = NullBuildCacheServiceHandle.INSTANCE; } else { this.local = NullLocalBuildCacheServiceHandle.INSTANCE; this.legacyLocal = toHandle(config.local, config.localPush, BuildCacheServiceRole.LOCAL, buildOperationExecutor, logStackTraces); this.tmp = new DefaultBuildCacheTempFileStore(new File(gradleUserHomeDir, "build-cache-tmp")); } this.remote = toHandle(config.remote, config.remotePush, BuildCacheServiceRole.REMOTE, buildOperationExecutor, logStackTraces); } @Nullable @Override public <T> T load(final BuildCacheLoadCommand<T> command) { final Unpack<T> unpack = new Unpack<T>(command); if (local.canLoad()) { try { local.load(command.getKey(), unpack); } catch (Exception e) { throw new GradleException("Build cache entry " + command.getKey() + " from local build cache is invalid", e); } if (unpack.result != null) { return unpack.result.getMetadata(); } } if (legacyLocal.canLoad() || remote.canLoad()) { tmp.allocateTempFile(command.getKey(), new Action<File>() { @Override public void execute(File file) { LoadTarget loadTarget = new LoadTarget(file); BuildCacheServiceRole loadedRole = null; if (legacyLocal.canLoad()) { loadedRole = BuildCacheServiceRole.LOCAL; legacyLocal.load(command.getKey(), loadTarget); } if (remote.canLoad() && !loadTarget.isLoaded()) { loadedRole = BuildCacheServiceRole.REMOTE; remote.load(command.getKey(), loadTarget); } if (loadTarget.isLoaded()) { try { unpack.execute(file); } catch (Exception e) { @SuppressWarnings("ConstantConditions") String roleDisplayName = loadedRole.getDisplayName(); throw new GradleException("Build cache entry " + command.getKey() + " from " + roleDisplayName + " build cache is invalid", e); } if (local.canStore()) { local.store(command.getKey(), file); } } } }); } BuildCacheLoadCommand.Result<T> result = unpack.result; if (result == null) { return null; } else { return result.getMetadata(); } } private class Unpack<T> implements Action<File> { private final BuildCacheLoadCommand<T> command; private BuildCacheLoadCommand.Result<T> result; private Unpack(BuildCacheLoadCommand<T> command) { this.command = command; } @Override public void execute(final File file) { buildOperationExecutor.run(new RunnableBuildOperation() { @Override public void run(BuildOperationContext context) { InputStream input; try { input = new FileInputStream(file); } catch (FileNotFoundException e) { throw UncheckedException.throwAsUncheckedException(e); } try { result = command.load(input); } finally { IOUtils.closeQuietly(input); } context.setResult(new UnpackOperationResult( result.getArtifactEntryCount() )); } @Override public BuildOperationDescriptor.Builder description() { return BuildOperationDescriptor.displayName("Unpack build cache entry " + command.getKey()) .details(new UnpackOperationDetails(command.getKey(), file.length())) .progressDisplayName("Unpacking build cache entry"); } }); } } @Override public void store(final BuildCacheStoreCommand command) { boolean anyStore = local.canStore() || legacyLocal.canStore() || remote.canStore(); if (!anyStore) { return; } final BuildCacheKey key = command.getKey(); final Pack pack = new Pack(command); tmp.allocateTempFile(command.getKey(), new Action<File>() { @Override public void execute(File file) { pack.execute(file); if (legacyLocal.canStore()) { legacyLocal.store(key, new StoreTarget(file)); } if (remote.canStore()) { remote.store(key, new StoreTarget(file)); } if (local.canStore()) { local.store(key, file); } } }); } private class Pack implements Action<File> { private final BuildCacheStoreCommand command; private Pack(BuildCacheStoreCommand command) { this.command = command; } @Override public void execute(final File file) { buildOperationExecutor.run(new RunnableBuildOperation() { @Override public void run(BuildOperationContext context) { try { BuildCacheStoreCommand.Result result = command.store(new FileOutputStream(file)); context.setResult(new PackOperationResult( result.getArtifactEntryCount(), file.length() )); } catch (IOException e) { throw UncheckedException.throwAsUncheckedException(e); } } @Override public BuildOperationDescriptor.Builder description() { return BuildOperationDescriptor.displayName("Pack build cache entry " + command.getKey()) .details(new PackOperationDetails(command.getKey())) .progressDisplayName("Packing build cache entry"); } }); } } @Override public void close() { if (!closed) { closed = true; CompositeStoppable.stoppable(legacyLocal, local, remote).stop(); } } private static BuildCacheServiceHandle toHandle(BuildCacheService service, boolean push, BuildCacheServiceRole role, BuildOperationExecutor buildOperationExecutor, boolean logStackTraces) { return service == null ? NullBuildCacheServiceHandle.INSTANCE : toNonNullHandle(service, push, role, buildOperationExecutor, logStackTraces); } private static BuildCacheServiceHandle toNonNullHandle(BuildCacheService service, boolean push, BuildCacheServiceRole role, BuildOperationExecutor buildOperationExecutor, boolean logStackTraces) { if (role == BuildCacheServiceRole.LOCAL) { return new BaseBuildCacheServiceHandle(service, push, role, logStackTraces); } else { return new OpFiringBuildCacheServiceHandle(service, push, role, buildOperationExecutor, logStackTraces); } } private static LocalBuildCacheServiceHandle toHandle(LocalBuildCacheService local, boolean localPush) { if (local == null) { return NullLocalBuildCacheServiceHandle.INSTANCE; } else { return new DefaultLocalBuildCacheServiceHandle(local, localPush); } } }
Fix exception
subprojects/core/src/main/java/org/gradle/caching/internal/controller/DefaultBuildCacheController.java
Fix exception
<ide><path>ubprojects/core/src/main/java/org/gradle/caching/internal/controller/DefaultBuildCacheController.java <ide> import org.apache.commons.io.IOUtils; <ide> import org.gradle.api.Action; <ide> import org.gradle.api.GradleException; <add>import org.gradle.api.UncheckedIOException; <ide> import org.gradle.caching.BuildCacheKey; <ide> import org.gradle.caching.BuildCacheService; <ide> import org.gradle.caching.internal.controller.operations.PackOperationDetails; <ide> try { <ide> input = new FileInputStream(file); <ide> } catch (FileNotFoundException e) { <del> throw UncheckedException.throwAsUncheckedException(e); <add> throw new UncheckedIOException(e); <ide> } <ide> <ide> try { <ide> result = command.load(input); <add> } catch (IOException e) { <add> throw new UncheckedIOException(e); <ide> } finally { <ide> IOUtils.closeQuietly(input); <ide> }
Java
apache-2.0
a25b709fc0d4319e64099a780ba526c22fd4d9af
0
ibrahimshbat/JGroups,deepnarsay/JGroups,Sanne/JGroups,pferraro/JGroups,dimbleby/JGroups,belaban/JGroups,danberindei/JGroups,kedzie/JGroups,ligzy/JGroups,ibrahimshbat/JGroups,dimbleby/JGroups,rpelisse/JGroups,pferraro/JGroups,TarantulaTechnology/JGroups,ligzy/JGroups,deepnarsay/JGroups,rhusar/JGroups,belaban/JGroups,slaskawi/JGroups,kedzie/JGroups,tristantarrant/JGroups,Sanne/JGroups,pruivo/JGroups,rhusar/JGroups,pruivo/JGroups,deepnarsay/JGroups,vjuranek/JGroups,slaskawi/JGroups,danberindei/JGroups,tristantarrant/JGroups,dimbleby/JGroups,ibrahimshbat/JGroups,vjuranek/JGroups,danberindei/JGroups,TarantulaTechnology/JGroups,rvansa/JGroups,pruivo/JGroups,Sanne/JGroups,pferraro/JGroups,ligzy/JGroups,belaban/JGroups,TarantulaTechnology/JGroups,ibrahimshbat/JGroups,rpelisse/JGroups,slaskawi/JGroups,rhusar/JGroups,vjuranek/JGroups,kedzie/JGroups,rvansa/JGroups,rpelisse/JGroups
package org.jgroups.tests.helpers; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.stack.Protocol; /** * @author Bela Ban * @since 3.1 */ public class SequencerFailoverTestHelper { public void sendMessages(final Protocol prot, final int start, final int end) { final Thread sender=new Thread() { public void run() { for(int i=start; i <= end; i++) { Message msg=new Message(null, i); System.out.println("[" + prot.getValue("local_addr") + "] --> sending message " + i); prot.down(new Event(Event.MSG,msg)); } } }; sender.setName("BytemanSenderThread"); sender.start(); try { sender.join(1000); } catch(InterruptedException e) { } } }
tests/byteman/org/jgroups/tests/helpers/SequencerFailoverTestHelper.java
package org.jgroups.tests.helpers; import org.jboss.byteman.rule.Rule; import org.jboss.byteman.rule.helper.Helper; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.stack.Protocol; /** * @author Bela Ban * @since 3.1 */ public class SequencerFailoverTestHelper extends Helper { protected SequencerFailoverTestHelper(Rule rule) { super(rule); } public void sendMessages(final Protocol prot, final int start, final int end) { final Thread sender=new Thread() { public void run() { for(int i=start; i <= end; i++) { Message msg=new Message(null, i); System.out.println("[" + prot.getValue("local_addr") + "] --> sending message " + i); prot.down(new Event(Event.MSG,msg)); } } }; sender.setName("BytemanSenderThread"); sender.start(); try { sender.join(1000); } catch(InterruptedException e) { } } }
No need to extends Helper
tests/byteman/org/jgroups/tests/helpers/SequencerFailoverTestHelper.java
No need to extends Helper
<ide><path>ests/byteman/org/jgroups/tests/helpers/SequencerFailoverTestHelper.java <ide> package org.jgroups.tests.helpers; <ide> <del>import org.jboss.byteman.rule.Rule; <del>import org.jboss.byteman.rule.helper.Helper; <ide> import org.jgroups.Event; <ide> import org.jgroups.Message; <ide> import org.jgroups.stack.Protocol; <ide> * @author Bela Ban <ide> * @since 3.1 <ide> */ <del>public class SequencerFailoverTestHelper extends Helper { <del> protected SequencerFailoverTestHelper(Rule rule) { <del> super(rule); <del> } <add>public class SequencerFailoverTestHelper { <ide> <ide> public void sendMessages(final Protocol prot, final int start, final int end) { <ide> final Thread sender=new Thread() {
Java
bsd-3-clause
9d96017ac3c0ae461500a953ba40dad3b175bd62
0
sumedhasingla/VTK,keithroe/vtkoptix,SimVascular/VTK,SimVascular/VTK,sumedhasingla/VTK,keithroe/vtkoptix,SimVascular/VTK,keithroe/vtkoptix,sumedhasingla/VTK,keithroe/vtkoptix,keithroe/vtkoptix,SimVascular/VTK,SimVascular/VTK,sumedhasingla/VTK,sumedhasingla/VTK,SimVascular/VTK,keithroe/vtkoptix,keithroe/vtkoptix,sumedhasingla/VTK,sumedhasingla/VTK,keithroe/vtkoptix,SimVascular/VTK,sumedhasingla/VTK,SimVascular/VTK
package vtk; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantLock; /** * Provide a Java thread safe implementation of vtkJavaMemoryManager. This does * not make VTK thread safe. This only insure that the change of reference count * will never happen in two concurrent thread in the Java world. * * @see vtkJavaMemoryManager * @author sebastien jourdain - [email protected] */ public class vtkJavaMemoryManagerImpl implements vtkJavaMemoryManager { private vtkJavaGarbageCollector garbageCollector; private ReentrantLock lock; private vtkReferenceInformation lastGcResult; private HashMap<Long, WeakReference<vtkObjectBase>> objectMap; private HashMap<Long, String> objectMapClassName; public vtkJavaMemoryManagerImpl() { this.lock = new ReentrantLock(); this.objectMap = new HashMap<Long, WeakReference<vtkObjectBase>>(); this.objectMapClassName = new HashMap<Long, String>(); this.garbageCollector = new vtkJavaGarbageCollector(); } // Thread safe public vtkObjectBase getJavaObject(Long vtkId) { // Check pre-condition if (vtkId == null || vtkId.longValue() == 0) { throw new RuntimeException("Invalid ID, can not be null or equal to 0."); } // Check inside the map if the object is already there WeakReference<vtkObjectBase> value = objectMap.get(vtkId); vtkObjectBase resultObject = (value == null) ? null : value.get(); // If not, we have to do something if (value == null || resultObject == null) { try { // Make sure no concurrency could happen inside that this.lock.lock(); // Now that we have the lock make sure someone else didn't // create the object in between, if so just return the created // instance value = objectMap.get(vtkId); resultObject = (value == null) ? null : value.get(); if (resultObject != null) { return resultObject; } // We need to do the work of the gc if (value != null && resultObject == null) { this.unRegisterJavaObject(vtkId); } // No-one did create it, so let's do it if (resultObject == null) { try { String className = vtkObjectBase.VTKGetClassNameFromReference(vtkId.longValue()); Class<?> c = Class.forName("vtk." + className); Constructor<?> cons = c.getConstructor(new Class<?>[] { long.class }); resultObject = (vtkObjectBase) cons.newInstance(new Object[] { vtkId }); } catch (Exception e) { e.printStackTrace(); } } } finally { this.lock.unlock(); } } return resultObject; } // Thread safe public void registerJavaObject(Long id, vtkObjectBase obj) { try { this.lock.lock(); this.objectMap.put(id, new WeakReference<vtkObjectBase>(obj)); this.objectMapClassName.put(id, obj.GetClassName()); } finally { this.lock.unlock(); } } // Thread safe public void unRegisterJavaObject(Long id) { try { this.lock.lock(); this.objectMapClassName.remove(id); WeakReference<vtkObjectBase> value = this.objectMap.remove(id); // Prevent double deletion... if (value != null) { vtkObjectBase.VTKDeleteReference(id.longValue()); } else { throw new RuntimeException("You try to delete a vtkObject that is not referenced in the Java object Map. You may have call Delete() twice."); } } finally { this.lock.unlock(); } } // Thread safe public vtkReferenceInformation gc(boolean debug) { System.gc(); try { this.lock.lock(); final vtkReferenceInformation infos = new vtkReferenceInformation(debug); for (Long id : new TreeSet<Long>(this.objectMap.keySet())) { vtkObjectBase obj = this.objectMap.get(id).get(); if (obj == null) { infos.addFreeObject(this.objectMapClassName.get(id)); this.unRegisterJavaObject(id); } else { infos.addKeptObject(this.objectMapClassName.get(id)); } } this.lastGcResult = infos; return infos; } finally { this.lock.unlock(); } } public vtkJavaGarbageCollector getAutoGarbageCollector() { return this.garbageCollector; } // Thread safe public int deleteAll() { int size = this.objectMap.size(); try { this.lock.lock(); for (Long id : new TreeSet<Long>(this.objectMap.keySet())) { this.unRegisterJavaObject(id); } } finally { this.lock.unlock(); } return size; } public int getSize() { return objectMap.size(); } public vtkReferenceInformation getLastReferenceInformation() { return this.lastGcResult; } }
Wrapping/Java/vtk/vtkJavaMemoryManagerImpl.java
package vtk; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.util.HashMap; import java.util.TreeSet; import java.util.concurrent.locks.ReentrantLock; /** * Provide a Java thread safe implementation of vtkJavaMemoryManager. This does * not make VTK thread safe. This only insure that the change of reference count * will never happen in two concurrent thread in the Java world. * * @see vtkJavaMemoryManager * @author sebastien jourdain - [email protected] */ public class vtkJavaMemoryManagerImpl implements vtkJavaMemoryManager { private vtkJavaGarbageCollector garbageCollector; private ReentrantLock lock; private vtkReferenceInformation lastGcResult; private HashMap<Long, WeakReference<vtkObjectBase>> objectMap; private HashMap<Long, String> objectMapClassName; public vtkJavaMemoryManagerImpl() { this.lock = new ReentrantLock(); this.objectMap = new HashMap<Long, WeakReference<vtkObjectBase>>(); this.objectMapClassName = new HashMap<Long, String>(); this.garbageCollector = new vtkJavaGarbageCollector(); } // Thread safe public vtkObjectBase getJavaObject(Long vtkId) { // Check pre-condition if (vtkId == null || vtkId.longValue() == 0) { throw new RuntimeException("Invalid ID, can not be null or equal to 0."); } // Check inside the map if the object is already there WeakReference<vtkObjectBase> value = objectMap.get(vtkId); vtkObjectBase resultObject = (value == null) ? null : value.get(); // If not, we have to do something if (value == null || resultObject == null) { try { // Make sure no concurrency could happen inside that this.lock.lock(); // Now that we have the lock make sure someone else didn't // create the object in between, if so just return the created // instance value = objectMap.get(vtkId); resultObject = (value == null) ? null : value.get(); if (resultObject != null) { return resultObject; } // We need to do the work of the gc if (value != null && resultObject == null) { this.unRegisterJavaObject(vtkId); } // No-one did create it, so let's do it if (resultObject == null) { try { String className = vtkObjectBase.VTKGetClassNameFromReference(vtkId.longValue()); Class c = Class.forName("vtk." + className); Constructor cons = c.getConstructor(new Class[] { long.class }); resultObject = (vtkObjectBase) cons.newInstance(new Object[] { vtkId }); } catch (Exception e) { e.printStackTrace(); } } } finally { this.lock.unlock(); } } return resultObject; } // Thread safe public void registerJavaObject(Long id, vtkObjectBase obj) { try { this.lock.lock(); this.objectMap.put(id, new WeakReference<vtkObjectBase>(obj)); this.objectMapClassName.put(id, obj.GetClassName()); } finally { this.lock.unlock(); } } // Thread safe public void unRegisterJavaObject(Long id) { try { this.lock.lock(); this.objectMapClassName.remove(id); WeakReference<vtkObjectBase> value = this.objectMap.remove(id); // Prevent double deletion... if (value != null) { vtkObjectBase.VTKDeleteReference(id.longValue()); } else { throw new RuntimeException("You try to delete a vtkObject that is not referenced in the Java object Map. You may have call Delete() twice."); } } finally { this.lock.unlock(); } } // Thread safe public vtkReferenceInformation gc(boolean debug) { System.gc(); try { this.lock.lock(); final vtkReferenceInformation infos = new vtkReferenceInformation(debug); for (Long id : new TreeSet<Long>(this.objectMap.keySet())) { vtkObjectBase obj = this.objectMap.get(id).get(); if (obj == null) { infos.addFreeObject(this.objectMapClassName.get(id)); this.unRegisterJavaObject(id); } else { infos.addKeptObject(this.objectMapClassName.get(id)); } } this.lastGcResult = infos; return infos; } finally { this.lock.unlock(); } } public vtkJavaGarbageCollector getAutoGarbageCollector() { return this.garbageCollector; } // Thread safe public int deleteAll() { int size = this.objectMap.size(); try { this.lock.lock(); for (Long id : new TreeSet<Long>(this.objectMap.keySet())) { this.unRegisterJavaObject(id); } } finally { this.lock.unlock(); } return size; } public int getSize() { return objectMap.size(); } public vtkReferenceInformation getLastReferenceInformation() { return this.lastGcResult; } }
vtkJavaMemoryManagerImpl: parameterize Constructor for inspection https://stackoverflow.com/questions/2238818/java-unchecked-call-to-getconstructorjava-lang-class
Wrapping/Java/vtk/vtkJavaMemoryManagerImpl.java
vtkJavaMemoryManagerImpl: parameterize Constructor for inspection
<ide><path>rapping/Java/vtk/vtkJavaMemoryManagerImpl.java <ide> if (resultObject == null) { <ide> try { <ide> String className = vtkObjectBase.VTKGetClassNameFromReference(vtkId.longValue()); <del> Class c = Class.forName("vtk." + className); <del> Constructor cons = c.getConstructor(new Class[] { long.class }); <add> Class<?> c = Class.forName("vtk." + className); <add> Constructor<?> cons = c.getConstructor(new Class<?>[] { long.class }); <ide> resultObject = (vtkObjectBase) cons.newInstance(new Object[] { vtkId }); <ide> } catch (Exception e) { <ide> e.printStackTrace();
Java
apache-2.0
2f72af40723d32cd121fa6fe4863f5a24ede8b9d
0
opennetworkinglab/onos,gkatsikas/onos,gkatsikas/onos,opennetworkinglab/onos,oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,opennetworkinglab/onos,opennetworkinglab/onos,gkatsikas/onos,gkatsikas/onos,gkatsikas/onos,oplinkoms/onos,oplinkoms/onos,oplinkoms/onos,opennetworkinglab/onos,oplinkoms/onos,opennetworkinglab/onos,oplinkoms/onos
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.roadm; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Range; import org.onlab.util.Frequency; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.net.ChannelSpacing; import org.onosproject.net.ConnectPoint; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.Direction; import org.onosproject.net.ModulationScheme; import org.onosproject.net.OchSignal; import org.onosproject.net.Port; import org.onosproject.net.OchSignalType; import org.onosproject.net.PortNumber; import org.onosproject.net.behaviour.LambdaQuery; import org.onosproject.net.behaviour.ModulationConfig; import org.onosproject.net.behaviour.PowerConfig; import org.onosproject.net.behaviour.protection.ProtectedTransportEndpointState; import org.onosproject.net.behaviour.protection.ProtectionConfigBehaviour; import org.onosproject.net.behaviour.protection.TransportEndpointState; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowEntry; import org.onosproject.net.flow.FlowId; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import org.onosproject.net.flow.criteria.Criteria; import org.onosproject.net.flow.instructions.Instruction; import org.onosproject.net.flow.instructions.Instructions; import org.onosproject.net.flow.instructions.L0ModificationInstruction; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.net.optical.OpticalAnnotations.INPUT_PORT_STATUS; import static org.onosproject.roadm.RoadmUtil.OPS_OPT_AUTO; import static org.onosproject.roadm.RoadmUtil.OPS_OPT_FORCE; import static org.onosproject.roadm.RoadmUtil.OPS_OPT_MANUAL; /** * Application for monitoring and configuring ROADM devices. */ @Component(immediate = true, service = RoadmService.class) public class RoadmManager implements RoadmService { private static final String APP_NAME = "org.onosproject.roadm"; private ApplicationId appId; private final Logger log = LoggerFactory.getLogger(getClass()); private DeviceListener deviceListener = new InternalDeviceListener(); @Reference(cardinality = ReferenceCardinality.MANDATORY) protected RoadmStore roadmStore; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected FlowRuleService flowRuleService; @Activate protected void activate() { appId = coreService.registerApplication(APP_NAME); deviceService.addListener(deviceListener); initDevices(); log.info("Started"); } @Deactivate protected void deactivate() { deviceService.removeListener(deviceListener); log.info("Stopped"); } @Deprecated @Override public void setProtectionSwitchWorkingPath(DeviceId deviceId, int index) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return; } Map<ConnectPoint, ProtectedTransportEndpointState> map = getProtectionSwitchStates(behaviour); if (map == null) { log.warn("Failed to get protected transport endpoint state in device {}", deviceId); return; } if (map.isEmpty()) { log.warn("No protected transport endpoint state found in device {}", deviceId); return; } behaviour.switchToManual(map.keySet().toArray(new ConnectPoint[0])[0], index); } @Deprecated @Override public String getProtectionSwitchPortState(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return null; } Map<ConnectPoint, ProtectedTransportEndpointState> map = getProtectionSwitchStates(behaviour); if (map == null) { log.warn("Failed to get protected transport endpoint state in device {}", deviceId); return null; } for (ProtectedTransportEndpointState state : map.values()) { for (TransportEndpointState element : state.pathStates()) { if (element.description().output().connectPoint().port().equals(portNumber)) { return element.attributes().get(INPUT_PORT_STATUS); } } } // Do not need warning here for port polling. log.debug("Unable to get port status, device: {}, port: {}", deviceId, portNumber); return null; } @Override public void configProtectionSwitch(DeviceId deviceId, String operation, ConnectPoint identifier, int index) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return; } // automatic operation if (OPS_OPT_AUTO.equals(operation)) { behaviour.switchToAutomatic(identifier); return; } // force or manual operation if (OPS_OPT_MANUAL.equals(operation)) { behaviour.switchToManual(identifier, index); } else if (OPS_OPT_FORCE.equals(operation)) { behaviour.switchToForce(identifier, index); } } @Override public Map<ConnectPoint, ProtectedTransportEndpointState> getProtectionSwitchStates(DeviceId deviceId) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return ImmutableMap.of(); } return getProtectionSwitchStates(behaviour); } @Override public void setTargetPortPower(DeviceId deviceId, PortNumber portNumber, double power) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { roadmStore.setTargetPower(deviceId, portNumber, power); powerConfig.setTargetPower(portNumber, Direction.ALL, power); } else { log.warn("Unable to set target port power for device {}", deviceId); } } @Override public Double getTargetPortPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); // Request target port power when it doesn't exist. Inactive updating mode. Double power = roadmStore.getTargetPower(deviceId, portNumber); if (power == null) { return syncTargetPortPower(deviceId, portNumber); } return power; } @Override public Double syncTargetPortPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> pl = powerConfig.getTargetPower(portNumber, Direction.ALL); if (pl.isPresent()) { roadmStore.setTargetPower(deviceId, portNumber, pl.get()); return pl.get(); } else { roadmStore.removeTargetPower(deviceId, portNumber); } } return null; } @Override public void setAttenuation(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal, double attenuation) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { powerConfig.setTargetPower(portNumber, ochSignal, attenuation); } else { log.warn("Cannot set attenuation for channel index {} on device {}", ochSignal.spacingMultiplier(), deviceId); } } @Override public Double getAttenuation(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> attenuation = powerConfig.getTargetPower(portNumber, ochSignal); if (attenuation.isPresent()) { return attenuation.get(); } } return null; } @Override public Double getCurrentPortPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> currentPower = powerConfig.currentPower(portNumber, Direction.ALL); if (currentPower.isPresent()) { return currentPower.get(); } } return null; } @Override public Double getCurrentChannelPower(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> currentPower = powerConfig.currentPower(portNumber, ochSignal); if (currentPower.isPresent()) { return currentPower.get(); } } return null; } @Override public Set<OchSignal> queryLambdas(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); LambdaQuery lambdaQuery = getLambdaQuery(deviceId); if (lambdaQuery != null) { return lambdaQuery.queryLambdas(portNumber); } return Collections.emptySet(); } @Override public ModulationScheme getModulation(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); Device device = deviceService.getDevice(deviceId); Direction component = Direction.ALL; if (device.is(ModulationConfig.class)) { ModulationConfig<Object> modulationConfig = device.as(ModulationConfig.class); Optional<ModulationScheme> scheme = modulationConfig.getModulationScheme(portNumber, component); if (scheme.isPresent()) { return scheme.get(); } } return null; } @Override public void setModulation(DeviceId deviceId, PortNumber portNumber, String modulation) { checkNotNull(deviceId); checkNotNull(portNumber); Device device = deviceService.getDevice(deviceId); Direction component = Direction.ALL; if (device.is(ModulationConfig.class)) { ModulationConfig<Object> modulationConfig = device.as(ModulationConfig.class); long bitRate = 0; if (modulation.equalsIgnoreCase(ModulationScheme.DP_QPSK.name())) { bitRate = 100; } else { bitRate = 200; } modulationConfig.setModulationScheme(portNumber, component, bitRate); } } @Override public FlowId createConnection(DeviceId deviceId, int priority, boolean isPermanent, int timeout, PortNumber inPort, PortNumber outPort, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(inPort); checkNotNull(outPort); //Creation of selector. TrafficSelector selector = DefaultTrafficSelector.builder() .add(Criteria.matchInPort(inPort)) .add(Criteria.matchOchSignalType(OchSignalType.FIXED_GRID)) .add(Criteria.matchLambda(ochSignal)) .build(); //Creation of treatment TrafficTreatment treatment = DefaultTrafficTreatment.builder() .add(Instructions.modL0Lambda(ochSignal)) .add(Instructions.createOutput(outPort)) .build(); FlowRule.Builder flowBuilder = DefaultFlowRule.builder() .forDevice(deviceId) .fromApp(appId) .withPriority(priority) .withSelector(selector) .withTreatment(treatment); if (isPermanent) { flowBuilder.makePermanent(); } else { flowBuilder.makeTemporary(timeout); } FlowRule flowRule = flowBuilder.build(); flowRuleService.applyFlowRules(flowRule); log.info("Created connection from input port {} to output port {}", inPort.toLong(), outPort.toLong()); return flowRule.id(); } @Override public FlowId createConnection(DeviceId deviceId, int priority, boolean isPermanent, int timeout, PortNumber inPort, PortNumber outPort, OchSignal ochSignal, Double attenuation) { checkNotNull(deviceId); checkNotNull(inPort); checkNotNull(outPort); FlowId flowId = createConnection(deviceId, priority, isPermanent, timeout, inPort, outPort, ochSignal); delayedSetAttenuation(deviceId, outPort, ochSignal, attenuation); return flowId; } @Override public Frequency getWavelength(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); Optional<FlowEntry> optFlow = StreamSupport .stream(flowRuleService.getFlowEntries(deviceId).spliterator(), false) .filter(flow -> { return flow.treatment().allInstructions().stream().filter(instr -> { if (instr.type().equals(Instruction.Type.OUTPUT)) { return ((Instructions.OutputInstruction) instr).port().equals(portNumber); } else if (instr.type().equals(Instruction.Type.L0MODIFICATION)) { return ((L0ModificationInstruction) instr).subtype() .equals(L0ModificationInstruction.L0SubType.OCH); } return false; }).count() == 2; }).findFirst(); if (optFlow.isPresent()) { Optional<Instruction> instruction = optFlow.get().treatment().allInstructions().stream().filter(instr -> { if (instr.type().equals(Instruction.Type.L0MODIFICATION)) { return ((L0ModificationInstruction) instr).subtype() .equals(L0ModificationInstruction.L0SubType.OCH); } return false; }).findAny(); if (instruction.isPresent()) { return ((L0ModificationInstruction.ModOchSignalInstruction) instruction.get()).lambda() .centralFrequency(); } } return null; } @Override public void removeConnection(DeviceId deviceId, FlowId flowId) { checkNotNull(deviceId); checkNotNull(flowId); for (FlowEntry entry : flowRuleService.getFlowEntries(deviceId)) { if (entry.id().equals(flowId)) { flowRuleService.removeFlowRules(entry); log.info("Deleted connection {}", entry.id()); break; } } } @Override public boolean hasPortTargetPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); return range.isPresent(); } return false; } @Override public boolean portTargetPowerInRange(DeviceId deviceId, PortNumber portNumber, double power) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); return range.isPresent() && range.get().contains(power); } return false; } @Override public boolean attenuationInRange(DeviceId deviceId, PortNumber outPort, double att) { checkNotNull(deviceId); checkNotNull(outPort); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { OchSignal stubOch = OchSignal.newDwdmSlot(ChannelSpacing.CHL_50GHZ, 0); Optional<Range<Double>> range = powerConfig.getTargetPowerRange(outPort, stubOch); return range.isPresent() && range.get().contains(att); } return false; } @Override public boolean validInputPort(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getInputPowerRange(portNumber, Direction.ALL); return range.isPresent(); } return false; } @Override public boolean validOutputPort(DeviceId deviceId, PortNumber portNumber) { return hasPortTargetPower(deviceId, portNumber); } @Override public boolean validChannel(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); LambdaQuery lambdaQuery = getLambdaQuery(deviceId); if (lambdaQuery != null) { Set<OchSignal> channels = lambdaQuery.queryLambdas(portNumber); return channels.contains(ochSignal); } return false; } @Override public boolean channelAvailable(DeviceId deviceId, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(ochSignal); for (FlowEntry entry : flowRuleService.getFlowEntries(deviceId)) { if (ChannelData.fromFlow(entry).ochSignal().equals(ochSignal)) { return false; } } return true; } @Override public boolean validConnection(DeviceId deviceId, PortNumber inPort, PortNumber outPort) { checkNotNull(deviceId); checkNotNull(inPort); checkNotNull(outPort); return validInputPort(deviceId, inPort) && validOutputPort(deviceId, outPort); } @Override public Range<Double> targetPortPowerRange(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); if (range.isPresent()) { return range.get(); } } return null; } @Override public Range<Double> attenuationRange(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, ochSignal); if (range.isPresent()) { return range.get(); } } return null; } @Override public Range<Double> inputPortPowerRange(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getInputPowerRange(portNumber, Direction.ALL); if (range.isPresent()) { return range.get(); } } return null; } private PowerConfig<Object> getPowerConfig(DeviceId deviceId) { Device device = deviceService.getDevice(deviceId); if (device != null && device.is(PowerConfig.class)) { return device.as(PowerConfig.class); } // Do not need warning here for port polling. log.debug("Unable to load PowerConfig for {}", deviceId); return null; } private LambdaQuery getLambdaQuery(DeviceId deviceId) { Device device = deviceService.getDevice(deviceId); if (device != null && device.is(LambdaQuery.class)) { return device.as(LambdaQuery.class); } // Do not need warning here for port polling. log.debug("Unable to load LambdaQuery for {}", deviceId); return null; } private ProtectionConfigBehaviour getProtectionConfig(DeviceId deviceId) { Device device = deviceService.getDevice(deviceId); if (device != null && device.is(ProtectionConfigBehaviour.class)) { return device.as(ProtectionConfigBehaviour.class); } // Do not need warning here for port polling. log.debug("Unable to load ProtectionConfigBehaviour for {}", deviceId); return null; } // Initialize all devices private void initDevices() { for (Device device : deviceService.getDevices(Device.Type.ROADM)) { initDevice(device.id()); //FIXME // As roadm application is a optional tool for now. // The target power initialization will be enhanced later, // hopefully using an formal optical subsystem. // setAllInitialTargetPortPowers(device.id()); } } // Initialize RoadmStore for a device to support target power private void initDevice(DeviceId deviceId) { if (!roadmStore.deviceAvailable(deviceId)) { roadmStore.addDevice(deviceId); } log.info("Initialized device {}", deviceId); } // Sets the target port powers for a port on a device // Attempts to read target powers from store. If no value is found then // default value is used instead. private void setInitialTargetPortPower(DeviceId deviceId, PortNumber portNumber) { PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig == null) { log.warn("Unable to set default initial powers for port {} on device {}", portNumber, deviceId); return; } Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); if (!range.isPresent()) { log.warn("No target power range found for port {} on device {}", portNumber, deviceId); return; } Double power = roadmStore.getTargetPower(deviceId, portNumber); if (power == null) { // Set default to middle of the range power = (range.get().lowerEndpoint() + range.get().upperEndpoint()) / 2; roadmStore.setTargetPower(deviceId, portNumber, power); } powerConfig.setTargetPower(portNumber, Direction.ALL, power); } // Sets the target port powers for each each port on a device // Attempts to read target powers from store. If no value is found then // default value is used instead private void setAllInitialTargetPortPowers(DeviceId deviceId) { PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig == null) { log.warn("Unable to set default initial powers for device {}", deviceId); return; } List<Port> ports = deviceService.getPorts(deviceId); for (Port port : ports) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(port.number(), Direction.ALL); if (range.isPresent()) { Double power = roadmStore.getTargetPower(deviceId, port.number()); if (power == null) { // Set default to middle of the range power = (range.get().lowerEndpoint() + range.get().upperEndpoint()) / 2; roadmStore.setTargetPower(deviceId, port.number(), power); } powerConfig.setTargetPower(port.number(), Direction.ALL, power); } else { log.warn("No target power range found for port {} on device {}", port.number(), deviceId); } } } // Delay the call to setTargetPower because the flow may not be in the store yet // Tested with Lumentum ROADM-20 1 seconds was not enough, increased to 5 seconds private void delayedSetAttenuation(DeviceId deviceId, PortNumber outPort, OchSignal ochSignal, Double attenuation) { Runnable setAtt = () -> { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { log.warn("Thread interrupted. Setting attenuation early."); Thread.currentThread().interrupt(); } setAttenuation(deviceId, outPort, ochSignal, attenuation); }; new Thread(setAtt).start(); } // get protection endpoint states private Map<ConnectPoint, ProtectedTransportEndpointState> getProtectionSwitchStates( ProtectionConfigBehaviour behaviour) { Map<ConnectPoint, ProtectedTransportEndpointState> map; try { map = behaviour.getProtectionEndpointStates().get(); } catch (InterruptedException e1) { log.error("Interrupted.", e1); Thread.currentThread().interrupt(); return ImmutableMap.of(); } catch (ExecutionException e1) { log.error("Exception caught.", e1); return ImmutableMap.of(); } return map; } // Listens to device events. private class InternalDeviceListener implements DeviceListener { @Override public void event(DeviceEvent deviceEvent) { Device device = deviceEvent.subject(); switch (deviceEvent.type()) { case DEVICE_ADDED: case DEVICE_UPDATED: initDevice(device.id()); break; case PORT_ADDED: case PORT_UPDATED: //FIXME // As roadm application is a optional tool for now. // The target power initialization will be enhanced later, // hopefully using an formal optical subsystem. // setInitialTargetPortPower(device.id(), deviceEvent.port().number()); break; default: break; } } } }
apps/roadm/app/src/main/java/org/onosproject/roadm/RoadmManager.java
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.roadm; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Range; import org.onlab.util.Frequency; import org.onosproject.core.ApplicationId; import org.onosproject.core.CoreService; import org.onosproject.net.ChannelSpacing; import org.onosproject.net.ConnectPoint; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.Direction; import org.onosproject.net.ModulationScheme; import org.onosproject.net.OchSignal; import org.onosproject.net.Port; import org.onosproject.net.PortNumber; import org.onosproject.net.behaviour.LambdaQuery; import org.onosproject.net.behaviour.ModulationConfig; import org.onosproject.net.behaviour.PowerConfig; import org.onosproject.net.behaviour.protection.ProtectedTransportEndpointState; import org.onosproject.net.behaviour.protection.ProtectionConfigBehaviour; import org.onosproject.net.behaviour.protection.TransportEndpointState; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceService; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.FlowEntry; import org.onosproject.net.flow.FlowId; import org.onosproject.net.flow.FlowRule; import org.onosproject.net.flow.FlowRuleService; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import org.onosproject.net.flow.criteria.Criteria; import org.onosproject.net.flow.instructions.Instruction; import org.onosproject.net.flow.instructions.Instructions; import org.onosproject.net.flow.instructions.L0ModificationInstruction; import org.osgi.service.component.annotations.Activate; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Deactivate; import org.osgi.service.component.annotations.Reference; import org.osgi.service.component.annotations.ReferenceCardinality; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport; import static com.google.common.base.Preconditions.checkNotNull; import static org.onosproject.net.optical.OpticalAnnotations.INPUT_PORT_STATUS; import static org.onosproject.roadm.RoadmUtil.OPS_OPT_AUTO; import static org.onosproject.roadm.RoadmUtil.OPS_OPT_FORCE; import static org.onosproject.roadm.RoadmUtil.OPS_OPT_MANUAL; /** * Application for monitoring and configuring ROADM devices. */ @Component(immediate = true, service = RoadmService.class) public class RoadmManager implements RoadmService { private static final String APP_NAME = "org.onosproject.roadm"; private ApplicationId appId; private final Logger log = LoggerFactory.getLogger(getClass()); private DeviceListener deviceListener = new InternalDeviceListener(); @Reference(cardinality = ReferenceCardinality.MANDATORY) protected RoadmStore roadmStore; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected CoreService coreService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected DeviceService deviceService; @Reference(cardinality = ReferenceCardinality.MANDATORY) protected FlowRuleService flowRuleService; @Activate protected void activate() { appId = coreService.registerApplication(APP_NAME); deviceService.addListener(deviceListener); initDevices(); log.info("Started"); } @Deactivate protected void deactivate() { deviceService.removeListener(deviceListener); log.info("Stopped"); } @Deprecated @Override public void setProtectionSwitchWorkingPath(DeviceId deviceId, int index) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return; } Map<ConnectPoint, ProtectedTransportEndpointState> map = getProtectionSwitchStates(behaviour); if (map == null) { log.warn("Failed to get protected transport endpoint state in device {}", deviceId); return; } if (map.isEmpty()) { log.warn("No protected transport endpoint state found in device {}", deviceId); return; } behaviour.switchToManual(map.keySet().toArray(new ConnectPoint[0])[0], index); } @Deprecated @Override public String getProtectionSwitchPortState(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return null; } Map<ConnectPoint, ProtectedTransportEndpointState> map = getProtectionSwitchStates(behaviour); if (map == null) { log.warn("Failed to get protected transport endpoint state in device {}", deviceId); return null; } for (ProtectedTransportEndpointState state : map.values()) { for (TransportEndpointState element : state.pathStates()) { if (element.description().output().connectPoint().port().equals(portNumber)) { return element.attributes().get(INPUT_PORT_STATUS); } } } // Do not need warning here for port polling. log.debug("Unable to get port status, device: {}, port: {}", deviceId, portNumber); return null; } @Override public void configProtectionSwitch(DeviceId deviceId, String operation, ConnectPoint identifier, int index) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return; } // automatic operation if (OPS_OPT_AUTO.equals(operation)) { behaviour.switchToAutomatic(identifier); return; } // force or manual operation if (OPS_OPT_MANUAL.equals(operation)) { behaviour.switchToManual(identifier, index); } else if (OPS_OPT_FORCE.equals(operation)) { behaviour.switchToForce(identifier, index); } } @Override public Map<ConnectPoint, ProtectedTransportEndpointState> getProtectionSwitchStates(DeviceId deviceId) { checkNotNull(deviceId); ProtectionConfigBehaviour behaviour = getProtectionConfig(deviceId); if (behaviour == null) { return ImmutableMap.of(); } return getProtectionSwitchStates(behaviour); } @Override public void setTargetPortPower(DeviceId deviceId, PortNumber portNumber, double power) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { roadmStore.setTargetPower(deviceId, portNumber, power); powerConfig.setTargetPower(portNumber, Direction.ALL, power); } else { log.warn("Unable to set target port power for device {}", deviceId); } } @Override public Double getTargetPortPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); // Request target port power when it doesn't exist. Inactive updating mode. Double power = roadmStore.getTargetPower(deviceId, portNumber); if (power == null) { return syncTargetPortPower(deviceId, portNumber); } return power; } @Override public Double syncTargetPortPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> pl = powerConfig.getTargetPower(portNumber, Direction.ALL); if (pl.isPresent()) { roadmStore.setTargetPower(deviceId, portNumber, pl.get()); return pl.get(); } else { roadmStore.removeTargetPower(deviceId, portNumber); } } return null; } @Override public void setAttenuation(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal, double attenuation) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { powerConfig.setTargetPower(portNumber, ochSignal, attenuation); } else { log.warn("Cannot set attenuation for channel index {} on device {}", ochSignal.spacingMultiplier(), deviceId); } } @Override public Double getAttenuation(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> attenuation = powerConfig.getTargetPower(portNumber, ochSignal); if (attenuation.isPresent()) { return attenuation.get(); } } return null; } @Override public Double getCurrentPortPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> currentPower = powerConfig.currentPower(portNumber, Direction.ALL); if (currentPower.isPresent()) { return currentPower.get(); } } return null; } @Override public Double getCurrentChannelPower(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Double> currentPower = powerConfig.currentPower(portNumber, ochSignal); if (currentPower.isPresent()) { return currentPower.get(); } } return null; } @Override public Set<OchSignal> queryLambdas(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); LambdaQuery lambdaQuery = getLambdaQuery(deviceId); if (lambdaQuery != null) { return lambdaQuery.queryLambdas(portNumber); } return Collections.emptySet(); } @Override public ModulationScheme getModulation(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); Device device = deviceService.getDevice(deviceId); Direction component = Direction.ALL; if (device.is(ModulationConfig.class)) { ModulationConfig<Object> modulationConfig = device.as(ModulationConfig.class); Optional<ModulationScheme> scheme = modulationConfig.getModulationScheme(portNumber, component); if (scheme.isPresent()) { return scheme.get(); } } return null; } @Override public void setModulation(DeviceId deviceId, PortNumber portNumber, String modulation) { checkNotNull(deviceId); checkNotNull(portNumber); Device device = deviceService.getDevice(deviceId); Direction component = Direction.ALL; if (device.is(ModulationConfig.class)) { ModulationConfig<Object> modulationConfig = device.as(ModulationConfig.class); long bitRate = 0; if (modulation.equalsIgnoreCase(ModulationScheme.DP_QPSK.name())) { bitRate = 100; } else { bitRate = 200; } modulationConfig.setModulationScheme(portNumber, component, bitRate); } } @Override public FlowId createConnection(DeviceId deviceId, int priority, boolean isPermanent, int timeout, PortNumber inPort, PortNumber outPort, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(inPort); checkNotNull(outPort); TrafficSelector selector = DefaultTrafficSelector.builder() .add(Criteria.matchInPort(inPort)) .build(); TrafficTreatment treatment = DefaultTrafficTreatment.builder() .add(Instructions.modL0Lambda(ochSignal)) .add(Instructions.createOutput(outPort)) .build(); FlowRule.Builder flowBuilder = DefaultFlowRule.builder() .forDevice(deviceId) .fromApp(appId) .withPriority(priority) .withSelector(selector) .withTreatment(treatment); if (isPermanent) { flowBuilder.makePermanent(); } else { flowBuilder.makeTemporary(timeout); } FlowRule flowRule = flowBuilder.build(); flowRuleService.applyFlowRules(flowRule); log.info("Created connection from input port {} to output port {}", inPort.toLong(), outPort.toLong()); return flowRule.id(); } @Override public FlowId createConnection(DeviceId deviceId, int priority, boolean isPermanent, int timeout, PortNumber inPort, PortNumber outPort, OchSignal ochSignal, Double attenuation) { checkNotNull(deviceId); checkNotNull(inPort); checkNotNull(outPort); FlowId flowId = createConnection(deviceId, priority, isPermanent, timeout, inPort, outPort, ochSignal); delayedSetAttenuation(deviceId, outPort, ochSignal, attenuation); return flowId; } @Override public Frequency getWavelength(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); Optional<FlowEntry> optFlow = StreamSupport .stream(flowRuleService.getFlowEntries(deviceId).spliterator(), false) .filter(flow -> { return flow.treatment().allInstructions().stream().filter(instr -> { if (instr.type().equals(Instruction.Type.OUTPUT)) { return ((Instructions.OutputInstruction) instr).port().equals(portNumber); } else if (instr.type().equals(Instruction.Type.L0MODIFICATION)) { return ((L0ModificationInstruction) instr).subtype() .equals(L0ModificationInstruction.L0SubType.OCH); } return false; }).count() == 2; }).findFirst(); if (optFlow.isPresent()) { Optional<Instruction> instruction = optFlow.get().treatment().allInstructions().stream().filter(instr -> { if (instr.type().equals(Instruction.Type.L0MODIFICATION)) { return ((L0ModificationInstruction) instr).subtype() .equals(L0ModificationInstruction.L0SubType.OCH); } return false; }).findAny(); if (instruction.isPresent()) { return ((L0ModificationInstruction.ModOchSignalInstruction) instruction.get()).lambda() .centralFrequency(); } } return null; } @Override public void removeConnection(DeviceId deviceId, FlowId flowId) { checkNotNull(deviceId); checkNotNull(flowId); for (FlowEntry entry : flowRuleService.getFlowEntries(deviceId)) { if (entry.id().equals(flowId)) { flowRuleService.removeFlowRules(entry); log.info("Deleted connection {}", entry.id()); break; } } } @Override public boolean hasPortTargetPower(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); return range.isPresent(); } return false; } @Override public boolean portTargetPowerInRange(DeviceId deviceId, PortNumber portNumber, double power) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); return range.isPresent() && range.get().contains(power); } return false; } @Override public boolean attenuationInRange(DeviceId deviceId, PortNumber outPort, double att) { checkNotNull(deviceId); checkNotNull(outPort); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { OchSignal stubOch = OchSignal.newDwdmSlot(ChannelSpacing.CHL_50GHZ, 0); Optional<Range<Double>> range = powerConfig.getTargetPowerRange(outPort, stubOch); return range.isPresent() && range.get().contains(att); } return false; } @Override public boolean validInputPort(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getInputPowerRange(portNumber, Direction.ALL); return range.isPresent(); } return false; } @Override public boolean validOutputPort(DeviceId deviceId, PortNumber portNumber) { return hasPortTargetPower(deviceId, portNumber); } @Override public boolean validChannel(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); LambdaQuery lambdaQuery = getLambdaQuery(deviceId); if (lambdaQuery != null) { Set<OchSignal> channels = lambdaQuery.queryLambdas(portNumber); return channels.contains(ochSignal); } return false; } @Override public boolean channelAvailable(DeviceId deviceId, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(ochSignal); for (FlowEntry entry : flowRuleService.getFlowEntries(deviceId)) { if (ChannelData.fromFlow(entry).ochSignal().equals(ochSignal)) { return false; } } return true; } @Override public boolean validConnection(DeviceId deviceId, PortNumber inPort, PortNumber outPort) { checkNotNull(deviceId); checkNotNull(inPort); checkNotNull(outPort); return validInputPort(deviceId, inPort) && validOutputPort(deviceId, outPort); } @Override public Range<Double> targetPortPowerRange(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); if (range.isPresent()) { return range.get(); } } return null; } @Override public Range<Double> attenuationRange(DeviceId deviceId, PortNumber portNumber, OchSignal ochSignal) { checkNotNull(deviceId); checkNotNull(portNumber); checkNotNull(ochSignal); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, ochSignal); if (range.isPresent()) { return range.get(); } } return null; } @Override public Range<Double> inputPortPowerRange(DeviceId deviceId, PortNumber portNumber) { checkNotNull(deviceId); checkNotNull(portNumber); PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig != null) { Optional<Range<Double>> range = powerConfig.getInputPowerRange(portNumber, Direction.ALL); if (range.isPresent()) { return range.get(); } } return null; } private PowerConfig<Object> getPowerConfig(DeviceId deviceId) { Device device = deviceService.getDevice(deviceId); if (device != null && device.is(PowerConfig.class)) { return device.as(PowerConfig.class); } // Do not need warning here for port polling. log.debug("Unable to load PowerConfig for {}", deviceId); return null; } private LambdaQuery getLambdaQuery(DeviceId deviceId) { Device device = deviceService.getDevice(deviceId); if (device != null && device.is(LambdaQuery.class)) { return device.as(LambdaQuery.class); } // Do not need warning here for port polling. log.debug("Unable to load LambdaQuery for {}", deviceId); return null; } private ProtectionConfigBehaviour getProtectionConfig(DeviceId deviceId) { Device device = deviceService.getDevice(deviceId); if (device != null && device.is(ProtectionConfigBehaviour.class)) { return device.as(ProtectionConfigBehaviour.class); } // Do not need warning here for port polling. log.debug("Unable to load ProtectionConfigBehaviour for {}", deviceId); return null; } // Initialize all devices private void initDevices() { for (Device device : deviceService.getDevices(Device.Type.ROADM)) { initDevice(device.id()); //FIXME // As roadm application is a optional tool for now. // The target power initialization will be enhanced later, // hopefully using an formal optical subsystem. // setAllInitialTargetPortPowers(device.id()); } } // Initialize RoadmStore for a device to support target power private void initDevice(DeviceId deviceId) { if (!roadmStore.deviceAvailable(deviceId)) { roadmStore.addDevice(deviceId); } log.info("Initialized device {}", deviceId); } // Sets the target port powers for a port on a device // Attempts to read target powers from store. If no value is found then // default value is used instead. private void setInitialTargetPortPower(DeviceId deviceId, PortNumber portNumber) { PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig == null) { log.warn("Unable to set default initial powers for port {} on device {}", portNumber, deviceId); return; } Optional<Range<Double>> range = powerConfig.getTargetPowerRange(portNumber, Direction.ALL); if (!range.isPresent()) { log.warn("No target power range found for port {} on device {}", portNumber, deviceId); return; } Double power = roadmStore.getTargetPower(deviceId, portNumber); if (power == null) { // Set default to middle of the range power = (range.get().lowerEndpoint() + range.get().upperEndpoint()) / 2; roadmStore.setTargetPower(deviceId, portNumber, power); } powerConfig.setTargetPower(portNumber, Direction.ALL, power); } // Sets the target port powers for each each port on a device // Attempts to read target powers from store. If no value is found then // default value is used instead private void setAllInitialTargetPortPowers(DeviceId deviceId) { PowerConfig<Object> powerConfig = getPowerConfig(deviceId); if (powerConfig == null) { log.warn("Unable to set default initial powers for device {}", deviceId); return; } List<Port> ports = deviceService.getPorts(deviceId); for (Port port : ports) { Optional<Range<Double>> range = powerConfig.getTargetPowerRange(port.number(), Direction.ALL); if (range.isPresent()) { Double power = roadmStore.getTargetPower(deviceId, port.number()); if (power == null) { // Set default to middle of the range power = (range.get().lowerEndpoint() + range.get().upperEndpoint()) / 2; roadmStore.setTargetPower(deviceId, port.number(), power); } powerConfig.setTargetPower(port.number(), Direction.ALL, power); } else { log.warn("No target power range found for port {} on device {}", port.number(), deviceId); } } } // Delay the call to setTargetPower because the flow may not be in the store yet // Tested with Lumentum ROADM-20 1 seconds was not enough, increased to 5 seconds private void delayedSetAttenuation(DeviceId deviceId, PortNumber outPort, OchSignal ochSignal, Double attenuation) { Runnable setAtt = () -> { try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { log.warn("Thread interrupted. Setting attenuation early."); Thread.currentThread().interrupt(); } setAttenuation(deviceId, outPort, ochSignal, attenuation); }; new Thread(setAtt).start(); } // get protection endpoint states private Map<ConnectPoint, ProtectedTransportEndpointState> getProtectionSwitchStates( ProtectionConfigBehaviour behaviour) { Map<ConnectPoint, ProtectedTransportEndpointState> map; try { map = behaviour.getProtectionEndpointStates().get(); } catch (InterruptedException e1) { log.error("Interrupted.", e1); Thread.currentThread().interrupt(); return ImmutableMap.of(); } catch (ExecutionException e1) { log.error("Exception caught.", e1); return ImmutableMap.of(); } return map; } // Listens to device events. private class InternalDeviceListener implements DeviceListener { @Override public void event(DeviceEvent deviceEvent) { Device device = deviceEvent.subject(); switch (deviceEvent.type()) { case DEVICE_ADDED: case DEVICE_UPDATED: initDevice(device.id()); break; case PORT_ADDED: case PORT_UPDATED: //FIXME // As roadm application is a optional tool for now. // The target power initialization will be enhanced later, // hopefully using an formal optical subsystem. // setInitialTargetPortPower(device.id(), deviceEvent.port().number()); break; default: break; } } } }
Alignment of the generated flow rule format to the format used by the intent framework for OpticalConnectivityIntent. Patch 2: checkstyle. Change-Id: I133459274d37df5c74f8599d382a3370b26ae640
apps/roadm/app/src/main/java/org/onosproject/roadm/RoadmManager.java
Alignment of the generated flow rule format to the format used by the intent framework for OpticalConnectivityIntent.
<ide><path>pps/roadm/app/src/main/java/org/onosproject/roadm/RoadmManager.java <ide> import org.onosproject.net.ModulationScheme; <ide> import org.onosproject.net.OchSignal; <ide> import org.onosproject.net.Port; <add>import org.onosproject.net.OchSignalType; <ide> import org.onosproject.net.PortNumber; <ide> import org.onosproject.net.behaviour.LambdaQuery; <ide> import org.onosproject.net.behaviour.ModulationConfig; <ide> checkNotNull(inPort); <ide> checkNotNull(outPort); <ide> <add> //Creation of selector. <ide> TrafficSelector selector = DefaultTrafficSelector.builder() <ide> .add(Criteria.matchInPort(inPort)) <add> .add(Criteria.matchOchSignalType(OchSignalType.FIXED_GRID)) <add> .add(Criteria.matchLambda(ochSignal)) <ide> .build(); <add> <add> //Creation of treatment <ide> TrafficTreatment treatment = DefaultTrafficTreatment.builder() <ide> .add(Instructions.modL0Lambda(ochSignal)) <ide> .add(Instructions.createOutput(outPort))
Java
bsd-3-clause
aef0624bac344b31e3b8ba5b89218cc1dac023af
0
interdroid/ibis-ipl,interdroid/ibis-ipl,interdroid/ibis-ipl
/* * Created on Apr 27, 2006 */ package ibis.satin.impl.sharedObjects; import ibis.ipl.IbisIdentifier; import ibis.ipl.ReadMessage; import ibis.ipl.StaticProperties; import ibis.satin.SharedObject; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.spawnSync.InvocationRecord; import java.util.HashMap; import java.util.Vector; class SharedObjectInfo { long lastBroadcastTime; IbisIdentifier[] destinations; SharedObject sharedObject; } public final class SharedObjects implements Config { /* use these to avoid locking */ protected volatile boolean gotSORequests = false; protected boolean receivingMcast = false; /** List that stores requests for shared object transfers */ protected SORequestList SORequestList = new SORequestList(); /** Used for storing pending shared object invocations (SOInvocationRecords)*/ private Vector soInvocationList = new Vector(); private Satin s; private volatile boolean gotSOInvocations = false; /** A hash containing all shared objects: * (String objectID, SharedObject object) */ private HashMap sharedObjects = new HashMap(); private SOCommunication soComm; public SharedObjects(Satin s, StaticProperties requestedProperties) { this.s = s; soComm = new SOCommunication(s); soComm.init(requestedProperties); } /** Add an object to the object table */ public void addObject(SharedObject object) { SharedObjectInfo i = new SharedObjectInfo(); i.sharedObject = object; synchronized (s) { sharedObjects.put(object.objectId, i); } soLogger.debug("SATIN '" + s.ident.name() + "': " + "object added, id = " + object.objectId); } /** Return a reference to a shared object */ public SharedObject getSOReference(String objectId) { synchronized (s) { SharedObjectInfo i = (SharedObjectInfo) sharedObjects.get(objectId); if (i == null) { soLogger.warn("SATIN '" + s.ident.name() + "': " + "object not found in getSOReference"); return null; } return i.sharedObject; } } /** Return a reference to a shared object */ public SharedObjectInfo getSOInfo(String objectId) { synchronized (s) { return (SharedObjectInfo) sharedObjects.get(objectId); } } void registerMulticast(SharedObject object, IbisIdentifier[] destinations) { synchronized (s) { SharedObjectInfo i = (SharedObjectInfo) sharedObjects.get(object.objectId); if (i == null) { soLogger.warn("OOPS, object not found in registerMulticast"); return; } i.destinations = destinations; i.lastBroadcastTime = System.currentTimeMillis(); } } /** * Execute all the so invocations stored in the so invocations list */ public void handleSOInvocations() { gotSOInvocations = false; while (true) { s.stats.handleSOInvocationsTimer.start(); if (soInvocationList.size() == 0) { s.stats.handleSOInvocationsTimer.stop(); return; } SOInvocationRecord soir = (SOInvocationRecord) soInvocationList.remove(0); SharedObject so = getSOReference(soir.getObjectId()); if (so == null) { s.stats.handleSOInvocationsTimer.stop(); return; } // No need to hold the satin lock here. // Object transfer requests cannot be handled // in the middle of a method invocation, // as transfers are delayed until a safe point is // reached soir.invoke(so); s.stats.handleSOInvocationsTimer.stop(); } } /** * Check if the given shared object is in the table, if not, ship it from * source. This is called from the generated code. */ public void setSOReference(String objectId, IbisIdentifier source) throws SOReferenceSourceCrashedException { s.handleDelayedMessages(); SharedObject obj = getSOReference(objectId); if (obj == null) { soComm.fetchObject(objectId, source, null); } } /** * Add a shared object invocation record to the so invocation record list; * the invocation will be executed later */ public void addSOInvocation(SOInvocationRecord soir) { synchronized (s) { soInvocationList.add(soir); gotSOInvocations = true; s.notifyAll(); } } /** returns false if the job must be aborted */ public boolean executeGuard(InvocationRecord r) { try { doExecuteGuard(r); } catch (SOReferenceSourceCrashedException e) { //the source has crashed - abort the job return false; } return true; } /** * Execute the guard of the invocation record r, wait for updates, if * necessary, ship objects if necessary */ private void doExecuteGuard(InvocationRecord r) throws SOReferenceSourceCrashedException { // restore shared object references r.setSOReferences(); if (r.guard()) return; s.stats.soGuardTimer.start(); soLogger.info("SATIN '" + s.ident.name() + "': " + "guard not satisfied, getting updates.."); // try to ship the object(s) from the owner of the job Vector objRefs = r.getSOReferences(); if (objRefs == null || objRefs.isEmpty()) { soLogger .fatal("SATIN '" + s.ident.name() + "': " + "a guard is not satisfied, but the spawn does not have shared objects.\nThis is not a correct Satin program."); System.exit(1); } // A shared object update may have arrived // during one of the fetches. while (true) { s.handleDelayedMessages(); if (r.guard()) { s.stats.soGuardTimer.stop(); return; } String ref = (String) objRefs.remove(0); soComm.fetchObject(ref, r.getOwner(), r); } } public void addToSORequestList(IbisIdentifier requester, String objID, boolean demand) { Satin.assertLocked(s); SORequestList.add(requester, objID, demand); gotSORequests = true; } public void handleDelayedMessages() { if (gotSORequests) { soComm.handleSORequests(); } if (gotSOInvocations) { s.so.handleSOInvocations(); } soComm.sendAccumulatedSOInvocations(); } public void handleSORequest(ReadMessage m, boolean demand) { soComm.handleSORequest(m, demand); } public void handleSOTransfer(ReadMessage m) { soComm.handleSOTransfer(m); } public void handleSONack(ReadMessage m) { soComm.handleSONack(m); } public void createSoPorts(IbisIdentifier[] joiners) { soComm.createSoReceivePorts(joiners); } public void handleMyOwnJoin() { soComm.handleMyOwnJoin(); } public void addSOConnection(IbisIdentifier id) { soComm.addSOConnection(id); } public void removeSOConnection(IbisIdentifier id) { soComm.removeSOConnection(id); } public void broadcastSOInvocation(SOInvocationRecord r) { soComm.broadcastSOInvocation(r); } public void broadcastSharedObject(SharedObject object) { soComm.broadcastSharedObject(object); } }
src/ibis/satin/impl/sharedObjects/SharedObjects.java
/* * Created on Apr 27, 2006 */ package ibis.satin.impl.sharedObjects; import ibis.ipl.IbisIdentifier; import ibis.ipl.ReadMessage; import ibis.ipl.StaticProperties; import ibis.satin.SharedObject; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.spawnSync.InvocationRecord; import java.util.HashMap; import java.util.Vector; class SharedObjectInfo { long lastBroadcastTime; IbisIdentifier[] destinations; SharedObject sharedObject; } public final class SharedObjects implements Config { /* use these to avoid locking */ protected volatile boolean gotSORequests = false; protected boolean receivingMcast = false; /** List that stores requests for shared object transfers */ protected SORequestList SORequestList = new SORequestList(); /** Used for storing pending shared object invocations (SOInvocationRecords)*/ private Vector soInvocationList = new Vector(); private Satin s; private volatile boolean gotSOInvocations = false; /** A hash containing all shared objects: * (String objectID, SharedObject object) */ private HashMap sharedObjects = new HashMap(); private SOCommunication soComm; public SharedObjects(Satin s, StaticProperties requestedProperties) { this.s = s; soComm = new SOCommunication(s); soComm.init(requestedProperties); } /** Add an object to the object table */ public void addObject(SharedObject object) { SharedObjectInfo i = new SharedObjectInfo(); i.sharedObject = object; synchronized (s) { sharedObjects.put(object.objectId, i); } soLogger.debug("SATIN '" + s.ident.name() + "': " + "object added, id = " + object.objectId); } /** Return a reference to a shared object */ public SharedObject getSOReference(String objectId) { synchronized (s) { SharedObjectInfo i = (SharedObjectInfo) sharedObjects.get(objectId); if (i == null) { soLogger.warn("SATIN '" + s.ident.name() + "': " + "object not found in getSOReference"); return null; } return i.sharedObject; } } /** Return a reference to a shared object */ public SharedObjectInfo getSOInfo(String objectId) { synchronized (s) { return (SharedObjectInfo) sharedObjects.get(objectId); } } void registerMulticast(SharedObject object, IbisIdentifier[] destinations) { synchronized (s) { SharedObjectInfo i = (SharedObjectInfo) sharedObjects.get(object.objectId); if (i == null) { soLogger.warn("OOPS, object not found in registerMulticast"); return; } i.destinations = destinations; i.lastBroadcastTime = System.currentTimeMillis(); } } /** * Execute all the so invocations stored in the so invocations list */ public void handleSOInvocations() { gotSOInvocations = false; while (true) { s.stats.handleSOInvocationsTimer.start(); if (soInvocationList.size() == 0) { s.stats.handleSOInvocationsTimer.stop(); return; } SOInvocationRecord soir = (SOInvocationRecord) soInvocationList.remove(0); SharedObject so = getSOReference(soir.getObjectId()); if (so == null) { s.stats.handleSOInvocationsTimer.stop(); return; } // No need to hold the satin lock here. // Object transfer requests cannot be handled // in the middle of a method invocation, // as transfers are delayed until a safe point is // reached soir.invoke(so); s.stats.handleSOInvocationsTimer.stop(); } } /** * Check if the given shared object is in the table, if not, ship it from * source. This is called from the generated code. */ public void setSOReference(String objectId, IbisIdentifier source) throws SOReferenceSourceCrashedException { s.handleDelayedMessages(); SharedObject obj = getSOReference(objectId); if (obj == null) { soComm.fetchObject(objectId, source, null); } } /** * Add a shared object invocation record to the so invocation record list; * the invocation will be executed later */ public void addSOInvocation(SOInvocationRecord soir) { synchronized (s) { soInvocationList.add(soir); gotSOInvocations = true; s.notifyAll(); } } /** returns false if the job must be aborted */ public boolean executeGuard(InvocationRecord r) { s.stats.soGuardTimer.start(); try { doExecuteGuard(r); } catch (SOReferenceSourceCrashedException e) { //the source has crashed - abort the job s.stats.soGuardTimer.stop(); return false; } s.stats.soGuardTimer.stop(); return true; } /** * Execute the guard of the invocation record r, wait for updates, if * necessary, ship objects if necessary */ private void doExecuteGuard(InvocationRecord r) throws SOReferenceSourceCrashedException { // restore shared object references r.setSOReferences(); if (r.guard()) return; soLogger.info("SATIN '" + s.ident.name() + "': " + "guard not satisfied, getting updates.."); // try to ship the object(s) from the owner of the job Vector objRefs = r.getSOReferences(); if (objRefs == null || objRefs.isEmpty()) { soLogger .fatal("SATIN '" + s.ident.name() + "': " + "a guard is not satisfied, but the spawn does not have shared objects.\nThis is not a correct Satin program."); } // A shared object update may have arrived // during one of the fetches. while (true) { s.handleDelayedMessages(); if (r.guard()) return; String ref = (String) objRefs.remove(0); soComm.fetchObject(ref, r.getOwner(), r); } } public void addToSORequestList(IbisIdentifier requester, String objID, boolean demand) { Satin.assertLocked(s); SORequestList.add(requester, objID, demand); gotSORequests = true; } public void handleDelayedMessages() { if (gotSORequests) { soComm.handleSORequests(); } if (gotSOInvocations) { s.so.handleSOInvocations(); } soComm.sendAccumulatedSOInvocations(); } public void handleSORequest(ReadMessage m, boolean demand) { soComm.handleSORequest(m, demand); } public void handleSOTransfer(ReadMessage m) { soComm.handleSOTransfer(m); } public void handleSONack(ReadMessage m) { soComm.handleSONack(m); } public void createSoPorts(IbisIdentifier[] joiners) { soComm.createSoReceivePorts(joiners); } public void handleMyOwnJoin() { soComm.handleMyOwnJoin(); } public void addSOConnection(IbisIdentifier id) { soComm.addSOConnection(id); } public void removeSOConnection(IbisIdentifier id) { soComm.removeSOConnection(id); } public void broadcastSOInvocation(SOInvocationRecord r) { soComm.broadcastSOInvocation(r); } public void broadcastSharedObject(SharedObject object) { soComm.broadcastSharedObject(object); } }
git-svn-id: http://gforge.cs.vu.nl/svn/ibis/ibis/trunk@4101 aaf88347-d911-0410-b711-e54d386773bb
src/ibis/satin/impl/sharedObjects/SharedObjects.java
<ide><path>rc/ibis/satin/impl/sharedObjects/SharedObjects.java <ide> <ide> /** returns false if the job must be aborted */ <ide> public boolean executeGuard(InvocationRecord r) { <del> s.stats.soGuardTimer.start(); <ide> try { <ide> doExecuteGuard(r); <ide> } catch (SOReferenceSourceCrashedException e) { <ide> //the source has crashed - abort the job <del> s.stats.soGuardTimer.stop(); <ide> return false; <ide> } <del> s.stats.soGuardTimer.stop(); <ide> return true; <ide> } <ide> <ide> r.setSOReferences(); <ide> <ide> if (r.guard()) return; <add> <add> s.stats.soGuardTimer.start(); <ide> <ide> soLogger.info("SATIN '" + s.ident.name() + "': " <ide> + "guard not satisfied, getting updates.."); <ide> soLogger <ide> .fatal("SATIN '" + s.ident.name() + "': " <ide> + "a guard is not satisfied, but the spawn does not have shared objects.\nThis is not a correct Satin program."); <add> System.exit(1); <ide> } <ide> <ide> // A shared object update may have arrived <ide> // during one of the fetches. <ide> while (true) { <ide> s.handleDelayedMessages(); <del> if (r.guard()) return; <add> if (r.guard()) { <add> s.stats.soGuardTimer.stop(); <add> return; <add> } <ide> <ide> String ref = (String) objRefs.remove(0); <ide> soComm.fetchObject(ref, r.getOwner(), r);
Java
mit
ced2b669f08302a88c85b01509c588a2f1123ad6
0
AmadouSallah/Programming-Interview-Questions,AmadouSallah/Programming-Interview-Questions
/* Resource: https://leetcode.com/problems/binary-tree-vertical-order-traversal/#/description Leetcode Problem 314. Binary Tree Vertical Order Traversal Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Examples: 1. Given binary tree [3,9,20,null,null,15,7], 3 /\ / \ 9 20 /\ / \ 15 7 return its vertical order traversal as: [[9], [3,15], [20], [7]] 2. Given binary tree [3,9,8,4,0,1,7], 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7 return its vertical order traversal as: [[4], [9], [3,0,1], [8], [7]] 3. Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5), 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7 /\ / \ 5 2 return its vertical order traversal as: [[4], [9,5], [3,0,1], [8,2], [7]] */ import java.util.*; public class VerticalOrderTraversal { public class TreeNode { int val; TreeNode left, right; TreeNode(int x) { val = x; } } public List<List<Integer>> verticalOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; Map<Integer, List<Integer>> map = new HashMap<>(); // key will be column number and value will be the list of all elements on that column Queue<TreeNode> queue = new LinkedList<>(); // queue will contain the tree nodes Queue<Integer> columns = new LinkedList<>(); // columns will contain the columns of the tree int minColumn = 0, maxColumn = 0; queue.add(root); columns.add(0); // root is at column 0; while (!queue.isEmpty()) { TreeNode node = queue.poll(); int col = columns.poll(); // if col has not been seen yet, we add it to map with value an empty list if (!map.containsKey(col)) { map.put(col, new ArrayList<>()); } // we add the value of current node to queue map.get(col).add(node.val); // if node has a left (respectively right) child, add it to queue and add col-1 // (respectively col+1) to columns. Then update minColumn and maxColumn if (node.left != null) { int nextLeftColumn = col-1; queue.add(node.left); columns.add(nextLeftColumn); minColumn = Math.min(minColumn, nextLeftColumn); } if (node.right != null) { int nextRightColumn = col + 1; queue.add(node.right); columns.add(nextRightColumn); maxColumn = Math.max(maxColumn, nextRightColumn); } } // Iterate through keys of map and add the corresponding list values to result for (int i = minColumn; i <= maxColumn; i++) { result.add(map.get(i)); } return result; } }
leetcode/java/prob314BinaryTreeVerticalOrderTraversal/VerticalOrderTraversal.java
/* Resource: https://leetcode.com/problems/binary-tree-vertical-order-traversal/#/description Leetcode Problem 314. Binary Tree Vertical Order Traversal Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column). If two nodes are in the same row and column, the order should be from left to right. Examples: 1. Given binary tree [3,9,20,null,null,15,7], 3 /\ / \ 9 20 /\ / \ 15 7 return its vertical order traversal as: [[9], [3,15], [20], [7]] 2. Given binary tree [3,9,8,4,0,1,7], 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7 return its vertical order traversal as: [[4], [9], [3,0,1], [8], [7]] 3. Given binary tree [3,9,8,4,0,1,7,null,null,null,2,5] (0's right child is 2 and 1's left child is 5), 3 /\ / \ 9 8 /\ /\ / \/ \ 4 01 7 /\ / \ 5 2 return its vertical order traversal as: [[4], [9,5], [3,0,1], [8,2], [7]] */
Added solution for VerticalOrderTraversal.java
leetcode/java/prob314BinaryTreeVerticalOrderTraversal/VerticalOrderTraversal.java
Added solution for VerticalOrderTraversal.java
<ide><path>eetcode/java/prob314BinaryTreeVerticalOrderTraversal/VerticalOrderTraversal.java <ide> return its vertical order traversal as: [[4], [9,5], [3,0,1], [8,2], [7]] <ide> <ide> */ <add> <add>import java.util.*; <add> <add>public class VerticalOrderTraversal { <add> <add> public class TreeNode { <add> int val; <add> TreeNode left, right; <add> <add> TreeNode(int x) { <add> val = x; <add> } <add> } <add> public List<List<Integer>> verticalOrder(TreeNode root) { <add> <add> List<List<Integer>> result = new ArrayList<>(); <add> if (root == null) return result; <add> <add> Map<Integer, List<Integer>> map = new HashMap<>(); // key will be column number and value will be the list of all elements on that column <add> Queue<TreeNode> queue = new LinkedList<>(); // queue will contain the tree nodes <add> Queue<Integer> columns = new LinkedList<>(); // columns will contain the columns of the tree <add> int minColumn = 0, maxColumn = 0; <add> <add> queue.add(root); <add> columns.add(0); // root is at column 0; <add> <add> while (!queue.isEmpty()) { <add> <add> TreeNode node = queue.poll(); <add> int col = columns.poll(); <add> <add> // if col has not been seen yet, we add it to map with value an empty list <add> if (!map.containsKey(col)) { <add> map.put(col, new ArrayList<>()); <add> } <add> // we add the value of current node to queue <add> map.get(col).add(node.val); <add> <add> // if node has a left (respectively right) child, add it to queue and add col-1 <add> // (respectively col+1) to columns. Then update minColumn and maxColumn <add> if (node.left != null) { <add> int nextLeftColumn = col-1; <add> queue.add(node.left); <add> columns.add(nextLeftColumn); <add> minColumn = Math.min(minColumn, nextLeftColumn); <add> } <add> if (node.right != null) { <add> int nextRightColumn = col + 1; <add> queue.add(node.right); <add> columns.add(nextRightColumn); <add> maxColumn = Math.max(maxColumn, nextRightColumn); <add> } <add> } <add> <add> // Iterate through keys of map and add the corresponding list values to result <add> for (int i = minColumn; i <= maxColumn; i++) { <add> result.add(map.get(i)); <add> } <add> <add> return result; <add> } <add>}
Java
agpl-3.0
e678a7d9c42339bae3a413d6655ffc58c761823d
0
zuowang/voltdb,VoltDB/voltdb,VoltDB/voltdb,zuowang/voltdb,migue/voltdb,wolffcm/voltdb,zuowang/voltdb,VoltDB/voltdb,kumarrus/voltdb,kobronson/cs-voltdb,creative-quant/voltdb,paulmartel/voltdb,ingted/voltdb,simonzhangsm/voltdb,ingted/voltdb,kobronson/cs-voltdb,kobronson/cs-voltdb,simonzhangsm/voltdb,kumarrus/voltdb,ingted/voltdb,kobronson/cs-voltdb,wolffcm/voltdb,deerwalk/voltdb,wolffcm/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,zuowang/voltdb,ingted/voltdb,kumarrus/voltdb,wolffcm/voltdb,creative-quant/voltdb,paulmartel/voltdb,VoltDB/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,paulmartel/voltdb,creative-quant/voltdb,kumarrus/voltdb,flybird119/voltdb,ingted/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,ingted/voltdb,kumarrus/voltdb,kobronson/cs-voltdb,deerwalk/voltdb,kumarrus/voltdb,creative-quant/voltdb,creative-quant/voltdb,migue/voltdb,kobronson/cs-voltdb,deerwalk/voltdb,creative-quant/voltdb,ingted/voltdb,migue/voltdb,kobronson/cs-voltdb,ingted/voltdb,zuowang/voltdb,flybird119/voltdb,paulmartel/voltdb,flybird119/voltdb,flybird119/voltdb,kobronson/cs-voltdb,deerwalk/voltdb,wolffcm/voltdb,migue/voltdb,wolffcm/voltdb,wolffcm/voltdb,deerwalk/voltdb,creative-quant/voltdb,flybird119/voltdb,flybird119/voltdb,deerwalk/voltdb,flybird119/voltdb,migue/voltdb,deerwalk/voltdb,migue/voltdb,kumarrus/voltdb,paulmartel/voltdb,creative-quant/voltdb,zuowang/voltdb,kumarrus/voltdb,VoltDB/voltdb,migue/voltdb,VoltDB/voltdb,paulmartel/voltdb,migue/voltdb,zuowang/voltdb,wolffcm/voltdb,zuowang/voltdb,flybird119/voltdb
/* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.utils; import java.io.*; import java.lang.StringBuilder; import java.util.List; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.Map; import java.util.Hashtable; import java.util.TreeSet; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.text.SimpleDateFormat; import java.math.BigDecimal; import java.net.URL; import java.nio.Buffer; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.NoConnectionsException; import org.voltdb.client.ProcCallException; import org.voltdb.VoltTable; import org.voltdb.VoltType; import jline.*; public class SQLCommand { // SQL Parsing private static final Pattern EscapedSingleQuote = Pattern.compile("''", Pattern.MULTILINE); private static final Pattern SingleLineComments = Pattern.compile("^\\s*(\\/\\/|--).*$", Pattern.MULTILINE); private static final Pattern Extract = Pattern.compile("'[^']*'", Pattern.MULTILINE); private static final Pattern AutoSplit = Pattern.compile("\\s(select|insert|update|delete|exec|execute)\\s", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern AutoSplitParameters = Pattern.compile("[\\s,]+", Pattern.MULTILINE); public static List<String> parseQuery(String query) { if (query == null) return null; String[] command = new String[] {"exec", "execute"}; String[] keyword = new String[] {"select", "insert", "update", "delete"}; for(int i = 0;i<command.length;i++) { for(int j = 0;j<command.length;j++) { Pattern r = Pattern.compile("\\s*(" + command[i].replace(" ","\\s+") + ")\\s+(" + keyword[j] + ")\\s*", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); query = r.matcher(query).replaceAll(" $1 #SQL_PARSER_STRING_KEYWORD#$2 "); } } query = SingleLineComments.matcher(query).replaceAll(""); query = EscapedSingleQuote.matcher(query).replaceAll("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)"); Matcher stringFragmentMatcher = Extract.matcher(query); ArrayList<String> stringFragments = new ArrayList<String>(); int i = 0; while(stringFragmentMatcher.find()) { stringFragments.add(stringFragmentMatcher.group()); query = stringFragmentMatcher.replaceFirst("#(SQL_PARSER_STRING_FRAGMENT#" + i + ")"); stringFragmentMatcher = Extract.matcher(query); i++; } query = AutoSplit.matcher(query).replaceAll(";$1 "); String[] sqlFragments = query.split("\\s*;+\\s*"); ArrayList<String> queries = new ArrayList<String>(); for(int j = 0;j<sqlFragments.length;j++) { sqlFragments[j] = sqlFragments[j].trim(); if (sqlFragments[j].length() != 0) { if(sqlFragments[j].indexOf("#(SQL_PARSER_STRING_FRAGMENT#") > -1) for(int k = 0;k<stringFragments.size();k++) sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_STRING_FRAGMENT#" + k + ")", stringFragments.get(k)); sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)", "''"); sqlFragments[j] = sqlFragments[j].replace("#SQL_PARSER_STRING_KEYWORD#",""); queries.add(sqlFragments[j]); } } return queries; } public static List<String> parseQueryProcedureCallParameters(String query) { if (query == null) return null; query = SingleLineComments.matcher(query).replaceAll(""); query = EscapedSingleQuote.matcher(query).replaceAll("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)"); Matcher stringFragmentMatcher = Extract.matcher(query); ArrayList<String> stringFragments = new ArrayList<String>(); int i = 0; while(stringFragmentMatcher.find()) { stringFragments.add(stringFragmentMatcher.group()); query = stringFragmentMatcher.replaceFirst("#(SQL_PARSER_STRING_FRAGMENT#" + i + ")"); stringFragmentMatcher = Extract.matcher(query); i++; } query = AutoSplitParameters.matcher(query).replaceAll(","); String[] sqlFragments = query.split("\\s*,+\\s*"); ArrayList<String> queries = new ArrayList<String>(); for(int j = 0;j<sqlFragments.length;j++) { sqlFragments[j] = sqlFragments[j].trim(); if (sqlFragments[j].length() != 0) { if(sqlFragments[j].indexOf("#(SQL_PARSER_STRING_FRAGMENT#") > -1) for(int k = 0;k<stringFragments.size();k++) sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_STRING_FRAGMENT#" + k + ")", stringFragments.get(k)); sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)", "''"); sqlFragments[j] = sqlFragments[j].trim(); queries.add(sqlFragments[j]); } } return queries; } // Command line interaction private static ConsoleReader Input = null; private static final Pattern GoToken = Pattern.compile("^\\s*go;*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ExitToken = Pattern.compile("^\\s*(exit|quit);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ListToken = Pattern.compile("^\\s*(list proc|list procedures);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ListTablesToken = Pattern.compile("^\\s*(list tables);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern SemicolonToken = Pattern.compile("^.*\\s*;+\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern RecallToken = Pattern.compile("^\\s*recall\\s*([^;]+)\\s*;*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern FileToken = Pattern.compile("^\\s*file\\s*['\"]*([^;'\"]+)['\"]*\\s*;*\\s*", Pattern.CASE_INSENSITIVE); private static int LineIndex = 1; private static List<String> Lines = new ArrayList<String>(); private static List<String> getQuery(boolean interactive) throws Exception { StringBuilder query = new StringBuilder(); boolean isRecall = false; String line = null; do { if (interactive) { if (isRecall) { isRecall = false; line = Input.readLine(""); } else line = Input.readLine((LineIndex++) + "> "); } else line = Input.readLine(); if (line == null) { if (query == null) return null; else return parseQuery(query.toString()); } // Process recall commands - ONLY in interactive mode if (interactive && RecallToken.matcher(line).matches()) { Matcher m = RecallToken.matcher(line); if (m.find()) { int recall = -1; try { recall = Integer.parseInt(m.group(1))-1; } catch(Exception x){} if (recall > -1 && recall < Lines.size()) { line = Lines.get(recall); Input.putString(line); out.flush(); isRecall = true; continue; } else System.out.printf("%s> Invalid RECALL reference: '" + m.group(1) + "'.\n", LineIndex-1); } else System.out.printf("%s> Invalid RECALL command: '" + line + "'.\n", LineIndex-1); } // Strip out invalid recall commands if (RecallToken.matcher(line).matches()) line = ""; // Queue up the line to the recall stack - ONLY in interactive mode if (interactive) Lines.add(line); // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) if (ExitToken.matcher(line).matches()) { if (interactive) return null; } // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) else if (ListToken.matcher(line).matches()) { if (interactive) { List<String> list = new LinkedList<String>(Procedures.keySet()); Collections.sort(list); int padding = 0; for(String procedure : list) if (padding < procedure.length()) padding = procedure.length(); padding++; String format = "%1$-" + padding + "s"; for(int i = 0;i<2;i++) { int j = 0; for(String procedure : list) { if (i == 0 && procedure.startsWith("@")) continue; else if (i == 1 && !procedure.startsWith("@")) continue; if (j == 0) { if (i == 0) System.out.println("\n--- User Procedures ----------------------------------------"); else System.out.println("\n--- System Procedures --------------------------------------"); } System.out.printf(format, procedure); System.out.print("\t"); int pidx = 0; for(String paramType : Procedures.get(procedure)) { if (pidx > 0) System.out.print(", "); System.out.print(paramType); pidx++; } System.out.print("\n"); j++; } } System.out.print("\n"); } } // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) else if (ListTablesToken.matcher(line).matches()) { if (interactive) { Object[] lists = GetTableList(); for(int i=0;i<3;i++) { if (i == 0) System.out.println("\n--- User Tables --------------------------------------------"); else if (i == 1) System.out.println("\n--- User Views ---------------------------------------------"); else System.out.println("\n--- User Export Streams ------------------------------------"); Iterator<String> list = ((TreeSet<String>)lists[i]).iterator(); while(list.hasNext()) System.out.println(list.next()); System.out.print("\n"); } System.out.print("\n"); } } // GO commands - ONLY in interactive mode, close batch and parse for execution else if (GoToken.matcher(line).matches()) { if (interactive) return parseQuery(query.toString().trim()); } // FILE command - include the content of the file into the query else if (FileToken.matcher(line).matches()) { boolean executeImmediate = false; if (interactive && SemicolonToken.matcher(line).matches()) executeImmediate = true; Matcher m = FileToken.matcher(line); if (m.find()) { line = readScriptFile(m.group(1)); if (line == null) { if (!interactive) return null; } else { query.append(line); query.append("\n"); if (executeImmediate) return parseQuery(query.toString().trim()); } } else { System.err.print("Invalid FILE command: '" + line + "'."); // In non-interactive mode, a failure aborts the entire batch // In interactive mode, we'll just ignore that specific failed command. if (!interactive) return null; } } else { query.append(line); query.append("\n"); if (interactive && SemicolonToken.matcher(line).matches()) return parseQuery(query.toString().trim()); } line = null; } while(true); } private static String readScriptFile(String filePath) { try { StringBuilder query = new StringBuilder(); BufferedReader script = new BufferedReader(new FileReader(filePath)); String line; while ((line = script.readLine()) != null) { // Strip out RECALL, EXIT and GO commands if (!(RecallToken.matcher(line).matches() || ExitToken.matcher(line).matches() || GoToken.matcher(line).matches())) { // Recursively process FILE commands, any failure will cause a recursive failure if (FileToken.matcher(line).matches()) { Matcher m = FileToken.matcher(line); if (m.find()) { line = readScriptFile(m.group(1)); if (line == null) return null; query.append(line); query.append("\n"); } else { System.err.print("Invalid FILE command: '" + line + "'."); return null; } } else { query.append(line); query.append("\n"); } } } script.close(); return query.toString().trim(); } catch(FileNotFoundException e) { System.err.println("Script file '" + filePath + "' could not be found."); return null; } catch(Exception x) { System.err.println(x.getMessage()); return null; } } // Query Execution private static final Pattern ExecuteCall = Pattern.compile("^(exec|execute) ", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern StripCRLF = Pattern.compile("[\r\n]+", Pattern.MULTILINE); private static final Pattern IsNull = Pattern.compile("null", Pattern.CASE_INSENSITIVE); private static final SimpleDateFormat DateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private static final Pattern Unquote = Pattern.compile("^'|'$", Pattern.MULTILINE); private static void executeQuery(String query) throws Exception { if (ExecuteCall.matcher(query).find()) { query = ExecuteCall.matcher(query).replaceFirst(""); List<String> params = parseQueryProcedureCallParameters(query); String procedure = params.remove(0); if (!Procedures.containsKey(procedure)) throw new Exception("Undefined procedure: " + procedure); List<String> paramTypes = Procedures.get(procedure); if (params.size() != paramTypes.size()) throw new Exception("Invalid parameter count for procedure: " + procedure + "(expected: " + paramTypes.size() + ", received: " + params.size() + ")"); Object[] objectParams = new Object[params.size()]; if (procedure.equals("@SnapshotDelete")) { objectParams[0] = new String[] { Unquote.matcher(params.get(0)).replaceAll("").replace("''","'") }; objectParams[1] = new String[] { Unquote.matcher(params.get(1)).replaceAll("").replace("''","'") }; } else { for(int i = 0;i<params.size();i++) { String paramType = paramTypes.get(i); String param = params.get(i); if (paramType.equals("bit")) { if(param.equals("yes") || param.equals("true") || param.equals("1")) objectParams[i] = (byte)1; else objectParams[i] = (byte)0; } else if (paramType.equals("tinyint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_TINYINT; else objectParams[i] = Byte.parseByte(param); } else if (paramType.equals("smallint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_SMALLINT; else objectParams[i] = Short.parseShort(param); } else if (paramType.equals("int") || paramType.equals("integer")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_INTEGER; else objectParams[i] = Integer.parseInt(param); } else if (paramType.equals("bigint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_BIGINT; else objectParams[i] = Long.parseLong(param); } else if (paramType.equals("float")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_FLOAT; else objectParams[i] = Double.parseDouble(param); } else if (paramType.equals("varchar")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_STRING_OR_VARBINARY; else objectParams[i] = Unquote.matcher(param).replaceAll("").replace("''","'"); } else if (paramType.equals("decimal")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_DECIMAL; else objectParams[i] = new BigDecimal(param); } else if (paramType.equals("timestamp")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_TIMESTAMP; else objectParams[i] = DateParser.parse(param); } else if (paramType.equals("statisticscomponent")) { if (!StatisticsComponents.contains(param.toUpperCase())) throw new Exception("Invalid Statistics Component: " + param); objectParams[i] = param.toUpperCase(); } else if (paramType.equals("sysinfoselector")) { if (!SysInfoSelectors.contains(param.toUpperCase())) throw new Exception("Invalid SysInfo Selector: " + param); objectParams[i] = param.toUpperCase(); } else if (paramType.equals("metadataselector")) { if (!MetaDataSelectors.contains(param.toUpperCase())) throw new Exception("Invalid Meta-Data Selector: " + param); objectParams[i] = param.toUpperCase(); } else if (paramType.equals("varbinary")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_STRING_OR_VARBINARY; else objectParams[i] = hexStringToByteArray(Unquote.matcher(param).replaceAll("").replace("''","'")); } else throw new Exception("Unsupported Data Type: " + paramType); } } if (procedure.equals("@UpdateApplicationCatalog")) { printResponse(VoltDB.updateApplicationCatalog(new File((String) objectParams[0]), new File((String) objectParams[1]))); } else { printResponse(VoltDB.callProcedure(procedure, objectParams)); } } else { query = StripCRLF.matcher(query).replaceAll(" "); printResponse(VoltDB.callProcedure("@AdHoc", query)); } return; } private static String byteArrayToHexString(byte[] data) { StringBuffer hexString = new StringBuffer(); for (int i=0;i<data.length;i++) { String hex = Integer.toHexString(0xFF & data[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } private static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); return data; } // Output generation private static String OutputFormat = "fixed"; private static boolean OutputShowMetadata = true; public static String paddingString(String s, int n, char c, boolean paddingLeft) { if (s == null) return s; int add = n - s.length(); if(add <= 0) return s; StringBuffer str = new StringBuffer(s); char[] ch = new char[add]; Arrays.fill(ch, c); if(paddingLeft) str.insert(0, ch); else str.append(ch); return str.toString(); } private static boolean isUpdateResult(VoltTable table) { return ((table.getColumnName(0).length() == 0 || table.getColumnName(0).equals("modified_tuples"))&& table.getRowCount() == 1 && table.getColumnCount() == 1 && table.getColumnType(0) == VoltType.BIGINT); } private static void printResponse(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) throw new Exception("Execution Error: " + response.getStatusString()); if (OutputFormat.equals("fixed")) { for(VoltTable t : response.getResults()) { if (isUpdateResult(t)) { if(OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.fetchRow(0).getLong(0)); continue; } int columnCount = t.getColumnCount(); int[] padding = new int[columnCount]; String[] fmt = new String[columnCount]; for (int i = 0; i < columnCount; i++) padding[i] = OutputShowMetadata ? t.getColumnName(i).length() : 0; t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { Object v = t.get(i, t.getColumnType(i)); if (v == null) v = "null"; int l = t.getColumnType(i) == VoltType.VARBINARY ? ((byte[])v).length*2 : v.toString().length(); if (padding[i] < l) padding[i] = l; } } for (int i = 0; i < columnCount; i++) { padding[i] += 1; fmt[i] = "%1$" + ((t.getColumnType(i) == VoltType.STRING || t.getColumnType(i) == VoltType.TIMESTAMP || t.getColumnType(i) == VoltType.VARBINARY) ? "-" : "#") + padding[i] + "s"; } if (OutputShowMetadata) { for (int i = 0; i < columnCount; i++) { System.out.printf("%1$-" + padding[i] + "s", t.getColumnName(i)); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); for (int i = 0; i < columnCount; i++) { System.out.print(paddingString("", padding[i], '-', false)); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); } t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { Object v = t.get(i, t.getColumnType(i)); if (v == null) v = "null"; else if (t.getColumnType(i) == VoltType.VARBINARY) v = byteArrayToHexString((byte[])v); else v = v.toString(); System.out.printf(fmt[i], v); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); } if (OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.getRowCount()); } } else { String separator = OutputFormat.equals("csv") ? "," : "\t"; for(VoltTable t : response.getResults()) { if (isUpdateResult(t)) { if(OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.fetchRow(0).getLong(0)); continue; } int columnCount = t.getColumnCount(); if (OutputShowMetadata) { for (int i = 0; i < columnCount; i++) { if (i > 0) System.out.print(separator); System.out.print(t.getColumnName(i)); } System.out.print("\n"); } t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { if (i > 0) System.out.print(separator); Object v = t.get(i, t.getColumnType(i)); if (v == null) v = "null"; else if (t.getColumnType(i) == VoltType.VARBINARY) v = byteArrayToHexString((byte[])v); else v = v.toString(); System.out.print(v); } System.out.print("\n"); } if (OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.getRowCount()); } } } // VoltDB connection support private static Client VoltDB; private static final List<String> Types = Arrays.asList("tinyint","smallint","integer","bigint","float","decimal","varchar","timestamp","varbinary"); private static final List<String> StatisticsComponents = Arrays.asList("INDEX","INITIATOR","IOSTATS","MANAGEMENT","MEMORY","PROCEDURE","TABLE","PARTITIONCOUNT","STARVATION","LIVECLIENTS"); private static final List<String> SysInfoSelectors = Arrays.asList("OVERVIEW","DEPLOYMENT"); private static final List<String> MetaDataSelectors = Arrays.asList("TABLES", "COLUMNS", "INDEXINFO", "PRIMARYKEYS", "PROCEDURES", "PROCEDURECOLUMNS"); private static Map<String,List<String>> Procedures = new Hashtable<String,List<String>>(); private static void loadSystemProcedures() { Procedures.put("@Pause", new ArrayList<String>()); Procedures.put("@Quiesce", new ArrayList<String>()); Procedures.put("@Resume", new ArrayList<String>()); Procedures.put("@Shutdown", new ArrayList<String>()); Procedures.put("@SnapshotDelete", Arrays.asList("varchar", "varchar")); Procedures.put("@SnapshotRestore", Arrays.asList("varchar", "varchar")); Procedures.put("@SnapshotSave", Arrays.asList("varchar", "varchar", "bit")); Procedures.put("@SnapshotScan", Arrays.asList("varchar")); Procedures.put("@Statistics", Arrays.asList("statisticscomponent", "bit")); Procedures.put("@SystemCatalog", Arrays.asList("metadataselector")); Procedures.put("@SystemInformation", Arrays.asList("sysinfoselector")); Procedures.put("@UpdateApplicationCatalog", Arrays.asList("varchar", "varchar")); Procedures.put("@UpdateLogging", Arrays.asList("varchar")); } public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { final Client client = ClientFactory.createClient(config); for (String server : servers) client.createConnection(server.trim(), port); return client; } // General application support private static void printUsage(String msg) { System.out.print(msg); System.out.println("\n"); printUsage(-1); } private static void printUsage(int exitCode) { System.out.println( "Usage: SQLCommand --help\n" + " or SQLCommand [--servers=comma_separated_server_list]\n" + " [--port=port_number]\n" + " [--user=user]\n" + " [--password=password]\n" + " [--output-format=(fixed|csv|tab)]\n" + " [--output-skip-metadata]\n" + "\n" + "[--servers=comma_separated_server_list]\n" + " List of servers to connect to.\n" + " Default: localhost.\n" + "\n" + "[--port=port_number]\n" + " Client port to connect to on cluster nodes.\n" + " Default: 21212.\n" + "\n" + "[--user=user]\n" + " Name of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--password=password]\n" + " Password of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--output-format=(fixed|csv|tab)]\n" + " Format of returned resultset data (Fixed-width, CSV or Tab-delimited).\n" + " Default: fixed.\n" + "\n" + "[--output-skip-metadata]\n" + " Removes metadata information such as column headers and row count from\n" + " produced output.\n" + "\n" + "[--debug]\n" + " Causes the utility to print out stack traces for all exceptions.\n" ); System.exit(exitCode); } public static void printHelp() { try { byte[] bytes = new byte[1024 * 4]; InputStream is = SQLCommand.class.getResourceAsStream("SQLCommandReadme.txt"); while (is.available() > 0) { is.read(bytes, 0, bytes.length); System.out.write(bytes); } } catch(Exception x) { System.err.println(x.getMessage()); System.exit(-1); } } private static Object[] GetTableList() throws Exception { VoltTable tableData = VoltDB.callProcedure("@SystemCatalog", "TABLES").getResults()[0]; TreeSet<String> tables = new TreeSet<String>(); TreeSet<String> exports = new TreeSet<String>(); TreeSet<String> views = new TreeSet<String>(); for(int i = 0; i < tableData.getRowCount(); i++) { String tableName = tableData.fetchRow(i).getString("TABLE_NAME"); String tableType = tableData.fetchRow(i).getString("TABLE_TYPE"); if (tableType.equalsIgnoreCase("EXPORT")) { exports.add(tableName); } else if (tableType.equalsIgnoreCase("VIEW")) { views.add(tableName); } else { tables.add(tableName); } } return new Object[] {tables, views, exports}; } private static void loadStoredProcedures(Map<String,List<String>> procedures) { VoltTable procs = null; VoltTable params = null; try { procs = VoltDB.callProcedure("@SystemCatalog", "PROCEDURES").getResults()[0]; params = VoltDB.callProcedure("@SystemCatalog", "PROCEDURECOLUMNS").getResults()[0]; } catch (NoConnectionsException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (ProcCallException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } while (procs.advanceRow()) { procedures.put(procs.getString("PROCEDURE_NAME"), new ArrayList<String>()); } while (params.advanceRow()) { List<String> this_params = procedures.get(params.getString("PROCEDURE_NAME")); this_params.add((int)params.getLong("ORDINAL_POSITION") - 1, params.getString("TYPE_NAME").toLowerCase()); } } private static InputStream in = null; private static Writer out = null; // Application entry point public static void main(String args[]) { boolean debug = false; try { // Initialize parameter defaults String serverList = "localhost"; int port = 21212; String user = ""; String password = ""; // Parse out parameters for(int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("--servers=")) serverList = arg.split("=")[1]; else if (arg.startsWith("--port=")) port = Integer.valueOf(arg.split("=")[1]); else if (arg.startsWith("--user=")) user = arg.split("=")[1]; else if (arg.startsWith("--password=")) password = arg.split("=")[1]; else if (arg.startsWith("--output-format=")) { if (Pattern.compile("(fixed|csv|tab)", Pattern.CASE_INSENSITIVE).matcher(arg.split("=")[1].toLowerCase()).matches()) OutputFormat = arg.split("=")[1].toLowerCase(); else printUsage("Invalid value for --output-format"); } else if (arg.equals("--output-skip-metadata")) OutputShowMetadata = false; else if (arg.equals("--debug")) debug = true; else if (arg.equals("--help")) { printHelp(); printUsage(0); } else if (arg.equals("--usage")) printUsage(0); else printUsage("Invalid Parameter: " + arg); } // Split server list String[] servers = serverList.split(","); // Load system procedures loadSystemProcedures(); // Don't ask... Java is such a crippled language! DateParser.setLenient(true); // Create connection VoltDB = getClient(new ClientConfig(user, password), servers,port); // Load user stored procs loadStoredProcedures(Procedures); List<String> queries = null; in = new FileInputStream(FileDescriptor.in); out = new PrintWriter(new OutputStreamWriter(System.out, System.getProperty("jline.WindowsTerminal.output.encoding", System.getProperty("file.encoding")))); Input = new ConsoleReader(in, out); Input.setBellEnabled(false); Input.addCompletor(new SimpleCompletor(new String[] {"select", "update", "insert", "delete", "exec", "file", "recall", "SELECT", "UPDATE", "INSERT", "DELETE", "EXEC", "FILE", "RECALL" })); // If Standard input comes loaded with data, run in non-interactive mode if (System.in.available() > 0) { queries = getQuery(false); if (queries == null) System.exit(0); else for(int i = 0;i<queries.size();i++) executeQuery(queries.get(i)); } else { // Print out welcome message System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port); while((queries = getQuery(true)) != null) { try { for(int i = 0;i<queries.size();i++) executeQuery(queries.get(i)); } catch(Exception x) { System.err.println(x.getMessage()); if (debug) x.printStackTrace(System.err); } } } } catch (Exception e) { System.err.println(e.getMessage()); if (debug) e.printStackTrace(System.err); System.exit(-1); } finally { try { VoltDB.close(); } catch(Exception _) {} } } }
src/frontend/org/voltdb/utils/SQLCommand.java
/* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * VoltDB is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * VoltDB is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.utils; import java.io.*; import java.lang.StringBuilder; import java.util.List; import java.util.ArrayList; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.Map; import java.util.Hashtable; import java.util.TreeSet; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.text.SimpleDateFormat; import java.math.BigDecimal; import java.net.URL; import java.nio.Buffer; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.NoConnectionsException; import org.voltdb.client.ProcCallException; import org.voltdb.VoltTable; import org.voltdb.VoltType; import jline.*; public class SQLCommand { // SQL Parsing private static final Pattern EscapedSingleQuote = Pattern.compile("''", Pattern.MULTILINE); private static final Pattern SingleLineComments = Pattern.compile("^\\s*(\\/\\/|--).*$", Pattern.MULTILINE); private static final Pattern Extract = Pattern.compile("'[^']*'", Pattern.MULTILINE); private static final Pattern AutoSplit = Pattern.compile("\\s(select|insert|update|delete|exec|execute)\\s", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern AutoSplitParameters = Pattern.compile("[\\s,]+", Pattern.MULTILINE); public static List<String> parseQuery(String query) { if (query == null) return null; String[] command = new String[] {"exec", "execute"}; String[] keyword = new String[] {"select", "insert", "update", "delete"}; for(int i = 0;i<command.length;i++) { for(int j = 0;j<command.length;j++) { Pattern r = Pattern.compile("\\s*(" + command[i].replace(" ","\\s+") + ")\\s+(" + keyword[j] + ")\\s*", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); query = r.matcher(query).replaceAll(" $1 #SQL_PARSER_STRING_KEYWORD#$2 "); } } query = SingleLineComments.matcher(query).replaceAll(""); query = EscapedSingleQuote.matcher(query).replaceAll("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)"); Matcher stringFragmentMatcher = Extract.matcher(query); ArrayList<String> stringFragments = new ArrayList<String>(); int i = 0; while(stringFragmentMatcher.find()) { stringFragments.add(stringFragmentMatcher.group()); query = stringFragmentMatcher.replaceFirst("#(SQL_PARSER_STRING_FRAGMENT#" + i + ")"); stringFragmentMatcher = Extract.matcher(query); i++; } query = AutoSplit.matcher(query).replaceAll(";$1 "); String[] sqlFragments = query.split("\\s*;+\\s*"); ArrayList<String> queries = new ArrayList<String>(); for(int j = 0;j<sqlFragments.length;j++) { sqlFragments[j] = sqlFragments[j].trim(); if (sqlFragments[j].length() != 0) { if(sqlFragments[j].indexOf("#(SQL_PARSER_STRING_FRAGMENT#") > -1) for(int k = 0;k<stringFragments.size();k++) sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_STRING_FRAGMENT#" + k + ")", stringFragments.get(k)); sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)", "''"); sqlFragments[j] = sqlFragments[j].replace("#SQL_PARSER_STRING_KEYWORD#",""); queries.add(sqlFragments[j]); } } return queries; } public static List<String> parseQueryProcedureCallParameters(String query) { if (query == null) return null; query = SingleLineComments.matcher(query).replaceAll(""); query = EscapedSingleQuote.matcher(query).replaceAll("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)"); Matcher stringFragmentMatcher = Extract.matcher(query); ArrayList<String> stringFragments = new ArrayList<String>(); int i = 0; while(stringFragmentMatcher.find()) { stringFragments.add(stringFragmentMatcher.group()); query = stringFragmentMatcher.replaceFirst("#(SQL_PARSER_STRING_FRAGMENT#" + i + ")"); stringFragmentMatcher = Extract.matcher(query); i++; } query = AutoSplitParameters.matcher(query).replaceAll(","); String[] sqlFragments = query.split("\\s*,+\\s*"); ArrayList<String> queries = new ArrayList<String>(); for(int j = 0;j<sqlFragments.length;j++) { sqlFragments[j] = sqlFragments[j].trim(); if (sqlFragments[j].length() != 0) { if(sqlFragments[j].indexOf("#(SQL_PARSER_STRING_FRAGMENT#") > -1) for(int k = 0;k<stringFragments.size();k++) sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_STRING_FRAGMENT#" + k + ")", stringFragments.get(k)); sqlFragments[j] = sqlFragments[j].replace("#(SQL_PARSER_ESCAPE_SINGLE_QUOTE)", "''"); sqlFragments[j] = sqlFragments[j].trim(); queries.add(sqlFragments[j]); } } return queries; } // Command line interaction private static ConsoleReader Input = null; private static final Pattern GoToken = Pattern.compile("^\\s*go;*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ExitToken = Pattern.compile("^\\s*(exit|quit);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ListToken = Pattern.compile("^\\s*(list proc|list procedures);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern ListTablesToken = Pattern.compile("^\\s*(list tables);*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern SemicolonToken = Pattern.compile("^.*\\s*;+\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern RecallToken = Pattern.compile("^\\s*recall\\s*([^;]+)\\s*;*\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern FileToken = Pattern.compile("^\\s*file\\s*['\"]*([^;'\"]+)['\"]*\\s*;*\\s*", Pattern.CASE_INSENSITIVE); private static int LineIndex = 1; private static List<String> Lines = new ArrayList<String>(); private static List<String> getQuery(boolean interactive) throws Exception { StringBuilder query = new StringBuilder(); boolean isRecall = false; String line = null; do { if (interactive) { if (isRecall) { isRecall = false; line = Input.readLine(""); } else line = Input.readLine((LineIndex++) + "> "); } else line = Input.readLine(); if (line == null) { if (query == null) return null; else return parseQuery(query.toString()); } // Process recall commands - ONLY in interactive mode if (interactive && RecallToken.matcher(line).matches()) { Matcher m = RecallToken.matcher(line); if (m.find()) { int recall = -1; try { recall = Integer.parseInt(m.group(1))-1; } catch(Exception x){} if (recall > -1 && recall < Lines.size()) { line = Lines.get(recall); Input.putString(line); out.flush(); isRecall = true; continue; } else System.out.printf("%s> Invalid RECALL reference: '" + m.group(1) + "'.\n", LineIndex-1); } else System.out.printf("%s> Invalid RECALL command: '" + line + "'.\n", LineIndex-1); } // Strip out invalid recall commands if (RecallToken.matcher(line).matches()) line = ""; // Queue up the line to the recall stack - ONLY in interactive mode if (interactive) Lines.add(line); // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) if (ExitToken.matcher(line).matches()) { if (interactive) return null; } // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) else if (ListToken.matcher(line).matches()) { if (interactive) { List<String> list = new LinkedList<String>(Procedures.keySet()); Collections.sort(list); int padding = 0; for(String procedure : list) if (padding < procedure.length()) padding = procedure.length(); padding++; String format = "%1$-" + padding + "s"; for(int i = 0;i<2;i++) { int j = 0; for(String procedure : list) { if (i == 0 && procedure.startsWith("@")) continue; else if (i == 1 && !procedure.startsWith("@")) continue; if (j == 0) { if (i == 0) System.out.println("\n--- User Procedures ----------------------------------------"); else System.out.println("\n--- System Procedures --------------------------------------"); } System.out.printf(format, procedure); System.out.print("\t"); int pidx = 0; for(String paramType : Procedures.get(procedure)) { if (pidx > 0) System.out.print(", "); System.out.print(paramType); pidx++; } System.out.print("\n"); j++; } } System.out.print("\n"); } } // EXIT command - ONLY in interactive mode, exit immediately (without running any queued statements) else if (ListTablesToken.matcher(line).matches()) { if (interactive) { Object[] lists = GetTableList(); for(int i=0;i<3;i++) { if (i == 0) System.out.println("\n--- User Tables --------------------------------------------"); else if (i == 1) System.out.println("\n--- User Views ---------------------------------------------"); else System.out.println("\n--- User Export Streams ------------------------------------"); Iterator<String> list = ((TreeSet<String>)lists[i]).iterator(); while(list.hasNext()) System.out.println(list.next()); System.out.print("\n"); } System.out.print("\n"); } } // GO commands - ONLY in interactive mode, close batch and parse for execution else if (GoToken.matcher(line).matches()) { if (interactive) return parseQuery(query.toString().trim()); } // FILE command - include the content of the file into the query else if (FileToken.matcher(line).matches()) { boolean executeImmediate = false; if (interactive && SemicolonToken.matcher(line).matches()) executeImmediate = true; Matcher m = FileToken.matcher(line); if (m.find()) { line = readScriptFile(m.group(1)); if (line == null) { if (!interactive) return null; } else { query.append(line); query.append("\n"); if (executeImmediate) return parseQuery(query.toString().trim()); } } else { System.err.print("Invalid FILE command: '" + line + "'."); // In non-interactive mode, a failure aborts the entire batch // In interactive mode, we'll just ignore that specific failed command. if (!interactive) return null; } } else { query.append(line); query.append("\n"); if (interactive && SemicolonToken.matcher(line).matches()) return parseQuery(query.toString().trim()); } line = null; } while(true); } private static String readScriptFile(String filePath) { try { StringBuilder query = new StringBuilder(); BufferedReader script = new BufferedReader(new FileReader(filePath)); String line; while ((line = script.readLine()) != null) { // Strip out RECALL, EXIT and GO commands if (!(RecallToken.matcher(line).matches() || ExitToken.matcher(line).matches() || GoToken.matcher(line).matches())) { // Recursively process FILE commands, any failure will cause a recursive failure if (FileToken.matcher(line).matches()) { Matcher m = FileToken.matcher(line); if (m.find()) { line = readScriptFile(m.group(1)); if (line == null) return null; query.append(line); query.append("\n"); } else { System.err.print("Invalid FILE command: '" + line + "'."); return null; } } else { query.append(line); query.append("\n"); } } } script.close(); return query.toString().trim(); } catch(FileNotFoundException e) { System.err.println("Script file '" + filePath + "' could not be found."); return null; } catch(Exception x) { System.err.println(x.getMessage()); return null; } } // Query Execution private static final Pattern ExecuteCall = Pattern.compile("^(exec|execute) ", Pattern.MULTILINE + Pattern.CASE_INSENSITIVE); private static final Pattern StripCRLF = Pattern.compile("[\r\n]+", Pattern.MULTILINE); private static final Pattern IsNull = Pattern.compile("null", Pattern.CASE_INSENSITIVE); private static final SimpleDateFormat DateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); private static final Pattern Unquote = Pattern.compile("^'|'$", Pattern.MULTILINE); private static void executeQuery(String query) throws Exception { if (ExecuteCall.matcher(query).find()) { query = ExecuteCall.matcher(query).replaceFirst(""); List<String> params = parseQueryProcedureCallParameters(query); String procedure = params.remove(0); if (!Procedures.containsKey(procedure)) throw new Exception("Undefined procedure: " + procedure); List<String> paramTypes = Procedures.get(procedure); if (params.size() != paramTypes.size()) throw new Exception("Invalid parameter count for procedure: " + procedure + "(expected: " + paramTypes.size() + ", received: " + params.size() + ")"); Object[] objectParams = new Object[params.size()]; if (procedure.equals("@SnapshotDelete")) { objectParams[0] = new String[] { Unquote.matcher(params.get(0)).replaceAll("").replace("''","'") }; objectParams[1] = new String[] { Unquote.matcher(params.get(1)).replaceAll("").replace("''","'") }; } else { for(int i = 0;i<params.size();i++) { String paramType = paramTypes.get(i); String param = params.get(i); if (paramType.equals("bit")) { if(param.equals("yes") || param.equals("true") || param.equals("1")) objectParams[i] = (byte)1; else objectParams[i] = (byte)0; } else if (paramType.equals("tinyint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_TINYINT; else objectParams[i] = Byte.parseByte(param); } else if (paramType.equals("smallint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_SMALLINT; else objectParams[i] = Short.parseShort(param); } else if (paramType.equals("int") || paramType.equals("integer")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_INTEGER; else objectParams[i] = Integer.parseInt(param); } else if (paramType.equals("bigint")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_BIGINT; else objectParams[i] = Long.parseLong(param); } else if (paramType.equals("float")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_FLOAT; else objectParams[i] = Double.parseDouble(param); } else if (paramType.equals("varchar")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_STRING_OR_VARBINARY; else objectParams[i] = Unquote.matcher(param).replaceAll("").replace("''","'"); } else if (paramType.equals("decimal")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_DECIMAL; else objectParams[i] = new BigDecimal(param); } else if (paramType.equals("timestamp")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_TIMESTAMP; else objectParams[i] = DateParser.parse(param); } else if (paramType.equals("statisticscomponent")) { if (!StatisticsComponents.contains(param.toUpperCase())) throw new Exception("Invalid Statistics Component: " + param); objectParams[i] = param.toUpperCase(); } else if (paramType.equals("sysinfoselector")) { if (!SysInfoSelectors.contains(param.toUpperCase())) throw new Exception("Invalid SysInfo Selector: " + param); objectParams[i] = param.toUpperCase(); } else if (paramType.equals("metadataselector")) { if (!MetaDataSelectors.contains(param.toUpperCase())) throw new Exception("Invalid Meta-Data Selector: " + param); objectParams[i] = param.toUpperCase(); } else if (paramType.equals("varbinary")) { if (IsNull.matcher(param).matches()) objectParams[i] = VoltType.NULL_STRING_OR_VARBINARY; else objectParams[i] = hexStringToByteArray(Unquote.matcher(param).replaceAll("").replace("''","'")); } else throw new Exception("Unsupported Data Type: " + paramType); } } printResponse(VoltDB.callProcedure(procedure, objectParams)); } else { query = StripCRLF.matcher(query).replaceAll(" "); printResponse(VoltDB.callProcedure("@AdHoc", query)); } return; } private static String byteArrayToHexString(byte[] data) { StringBuffer hexString = new StringBuffer(); for (int i=0;i<data.length;i++) { String hex = Integer.toHexString(0xFF & data[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } private static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) data[i/2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); return data; } // Output generation private static String OutputFormat = "fixed"; private static boolean OutputShowMetadata = true; public static String paddingString(String s, int n, char c, boolean paddingLeft) { if (s == null) return s; int add = n - s.length(); if(add <= 0) return s; StringBuffer str = new StringBuffer(s); char[] ch = new char[add]; Arrays.fill(ch, c); if(paddingLeft) str.insert(0, ch); else str.append(ch); return str.toString(); } private static boolean isUpdateResult(VoltTable table) { return ((table.getColumnName(0).length() == 0 || table.getColumnName(0).equals("modified_tuples"))&& table.getRowCount() == 1 && table.getColumnCount() == 1 && table.getColumnType(0) == VoltType.BIGINT); } private static void printResponse(ClientResponse response) throws Exception { if (response.getStatus() != ClientResponse.SUCCESS) throw new Exception("Execution Error: " + response.getStatusString()); if (OutputFormat.equals("fixed")) { for(VoltTable t : response.getResults()) { if (isUpdateResult(t)) { if(OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.fetchRow(0).getLong(0)); continue; } int columnCount = t.getColumnCount(); int[] padding = new int[columnCount]; String[] fmt = new String[columnCount]; for (int i = 0; i < columnCount; i++) padding[i] = OutputShowMetadata ? t.getColumnName(i).length() : 0; t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { Object v = t.get(i, t.getColumnType(i)); if (v == null) v = "null"; int l = t.getColumnType(i) == VoltType.VARBINARY ? ((byte[])v).length*2 : v.toString().length(); if (padding[i] < l) padding[i] = l; } } for (int i = 0; i < columnCount; i++) { padding[i] += 1; fmt[i] = "%1$" + ((t.getColumnType(i) == VoltType.STRING || t.getColumnType(i) == VoltType.TIMESTAMP || t.getColumnType(i) == VoltType.VARBINARY) ? "-" : "#") + padding[i] + "s"; } if (OutputShowMetadata) { for (int i = 0; i < columnCount; i++) { System.out.printf("%1$-" + padding[i] + "s", t.getColumnName(i)); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); for (int i = 0; i < columnCount; i++) { System.out.print(paddingString("", padding[i], '-', false)); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); } t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { Object v = t.get(i, t.getColumnType(i)); if (v == null) v = "null"; else if (t.getColumnType(i) == VoltType.VARBINARY) v = byteArrayToHexString((byte[])v); else v = v.toString(); System.out.printf(fmt[i], v); if (i < columnCount - 1) System.out.print(" "); } System.out.print("\n"); } if (OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.getRowCount()); } } else { String separator = OutputFormat.equals("csv") ? "," : "\t"; for(VoltTable t : response.getResults()) { if (isUpdateResult(t)) { if(OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.fetchRow(0).getLong(0)); continue; } int columnCount = t.getColumnCount(); if (OutputShowMetadata) { for (int i = 0; i < columnCount; i++) { if (i > 0) System.out.print(separator); System.out.print(t.getColumnName(i)); } System.out.print("\n"); } t.resetRowPosition(); while(t.advanceRow()) { for (int i = 0; i < columnCount; i++) { if (i > 0) System.out.print(separator); Object v = t.get(i, t.getColumnType(i)); if (v == null) v = "null"; else if (t.getColumnType(i) == VoltType.VARBINARY) v = byteArrayToHexString((byte[])v); else v = v.toString(); System.out.print(v); } System.out.print("\n"); } if (OutputShowMetadata) System.out.printf("\n\n(%d row(s) affected)\n", t.getRowCount()); } } } // VoltDB connection support private static Client VoltDB; private static final List<String> Types = Arrays.asList("tinyint","smallint","integer","bigint","float","decimal","varchar","timestamp","varbinary"); private static final List<String> StatisticsComponents = Arrays.asList("INDEX","INITIATOR","IOSTATS","MANAGEMENT","MEMORY","PROCEDURE","TABLE","PARTITIONCOUNT","STARVATION","LIVECLIENTS"); private static final List<String> SysInfoSelectors = Arrays.asList("OVERVIEW","DEPLOYMENT"); private static final List<String> MetaDataSelectors = Arrays.asList("TABLES", "COLUMNS", "INDEXINFO", "PRIMARYKEYS", "PROCEDURES", "PROCEDURECOLUMNS"); private static Map<String,List<String>> Procedures = new Hashtable<String,List<String>>(); private static void loadSystemProcedures() { Procedures.put("@Pause", new ArrayList<String>()); Procedures.put("@Quiesce", new ArrayList<String>()); Procedures.put("@Resume", new ArrayList<String>()); Procedures.put("@Shutdown", new ArrayList<String>()); Procedures.put("@SnapshotDelete", Arrays.asList("varchar", "varchar")); Procedures.put("@SnapshotRestore", Arrays.asList("varchar", "varchar")); Procedures.put("@SnapshotSave", Arrays.asList("varchar", "varchar", "bit")); Procedures.put("@SnapshotScan", Arrays.asList("varchar")); Procedures.put("@Statistics", Arrays.asList("statisticscomponent", "bit")); Procedures.put("@SystemCatalog", Arrays.asList("metadataselector")); Procedures.put("@SystemInformation", Arrays.asList("sysinfoselector")); Procedures.put("@UpdateApplicationCatalog", Arrays.asList("varchar", "varchar")); Procedures.put("@UpdateLogging", Arrays.asList("varchar")); } public static Client getClient(ClientConfig config, String[] servers, int port) throws Exception { final Client client = ClientFactory.createClient(config); for (String server : servers) client.createConnection(server.trim(), port); return client; } // General application support private static void printUsage(String msg) { System.out.print(msg); System.out.println("\n"); printUsage(-1); } private static void printUsage(int exitCode) { System.out.println( "Usage: SQLCommand --help\n" + " or SQLCommand [--servers=comma_separated_server_list]\n" + " [--port=port_number]\n" + " [--user=user]\n" + " [--password=password]\n" + " [--output-format=(fixed|csv|tab)]\n" + " [--output-skip-metadata]\n" + "\n" + "[--servers=comma_separated_server_list]\n" + " List of servers to connect to.\n" + " Default: localhost.\n" + "\n" + "[--port=port_number]\n" + " Client port to connect to on cluster nodes.\n" + " Default: 21212.\n" + "\n" + "[--user=user]\n" + " Name of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--password=password]\n" + " Password of the user for database login.\n" + " Default: (not defined - connection made without credentials).\n" + "\n" + "[--output-format=(fixed|csv|tab)]\n" + " Format of returned resultset data (Fixed-width, CSV or Tab-delimited).\n" + " Default: fixed.\n" + "\n" + "[--output-skip-metadata]\n" + " Removes metadata information such as column headers and row count from\n" + " produced output.\n" + "\n" + "[--debug]\n" + " Causes the utility to print out stack traces for all exceptions.\n" ); System.exit(exitCode); } public static void printHelp() { try { byte[] bytes = new byte[1024 * 4]; InputStream is = SQLCommand.class.getResourceAsStream("SQLCommandReadme.txt"); while (is.available() > 0) { is.read(bytes, 0, bytes.length); System.out.write(bytes); } } catch(Exception x) { System.err.println(x.getMessage()); System.exit(-1); } } private static Object[] GetTableList() throws Exception { VoltTable tableData = VoltDB.callProcedure("@SystemCatalog", "TABLES").getResults()[0]; TreeSet<String> tables = new TreeSet<String>(); TreeSet<String> exports = new TreeSet<String>(); TreeSet<String> views = new TreeSet<String>(); for(int i = 0; i < tableData.getRowCount(); i++) { String tableName = tableData.fetchRow(i).getString("TABLE_NAME"); String tableType = tableData.fetchRow(i).getString("TABLE_TYPE"); if (tableType.equalsIgnoreCase("EXPORT")) { exports.add(tableName); } else if (tableType.equalsIgnoreCase("VIEW")) { views.add(tableName); } else { tables.add(tableName); } } return new Object[] {tables, views, exports}; } private static void loadStoredProcedures(Map<String,List<String>> procedures) { VoltTable procs = null; VoltTable params = null; try { procs = VoltDB.callProcedure("@SystemCatalog", "PROCEDURES").getResults()[0]; params = VoltDB.callProcedure("@SystemCatalog", "PROCEDURECOLUMNS").getResults()[0]; } catch (NoConnectionsException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } catch (ProcCallException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } while (procs.advanceRow()) { procedures.put(procs.getString("PROCEDURE_NAME"), new ArrayList<String>()); } while (params.advanceRow()) { List<String> this_params = procedures.get(params.getString("PROCEDURE_NAME")); this_params.add((int)params.getLong("ORDINAL_POSITION") - 1, params.getString("TYPE_NAME").toLowerCase()); } } private static InputStream in = null; private static Writer out = null; // Application entry point public static void main(String args[]) { boolean debug = false; try { // Initialize parameter defaults String serverList = "localhost"; int port = 21212; String user = ""; String password = ""; // Parse out parameters for(int i = 0; i < args.length; i++) { String arg = args[i]; if (arg.startsWith("--servers=")) serverList = arg.split("=")[1]; else if (arg.startsWith("--port=")) port = Integer.valueOf(arg.split("=")[1]); else if (arg.startsWith("--user=")) user = arg.split("=")[1]; else if (arg.startsWith("--password=")) password = arg.split("=")[1]; else if (arg.startsWith("--output-format=")) { if (Pattern.compile("(fixed|csv|tab)", Pattern.CASE_INSENSITIVE).matcher(arg.split("=")[1].toLowerCase()).matches()) OutputFormat = arg.split("=")[1].toLowerCase(); else printUsage("Invalid value for --output-format"); } else if (arg.equals("--output-skip-metadata")) OutputShowMetadata = false; else if (arg.equals("--debug")) debug = true; else if (arg.equals("--help")) { printHelp(); printUsage(0); } else if (arg.equals("--usage")) printUsage(0); else printUsage("Invalid Parameter: " + arg); } // Split server list String[] servers = serverList.split(","); // Load system procedures loadSystemProcedures(); // Don't ask... Java is such a crippled language! DateParser.setLenient(true); // Create connection VoltDB = getClient(new ClientConfig(user, password), servers,port); // Load user stored procs loadStoredProcedures(Procedures); List<String> queries = null; in = new FileInputStream(FileDescriptor.in); out = new PrintWriter(new OutputStreamWriter(System.out, System.getProperty("jline.WindowsTerminal.output.encoding", System.getProperty("file.encoding")))); Input = new ConsoleReader(in, out); Input.setBellEnabled(false); Input.addCompletor(new SimpleCompletor(new String[] {"select", "update", "insert", "delete", "exec", "file", "recall", "SELECT", "UPDATE", "INSERT", "DELETE", "EXEC", "FILE", "RECALL" })); // If Standard input comes loaded with data, run in non-interactive mode if (System.in.available() > 0) { queries = getQuery(false); if (queries == null) System.exit(0); else for(int i = 0;i<queries.size();i++) executeQuery(queries.get(i)); } else { // Print out welcome message System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port); while((queries = getQuery(true)) != null) { try { for(int i = 0;i<queries.size();i++) executeQuery(queries.get(i)); } catch(Exception x) { System.err.println(x.getMessage()); if (debug) x.printStackTrace(System.err); } } } } catch (Exception e) { System.err.println(e.getMessage()); if (debug) e.printStackTrace(System.err); System.exit(-1); } finally { try { VoltDB.close(); } catch(Exception _) {} } } }
ENG-1763 SQLcmd can once again update the catalog.
src/frontend/org/voltdb/utils/SQLCommand.java
ENG-1763
<ide><path>rc/frontend/org/voltdb/utils/SQLCommand.java <ide> throw new Exception("Unsupported Data Type: " + paramType); <ide> } <ide> } <del> printResponse(VoltDB.callProcedure(procedure, objectParams)); <add> if (procedure.equals("@UpdateApplicationCatalog")) <add> { <add> printResponse(VoltDB.updateApplicationCatalog(new File((String) objectParams[0]), <add> new File((String) objectParams[1]))); <add> } <add> else <add> { <add> printResponse(VoltDB.callProcedure(procedure, objectParams)); <add> } <ide> } <ide> else <ide> {
Java
mit
89ead2949c26f7f06ad61eeda098592c73c0bb27
0
CS2103JAN2017-W10-B1/main,CS2103JAN2017-W10-B1/main
package seedu.address.model.task; import seedu.address.model.tag.Tag; /** * A read-only immutable interface for a Task in the TaskManager. * Implementations should guarantee: details are present and not null, field values are validated. */ public interface ReadOnlyTask { public enum FinishProperty { FINISHED, UNFINISHED } public enum EventProperty { EVENT, NON_EVENT } Name getName(); TaskDate getDate(); TaskTime getTime(); Tag getTag(); Description getDescription(); Venue getVenue(); Priority getPriority(); boolean isFavorite(); boolean isFinished(); String getFavoriteText(); String getFinishedText(); boolean isEvent(); //@@author A0147984L /** * Returns true if both have the same state. (interfaces cannot override equals) */ default boolean isSameStateAs(ReadOnlyTask other) { if (other.isFinished() == true || this.isFinished() == true) { return false; } // finished task are always treated as different return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && checkEqual(this.getName(), other.getName()) && checkEqual(this.getDate(), other.getDate()) && checkEqual(this.getTime(), other.getTime()) && checkEqual(this.getTag(), other.getTag())); // state checks here onwards } //@@ author A0147996E /** * For comparing two tasks in GUItests, to check if the list view matches desired list view. */ default boolean isSameCardAs(ReadOnlyTask other) { return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && other.getName().equals(this.getName()) && other.getDate().equals(this.getDate()) && other.getTime().equals(this.getTime()) && other.getTag().equals(this.getTag())) && other.getFinished().equals(this.getFinished()); } //@@ author A0143409J /* * Get the FinishProperty instead of boolean */ FinishProperty getFinished(); EventProperty getEventProperty(); default boolean checkEqual(TaskField mine, TaskField other) { if (mine == null) { return other == null; } else { return mine.equals(other); } } /** * Formats the person as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getName()); if (getDate() != null) { builder.append(" Due Date:"); builder.append(getDate()); } if (getTime() != null) { builder.append(" Time:"); builder.append(getTime()); } if (getDescription() != null) { builder.append(" Description:"); builder.append(getDescription()); } if (getTag() != null) { builder.append(" List:"); builder.append(getTag()); } if (getVenue() != null) { builder.append(" Venue:"); builder.append(getVenue()); } assert getPriority() != null; builder.append(" Priority:"); builder.append(getPriority()); if (isFavorite()) { builder.append(" favorite"); } if (isFinished()) { builder.append(" finished"); } return builder.toString(); } }
src/main/java/seedu/address/model/task/ReadOnlyTask.java
package seedu.address.model.task; import seedu.address.model.tag.Tag; /** * A read-only immutable interface for a Task in the TaskManager. * Implementations should guarantee: details are present and not null, field values are validated. */ public interface ReadOnlyTask { public enum FinishProperty { FINISHED, UNFINISHED } public enum EventProperty { EVENT, NON_EVENT } Name getName(); TaskDate getDate(); TaskTime getTime(); Tag getTag(); Description getDescription(); Venue getVenue(); Priority getPriority(); boolean isFavorite(); boolean isFinished(); String getFavoriteText(); String getFinishedText(); boolean isEvent(); //@@author A0147984L /** * Returns true if both have the same state. (interfaces cannot override equals) */ default boolean isSameStateAs(ReadOnlyTask other) { if (other.isFinished() == true || this.isFinished() == true) { return false; } // finished task are always treated as different return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && checkEqual(this.getName(), other.getName()) && checkEqual(this.getDate(), other.getDate()) && checkEqual(this.getTime(), other.getTime()) && checkEqual(this.getTag(), other.getTag())); // state checks here onwards } <<<<<<< HEAD //@@ author A0147996E /** * For comparing two tasks in GUItests, to check if the list view matches desired list view. */ default boolean isSameCardAs(ReadOnlyTask other) { return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && other.getName().equals(this.getName()) && other.getDate().equals(this.getDate()) && other.getTime().equals(this.getTime()) && other.getTag().equals(this.getTag())) && other.getFinished().equals(this.getFinished()); } ======= >>>>>>> origin/master //@@ author A0143409J /* * Get the FinishProperty instead of boolean */ FinishProperty getFinished(); EventProperty getEventProperty(); default boolean checkEqual(TaskField mine, TaskField other) { if (mine == null) { return other == null; } else { return mine.equals(other); } } /** * Formats the person as text, showing all contact details. */ default String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getName()); if (getDate() != null) { builder.append(" Due Date:"); builder.append(getDate()); } if (getTime() != null) { builder.append(" Time:"); builder.append(getTime()); } if (getDescription() != null) { builder.append(" Description:"); builder.append(getDescription()); } if (getTag() != null) { builder.append(" List:"); builder.append(getTag()); } if (getVenue() != null) { builder.append(" Venue:"); builder.append(getVenue()); } assert getPriority() != null; builder.append(" Priority:"); builder.append(getPriority()); if (isFavorite()) { builder.append(" favorite"); } if (isFinished()) { builder.append(" finished"); } return builder.toString(); } }
[V0.4] Resolve conflicts
src/main/java/seedu/address/model/task/ReadOnlyTask.java
[V0.4] Resolve conflicts
<ide><path>rc/main/java/seedu/address/model/task/ReadOnlyTask.java <ide> && checkEqual(this.getTime(), other.getTime()) <ide> && checkEqual(this.getTag(), other.getTag())); // state checks here onwards <ide> } <del><<<<<<< HEAD <del> <ide> //@@ author A0147996E <ide> /** <ide> * For comparing two tasks in GUItests, to check if the list view matches desired list view. <ide> && other.getTag().equals(this.getTag())) <ide> && other.getFinished().equals(this.getFinished()); <ide> } <del>======= <ide> <del>>>>>>>> origin/master <ide> //@@ author A0143409J <ide> /* <ide> * Get the FinishProperty instead of boolean
Java
bsd-3-clause
182c07dc46b5023f6d22df2d89ab9025428f7402
0
boundlessgeo/GeoGig,markles/GeoGit,annacarol/GeoGig,annacarol/GeoGig,boundlessgeo/GeoGig,markles/GeoGit,markles/GeoGit,boundlessgeo/GeoGig,markles/GeoGit,markles/GeoGit,annacarol/GeoGig
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.geoserver; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.Serializable; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; import org.geogit.api.GeoGIT; import org.geogit.api.NodeRef; import org.geogit.api.RevCommit; import org.geogit.api.plumbing.FindTreeChild; import org.geogit.api.plumbing.LsTreeOp; import org.geogit.api.plumbing.ResolveGeogitDir; import org.geogit.api.porcelain.CommitOp; import org.geogit.api.porcelain.LogOp; import org.geogit.di.GeogitModule; import org.geogit.di.caching.CachingModule; import org.geogit.geotools.data.GeoGitDataStore; import org.geogit.geotools.data.GeoGitDataStoreFactory; import org.geogit.storage.bdbje.JEStorageModule; import org.geogit.test.integration.RepositoryTestCase; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFactory; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.ProjectionPolicy; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.data.test.SystemTestData; import org.geoserver.wfs.WFSTestSupport; import org.geotools.data.DataAccess; import org.geotools.data.FeatureSource; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.opengis.feature.Feature; import org.opengis.feature.type.FeatureType; import org.opengis.filter.Filter; import org.w3c.dom.Document; import com.google.common.collect.ImmutableList; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.util.Modules; public class WFSIntegrationTest extends WFSTestSupport { /** HTTP_GEOGIT_ORG */ private static final String NAMESPACE = "http://geogit.org"; private static final String WORKSPACE = "geogit"; private static final String STORE = "geogitstore"; private static RepositoryTestCase helper; @Before public void revert() throws Exception { // revertLayer(CiteTestData.ROAD_SEGMENTS); } @AfterClass public static void oneTimeTearDown() throws Exception { if (helper != null) { helper.tearDown(); helper.repositoryTempFolder.delete(); } } @Override protected void setUpTestData(SystemTestData testData) throws Exception { // oevrride to avoid creating all the default feature types but call testData.setUp() only // instead testData.setUp(); } @Override protected void setUpNamespaces(Map<String, String> namespaces) { namespaces.put(WORKSPACE, NAMESPACE); } @Override protected void setUpInternal(SystemTestData testData) throws Exception { helper = new RepositoryTestCase() { @Override protected Injector createInjector() { return Guice.createInjector(Modules.override(new GeogitModule(), new CachingModule()).with(new JEStorageModule())); } @Override protected void setUpInternal() throws Exception { configureGeogitDataStore(); } }; helper.repositoryTempFolder.create(); helper.setUp(); } private void configureGeogitDataStore() throws Exception { helper.insertAndAdd(helper.lines1); helper.getGeogit().command(CommitOp.class).call(); Catalog catalog = getCatalog(); CatalogFactory factory = catalog.getFactory(); NamespaceInfo ns = factory.createNamespace(); ns.setPrefix(WORKSPACE); ns.setURI(NAMESPACE); catalog.add(ns); WorkspaceInfo ws = factory.createWorkspace(); ws.setName(ns.getName()); catalog.add(ws); DataStoreInfo ds = factory.createDataStore(); ds.setEnabled(true); ds.setDescription("Test Geogit DataStore"); ds.setName(STORE); ds.setType(GeoGitDataStoreFactory.DISPLAY_NAME); ds.setWorkspace(ws); Map<String, Serializable> connParams = ds.getConnectionParameters(); URL geogitDir = helper.getGeogit().command(ResolveGeogitDir.class).call(); File repositoryUrl = new File(geogitDir.toURI()).getParentFile(); assertTrue(repositoryUrl.exists() && repositoryUrl.isDirectory()); connParams.put(GeoGitDataStoreFactory.REPOSITORY.key, repositoryUrl); connParams.put(GeoGitDataStoreFactory.DEFAULT_NAMESPACE.key, ns.getURI()); catalog.add(ds); DataStoreInfo dsInfo = catalog.getDataStoreByName(WORKSPACE, STORE); assertNotNull(dsInfo); assertEquals(GeoGitDataStoreFactory.DISPLAY_NAME, dsInfo.getType()); DataAccess<? extends FeatureType, ? extends Feature> dataStore = dsInfo.getDataStore(null); assertNotNull(dataStore); assertTrue(dataStore instanceof GeoGitDataStore); FeatureTypeInfo fti = factory.createFeatureType(); fti.setNamespace(ns); fti.setCatalog(catalog); fti.setStore(dsInfo); fti.setSRS("EPSG:4326"); fti.setName("Lines"); fti.setAdvertised(true); fti.setEnabled(true); fti.setFilter(Filter.INCLUDE); fti.setProjectionPolicy(ProjectionPolicy.FORCE_DECLARED); ReferencedEnvelope bounds = new ReferencedEnvelope(-180, 180, -90, 90, CRS.decode("EPSG:4326")); fti.setNativeBoundingBox(bounds); fti.setLatLonBoundingBox(bounds); catalog.add(fti); fti = catalog.getFeatureType(fti.getId()); FeatureSource<? extends FeatureType, ? extends Feature> featureSource; featureSource = fti.getFeatureSource(null, null); assertNotNull(featureSource); } @Test public void testInsert() throws Exception { Document dom = insert(); assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); assertEquals("1", getFirstElementByTagName(dom, "wfs:totalInserted").getFirstChild() .getNodeValue()); dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines&srsName=EPSG:4326&"); // print(dom); assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName()); assertEquals(2, dom.getElementsByTagName("geogit:Lines").getLength()); } private Document insert() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\" "// + " xmlns:wfs=\"http://www.opengis.net/wfs\" "// + " xmlns:gml=\"http://www.opengis.net/gml\" " // + " xmlns:geogit=\"" + NAMESPACE + "\">"// + "<wfs:Insert>"// + "<geogit:Lines gml:id=\"Lines.1000\">"// + " <geogit:sp>StringProp new</geogit:sp>"// + " <geogit:ip>999</geogit:ip>"// + " <geogit:pp>"// + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>1.0 1.0 2.0 2.0</gml:posList>"// + " </gml:LineString>"// + " </geogit:pp>"// + "</geogit:Lines>"// + "</wfs:Insert>"// + "</wfs:Transaction>"; Document dom = postAsDOM("wfs", xml); return dom; } @Test public void testUpdate() throws Exception { Document dom = update(); assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); assertEquals("1", getFirstElementByTagName(dom, "wfs:totalUpdated").getFirstChild() .getNodeValue()); dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines" + "&" + "cql_filter=ip%3D1000"); assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName()); assertEquals(1, dom.getElementsByTagName("geogit:Lines").getLength()); } private Document update() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\""// + " xmlns:geogit=\"" + NAMESPACE + "\""// + " xmlns:ogc=\"http://www.opengis.net/ogc\""// + " xmlns:gml=\"http://www.opengis.net/gml\""// + " xmlns:wfs=\"http://www.opengis.net/wfs\">"// + " <wfs:Update typeName=\"geogit:Lines\">"// + " <wfs:Property>"// + " <wfs:Name>geogit:pp</wfs:Name>"// + " <wfs:Value>" + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>1 2 3 4</gml:posList>"// + " </gml:LineString>"// + " </wfs:Value>"// + " </wfs:Property>"// + " <ogc:Filter>"// + " <ogc:PropertyIsEqualTo>"// + " <ogc:PropertyName>ip</ogc:PropertyName>"// + " <ogc:Literal>1000</ogc:Literal>"// + " </ogc:PropertyIsEqualTo>"// + " </ogc:Filter>"// + " </wfs:Update>"// + "</wfs:Transaction>"; Document dom = postAsDOM("wfs", xml); return dom; } /** * Test case to expose issue https://github.com/opengeo/GeoGit/issues/310 * "Editing Features changes the feature type" * * @see #testUpdateDoesntChangeFeatureType() */ @Test public void testInsertDoesntChangeFeatureType() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\" "// + " xmlns:wfs=\"http://www.opengis.net/wfs\" "// + " xmlns:gml=\"http://www.opengis.net/gml\" " // + " xmlns:geogit=\"" + NAMESPACE + "\">"// + "<wfs:Insert>"// + "<geogit:Lines gml:id=\"Lines.1000\">"// + " <geogit:sp>added</geogit:sp>"// + " <geogit:ip>7</geogit:ip>"// + " <geogit:pp>"// + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>1 2 3 4</gml:posList>"// + " </gml:LineString>"// + " </geogit:pp>"// + "</geogit:Lines>"// + "</wfs:Insert>"// + "</wfs:Transaction>"; GeoGIT geogit = helper.getGeogit(); final NodeRef initialTypeTreeRef = geogit.command(FindTreeChild.class) .setChildPath("Lines").call().get(); assertFalse(initialTypeTreeRef.getMetadataId().isNull()); Document dom = postAsDOM("wfs", xml); try { assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); } catch (AssertionError e) { print(dom); throw e; } try { assertEquals("1", getFirstElementByTagName(dom, "wfs:totalInserted").getFirstChild() .getNodeValue()); } catch (AssertionError e) { print(dom); throw e; } final NodeRef finalTypeTreeRef = geogit.command(FindTreeChild.class).setChildPath("Lines") .call().get(); assertFalse(initialTypeTreeRef.equals(finalTypeTreeRef)); assertFalse(finalTypeTreeRef.getMetadataId().isNull()); assertEquals("Feature type tree metadataId shouuldn't change upon edits", initialTypeTreeRef.getMetadataId(), finalTypeTreeRef.getMetadataId()); Iterator<NodeRef> featureRefs = geogit.command(LsTreeOp.class).setReference("Lines").call(); while (featureRefs.hasNext()) { NodeRef ref = featureRefs.next(); assertEquals(finalTypeTreeRef.getMetadataId(), ref.getMetadataId()); assertFalse(ref.toString(), ref.getNode().getMetadataId().isPresent()); } } /** * Test case to expose issue https://github.com/opengeo/GeoGit/issues/310 * "Editing Features changes the feature type" * * @see #testInsertDoesntChangeFeatureType() */ @Test public void testUpdateDoesntChangeFeatureType() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\""// + " xmlns:geogit=\"" + NAMESPACE + "\""// + " xmlns:ogc=\"http://www.opengis.net/ogc\""// + " xmlns:gml=\"http://www.opengis.net/gml\""// + " xmlns:wfs=\"http://www.opengis.net/wfs\">"// + " <wfs:Update typeName=\"geogit:Lines\">"// + " <wfs:Property>"// + " <wfs:Name>geogit:pp</wfs:Name>"// + " <wfs:Value>" + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>3 4 5 6</gml:posList>"// + " </gml:LineString>"// + " </wfs:Value>"// + " </wfs:Property>"// + " <ogc:Filter>"// + " <ogc:PropertyIsEqualTo>"// + " <ogc:PropertyName>ip</ogc:PropertyName>"// + " <ogc:Literal>1000</ogc:Literal>"// + " </ogc:PropertyIsEqualTo>"// + " </ogc:Filter>"// + " </wfs:Update>"// + "</wfs:Transaction>"; GeoGIT geogit = helper.getGeogit(); final NodeRef initialTypeTreeRef = geogit.command(FindTreeChild.class) .setChildPath("Lines").call().get(); assertFalse(initialTypeTreeRef.getMetadataId().isNull()); Document dom = postAsDOM("wfs", xml); assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); assertEquals("1", getFirstElementByTagName(dom, "wfs:totalUpdated").getFirstChild() .getNodeValue()); final NodeRef finalTypeTreeRef = geogit.command(FindTreeChild.class).setChildPath("Lines") .call().get(); assertFalse(initialTypeTreeRef.equals(finalTypeTreeRef)); assertFalse(finalTypeTreeRef.getMetadataId().isNull()); assertEquals("Feature type tree metadataId shouuldn't change upon edits", initialTypeTreeRef.getMetadataId(), finalTypeTreeRef.getMetadataId()); Iterator<NodeRef> featureRefs = geogit.command(LsTreeOp.class).setReference("Lines").call(); while (featureRefs.hasNext()) { NodeRef ref = featureRefs.next(); assertEquals(finalTypeTreeRef.getMetadataId(), ref.getMetadataId()); assertFalse(ref.toString(), ref.getNode().getMetadataId().isPresent()); } } @Test public void testCommitsSurviveShutDown() throws Exception { RepositoryTestCase helper = WFSIntegrationTest.helper; GeoGIT geogit = helper.getGeogit(); insert(); update(); List<RevCommit> expected = ImmutableList.copyOf(geogit.command(LogOp.class).call()); File repoDir = helper.repositoryTempFolder.getRoot(); // shut down server super.doTearDownClass(); geogit = new GeoGIT(repoDir); try { assertNotNull(geogit.getRepository()); List<RevCommit> actual = ImmutableList.copyOf(geogit.command(LogOp.class).call()); assertEquals(expected, actual); } finally { geogit.close(); } } }
src/web/geoserver/src/test/java/org/geogit/geoserver/WFSIntegrationTest.java
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.geoserver; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.Serializable; import java.net.URL; import java.util.Iterator; import java.util.Map; import org.geogit.api.GeoGIT; import org.geogit.api.NodeRef; import org.geogit.api.plumbing.FindTreeChild; import org.geogit.api.plumbing.LsTreeOp; import org.geogit.api.plumbing.ResolveGeogitDir; import org.geogit.api.porcelain.CommitOp; import org.geogit.di.GeogitModule; import org.geogit.di.caching.CachingModule; import org.geogit.geotools.data.GeoGitDataStore; import org.geogit.geotools.data.GeoGitDataStoreFactory; import org.geogit.storage.bdbje.JEStorageModule; import org.geogit.test.integration.RepositoryTestCase; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFactory; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.ProjectionPolicy; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.data.test.SystemTestData; import org.geoserver.wfs.WFSTestSupport; import org.geotools.data.DataAccess; import org.geotools.data.FeatureSource; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.junit.AfterClass; import org.junit.Before; import org.junit.Test; import org.opengis.feature.Feature; import org.opengis.feature.type.FeatureType; import org.opengis.filter.Filter; import org.w3c.dom.Document; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.util.Modules; public class WFSIntegrationTest extends WFSTestSupport { /** HTTP_GEOGIT_ORG */ private static final String NAMESPACE = "http://geogit.org"; private static final String WORKSPACE = "geogit"; private static final String STORE = "geogitstore"; private static RepositoryTestCase helper; @Before public void revert() throws Exception { // revertLayer(CiteTestData.ROAD_SEGMENTS); } @AfterClass public static void oneTimeTearDown() throws Exception { if (helper != null) { helper.tearDown(); helper.repositoryTempFolder.delete(); } } @Override protected void setUpTestData(SystemTestData testData) throws Exception { // oevrride to avoid creating all the default feature types but call testData.setUp() only // instead testData.setUp(); } @Override protected void setUpNamespaces(Map<String, String> namespaces) { namespaces.put(WORKSPACE, NAMESPACE); } @Override protected void setUpInternal(SystemTestData testData) throws Exception { helper = new RepositoryTestCase() { @Override protected Injector createInjector() { return Guice.createInjector(Modules.override(new GeogitModule(), new CachingModule()).with(new JEStorageModule())); } @Override protected void setUpInternal() throws Exception { configureGeogitDataStore(); } }; helper.repositoryTempFolder.create(); helper.setUp(); } private void configureGeogitDataStore() throws Exception { helper.insertAndAdd(helper.lines1); helper.getGeogit().command(CommitOp.class).call(); Catalog catalog = getCatalog(); CatalogFactory factory = catalog.getFactory(); NamespaceInfo ns = factory.createNamespace(); ns.setPrefix(WORKSPACE); ns.setURI(NAMESPACE); catalog.add(ns); WorkspaceInfo ws = factory.createWorkspace(); ws.setName(ns.getName()); catalog.add(ws); DataStoreInfo ds = factory.createDataStore(); ds.setEnabled(true); ds.setDescription("Test Geogit DataStore"); ds.setName(STORE); ds.setType(GeoGitDataStoreFactory.DISPLAY_NAME); ds.setWorkspace(ws); Map<String, Serializable> connParams = ds.getConnectionParameters(); URL geogitDir = helper.getGeogit().command(ResolveGeogitDir.class).call(); File repositoryUrl = new File(geogitDir.toURI()).getParentFile(); assertTrue(repositoryUrl.exists() && repositoryUrl.isDirectory()); connParams.put(GeoGitDataStoreFactory.REPOSITORY.key, repositoryUrl); connParams.put(GeoGitDataStoreFactory.DEFAULT_NAMESPACE.key, ns.getURI()); catalog.add(ds); DataStoreInfo dsInfo = catalog.getDataStoreByName(WORKSPACE, STORE); assertNotNull(dsInfo); assertEquals(GeoGitDataStoreFactory.DISPLAY_NAME, dsInfo.getType()); DataAccess<? extends FeatureType, ? extends Feature> dataStore = dsInfo.getDataStore(null); assertNotNull(dataStore); assertTrue(dataStore instanceof GeoGitDataStore); FeatureTypeInfo fti = factory.createFeatureType(); fti.setNamespace(ns); fti.setCatalog(catalog); fti.setStore(dsInfo); fti.setSRS("EPSG:4326"); fti.setName("Lines"); fti.setAdvertised(true); fti.setEnabled(true); fti.setFilter(Filter.INCLUDE); fti.setProjectionPolicy(ProjectionPolicy.FORCE_DECLARED); ReferencedEnvelope bounds = new ReferencedEnvelope(-180, 180, -90, 90, CRS.decode("EPSG:4326")); fti.setNativeBoundingBox(bounds); fti.setLatLonBoundingBox(bounds); catalog.add(fti); fti = catalog.getFeatureType(fti.getId()); FeatureSource<? extends FeatureType, ? extends Feature> featureSource; featureSource = fti.getFeatureSource(null, null); assertNotNull(featureSource); } @Test public void testInsert() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\" "// + " xmlns:wfs=\"http://www.opengis.net/wfs\" "// + " xmlns:gml=\"http://www.opengis.net/gml\" " // + " xmlns:geogit=\"" + NAMESPACE + "\">"// + "<wfs:Insert>"// + "<geogit:Lines gml:id=\"Lines.1000\">"// + " <geogit:sp>StringProp new</geogit:sp>"// + " <geogit:ip>999</geogit:ip>"// + " <geogit:pp>"// + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>1.0 1.0 2.0 2.0</gml:posList>"// + " </gml:LineString>"// + " </geogit:pp>"// + "</geogit:Lines>"// + "</wfs:Insert>"// + "</wfs:Transaction>"; Document dom = postAsDOM("wfs", xml); assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); assertEquals("1", getFirstElementByTagName(dom, "wfs:totalInserted").getFirstChild() .getNodeValue()); dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines&srsName=EPSG:4326&"); // print(dom); assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName()); assertEquals(2, dom.getElementsByTagName("geogit:Lines").getLength()); } @Test public void testUpdate() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\""// + " xmlns:geogit=\"" + NAMESPACE + "\""// + " xmlns:ogc=\"http://www.opengis.net/ogc\""// + " xmlns:gml=\"http://www.opengis.net/gml\""// + " xmlns:wfs=\"http://www.opengis.net/wfs\">"// + " <wfs:Update typeName=\"geogit:Lines\">"// + " <wfs:Property>"// + " <wfs:Name>geogit:pp</wfs:Name>"// + " <wfs:Value>" + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>1 2 3 4</gml:posList>"// + " </gml:LineString>"// + " </wfs:Value>"// + " </wfs:Property>"// + " <ogc:Filter>"// + " <ogc:PropertyIsEqualTo>"// + " <ogc:PropertyName>ip</ogc:PropertyName>"// + " <ogc:Literal>1000</ogc:Literal>"// + " </ogc:PropertyIsEqualTo>"// + " </ogc:Filter>"// + " </wfs:Update>"// + "</wfs:Transaction>"; Document dom = postAsDOM("wfs", xml); assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); assertEquals("1", getFirstElementByTagName(dom, "wfs:totalUpdated").getFirstChild() .getNodeValue()); dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines" + "&" + "cql_filter=ip%3D1000"); assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName()); assertEquals(1, dom.getElementsByTagName("geogit:Lines").getLength()); } /** * Test case to expose issue https://github.com/opengeo/GeoGit/issues/310 * "Editing Features changes the feature type" * * @see #testUpdateDoesntChangeFeatureType() */ @Test public void testInsertDoesntChangeFeatureType() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\" "// + " xmlns:wfs=\"http://www.opengis.net/wfs\" "// + " xmlns:gml=\"http://www.opengis.net/gml\" " // + " xmlns:geogit=\"" + NAMESPACE + "\">"// + "<wfs:Insert>"// + "<geogit:Lines gml:id=\"Lines.1000\">"// + " <geogit:sp>added</geogit:sp>"// + " <geogit:ip>7</geogit:ip>"// + " <geogit:pp>"// + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>1 2 3 4</gml:posList>"// + " </gml:LineString>"// + " </geogit:pp>"// + "</geogit:Lines>"// + "</wfs:Insert>"// + "</wfs:Transaction>"; GeoGIT geogit = helper.getGeogit(); final NodeRef initialTypeTreeRef = geogit.command(FindTreeChild.class) .setChildPath("Lines").call().get(); assertFalse(initialTypeTreeRef.getMetadataId().isNull()); Document dom = postAsDOM("wfs", xml); try { assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); } catch (AssertionError e) { print(dom); throw e; } try { assertEquals("1", getFirstElementByTagName(dom, "wfs:totalInserted").getFirstChild() .getNodeValue()); } catch (AssertionError e) { print(dom); throw e; } final NodeRef finalTypeTreeRef = geogit.command(FindTreeChild.class).setChildPath("Lines") .call().get(); assertFalse(initialTypeTreeRef.equals(finalTypeTreeRef)); assertFalse(finalTypeTreeRef.getMetadataId().isNull()); assertEquals("Feature type tree metadataId shouuldn't change upon edits", initialTypeTreeRef.getMetadataId(), finalTypeTreeRef.getMetadataId()); Iterator<NodeRef> featureRefs = geogit.command(LsTreeOp.class).setReference("Lines").call(); while (featureRefs.hasNext()) { NodeRef ref = featureRefs.next(); assertEquals(finalTypeTreeRef.getMetadataId(), ref.getMetadataId()); assertFalse(ref.toString(), ref.getNode().getMetadataId().isPresent()); } } /** * Test case to expose issue https://github.com/opengeo/GeoGit/issues/310 * "Editing Features changes the feature type" * * @see #testInsertDoesntChangeFeatureType() */ @Test public void testUpdateDoesntChangeFeatureType() throws Exception { String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\""// + " xmlns:geogit=\"" + NAMESPACE + "\""// + " xmlns:ogc=\"http://www.opengis.net/ogc\""// + " xmlns:gml=\"http://www.opengis.net/gml\""// + " xmlns:wfs=\"http://www.opengis.net/wfs\">"// + " <wfs:Update typeName=\"geogit:Lines\">"// + " <wfs:Property>"// + " <wfs:Name>geogit:pp</wfs:Name>"// + " <wfs:Value>" + " <gml:LineString srsDimension=\"2\" srsName=\"EPSG:4326\">"// + " <gml:posList>3 4 5 6</gml:posList>"// + " </gml:LineString>"// + " </wfs:Value>"// + " </wfs:Property>"// + " <ogc:Filter>"// + " <ogc:PropertyIsEqualTo>"// + " <ogc:PropertyName>ip</ogc:PropertyName>"// + " <ogc:Literal>1000</ogc:Literal>"// + " </ogc:PropertyIsEqualTo>"// + " </ogc:Filter>"// + " </wfs:Update>"// + "</wfs:Transaction>"; GeoGIT geogit = helper.getGeogit(); final NodeRef initialTypeTreeRef = geogit.command(FindTreeChild.class) .setChildPath("Lines").call().get(); assertFalse(initialTypeTreeRef.getMetadataId().isNull()); Document dom = postAsDOM("wfs", xml); assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); assertEquals("1", getFirstElementByTagName(dom, "wfs:totalUpdated").getFirstChild() .getNodeValue()); final NodeRef finalTypeTreeRef = geogit.command(FindTreeChild.class).setChildPath("Lines") .call().get(); assertFalse(initialTypeTreeRef.equals(finalTypeTreeRef)); assertFalse(finalTypeTreeRef.getMetadataId().isNull()); assertEquals("Feature type tree metadataId shouuldn't change upon edits", initialTypeTreeRef.getMetadataId(), finalTypeTreeRef.getMetadataId()); Iterator<NodeRef> featureRefs = geogit.command(LsTreeOp.class).setReference("Lines").call(); while (featureRefs.hasNext()) { NodeRef ref = featureRefs.next(); assertEquals(finalTypeTreeRef.getMetadataId(), ref.getMetadataId()); assertFalse(ref.toString(), ref.getNode().getMetadataId().isPresent()); } } }
Add WFS integration test case to ensure commits survive app shutdown
src/web/geoserver/src/test/java/org/geogit/geoserver/WFSIntegrationTest.java
Add WFS integration test case to ensure commits survive app shutdown
<ide><path>rc/web/geoserver/src/test/java/org/geogit/geoserver/WFSIntegrationTest.java <ide> import java.io.Serializable; <ide> import java.net.URL; <ide> import java.util.Iterator; <add>import java.util.List; <ide> import java.util.Map; <ide> <ide> import org.geogit.api.GeoGIT; <ide> import org.geogit.api.NodeRef; <add>import org.geogit.api.RevCommit; <ide> import org.geogit.api.plumbing.FindTreeChild; <ide> import org.geogit.api.plumbing.LsTreeOp; <ide> import org.geogit.api.plumbing.ResolveGeogitDir; <ide> import org.geogit.api.porcelain.CommitOp; <add>import org.geogit.api.porcelain.LogOp; <ide> import org.geogit.di.GeogitModule; <ide> import org.geogit.di.caching.CachingModule; <ide> import org.geogit.geotools.data.GeoGitDataStore; <ide> import org.opengis.filter.Filter; <ide> import org.w3c.dom.Document; <ide> <add>import com.google.common.collect.ImmutableList; <ide> import com.google.inject.Guice; <ide> import com.google.inject.Injector; <ide> import com.google.inject.util.Modules; <ide> <ide> @Test <ide> public void testInsert() throws Exception { <add> Document dom = insert(); <add> assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); <add> <add> assertEquals("1", getFirstElementByTagName(dom, "wfs:totalInserted").getFirstChild() <add> .getNodeValue()); <add> <add> dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines&srsName=EPSG:4326&"); <add> // print(dom); <add> assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName()); <add> <add> assertEquals(2, dom.getElementsByTagName("geogit:Lines").getLength()); <add> } <add> <add> private Document insert() throws Exception { <ide> String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\" "// <ide> + " xmlns:wfs=\"http://www.opengis.net/wfs\" "// <ide> + " xmlns:gml=\"http://www.opengis.net/gml\" " // <ide> + "</wfs:Transaction>"; <ide> <ide> Document dom = postAsDOM("wfs", xml); <add> return dom; <add> } <add> <add> @Test <add> public void testUpdate() throws Exception { <add> Document dom = update(); <ide> assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); <del> <del> assertEquals("1", getFirstElementByTagName(dom, "wfs:totalInserted").getFirstChild() <add> assertEquals("1", getFirstElementByTagName(dom, "wfs:totalUpdated").getFirstChild() <ide> .getNodeValue()); <ide> <del> dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines&srsName=EPSG:4326&"); <del> // print(dom); <add> dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines" + "&" <add> + "cql_filter=ip%3D1000"); <ide> assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName()); <ide> <del> assertEquals(2, dom.getElementsByTagName("geogit:Lines").getLength()); <del> } <del> <del> @Test <del> public void testUpdate() throws Exception { <add> assertEquals(1, dom.getElementsByTagName("geogit:Lines").getLength()); <add> } <add> <add> private Document update() throws Exception { <ide> String xml = "<wfs:Transaction service=\"WFS\" version=\"1.1.0\""// <ide> + " xmlns:geogit=\"" + NAMESPACE <ide> + "\""// <ide> + "</wfs:Transaction>"; <ide> <ide> Document dom = postAsDOM("wfs", xml); <del> assertEquals("wfs:TransactionResponse", dom.getDocumentElement().getNodeName()); <del> assertEquals("1", getFirstElementByTagName(dom, "wfs:totalUpdated").getFirstChild() <del> .getNodeValue()); <del> <del> dom = getAsDOM("wfs?version=1.1.0&request=getfeature&typename=geogit:Lines" + "&" <del> + "cql_filter=ip%3D1000"); <del> assertEquals("wfs:FeatureCollection", dom.getDocumentElement().getNodeName()); <del> <del> assertEquals(1, dom.getElementsByTagName("geogit:Lines").getLength()); <add> return dom; <ide> } <ide> <ide> /** <ide> assertFalse(ref.toString(), ref.getNode().getMetadataId().isPresent()); <ide> } <ide> } <add> <add> @Test <add> public void testCommitsSurviveShutDown() throws Exception { <add> RepositoryTestCase helper = WFSIntegrationTest.helper; <add> GeoGIT geogit = helper.getGeogit(); <add> <add> insert(); <add> update(); <add> <add> List<RevCommit> expected = ImmutableList.copyOf(geogit.command(LogOp.class).call()); <add> <add> File repoDir = helper.repositoryTempFolder.getRoot(); <add> // shut down server <add> super.doTearDownClass(); <add> <add> geogit = new GeoGIT(repoDir); <add> try { <add> assertNotNull(geogit.getRepository()); <add> List<RevCommit> actual = ImmutableList.copyOf(geogit.command(LogOp.class).call()); <add> assertEquals(expected, actual); <add> } finally { <add> geogit.close(); <add> } <add> } <ide> }
Java
apache-2.0
fb09147b8d284a6d6d20378f62b2925111dd75d5
0
vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,vector-im/vector-android,vector-im/riot-android,vector-im/riot-android,vector-im/vector-android,vector-im/vector-android,vector-im/riot-android
/* * Copyright 2015 OpenMarket Ltd * Copyright 2017 Vector Creations Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Browser; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.adapters.MessageRow; import org.matrix.androidsdk.adapters.AbstractMessagesAdapter; import org.matrix.androidsdk.crypto.data.MXDeviceInfo; import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.fragments.MatrixMessageListFragment; import org.matrix.androidsdk.fragments.MatrixMessagesFragment; import org.matrix.androidsdk.listeners.MXMediaDownloadListener; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.EncryptedEventContent; import org.matrix.androidsdk.rest.model.EncryptedFileInfo; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.FileMessage; import org.matrix.androidsdk.rest.model.ImageMessage; import org.matrix.androidsdk.rest.model.MatrixError; import org.matrix.androidsdk.rest.model.Message; import org.matrix.androidsdk.rest.model.VideoMessage; import org.matrix.androidsdk.util.JsonUtils; import org.matrix.androidsdk.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import im.vector.Matrix; import im.vector.R; import im.vector.activity.CommonActivityUtils; import im.vector.activity.MXCActionBarActivity; import im.vector.activity.VectorHomeActivity; import im.vector.activity.VectorMediasViewerActivity; import im.vector.activity.VectorMemberDetailsActivity; import im.vector.activity.VectorRoomActivity; import im.vector.adapters.VectorMessagesAdapter; import im.vector.db.VectorContentProvider; import im.vector.listeners.IMessagesAdapterActionsListener; import im.vector.receiver.VectorUniversalLinkReceiver; import im.vector.util.SlidableMediaInfo; import im.vector.util.ThemeUtils; import im.vector.util.VectorUtils; import im.vector.widgets.WidgetsManager; public class VectorMessageListFragment extends MatrixMessageListFragment implements IMessagesAdapterActionsListener { private static final String LOG_TAG = VectorMessageListFragment.class.getSimpleName(); public interface IListFragmentEventListener { void onListTouch(); } private static final String TAG_FRAGMENT_RECEIPTS_DIALOG = "TAG_FRAGMENT_RECEIPTS_DIALOG"; private IListFragmentEventListener mHostActivityListener; // onMediaAction actions // private static final int ACTION_VECTOR_SHARE = R.id.ic_action_vector_share; private static final int ACTION_VECTOR_FORWARD = R.id.ic_action_vector_forward; private static final int ACTION_VECTOR_SAVE = R.id.ic_action_vector_save; static final int ACTION_VECTOR_OPEN = 123456; // spinners private View mBackProgressView; private View mForwardProgressView; private View mMainProgressView; public static VectorMessageListFragment newInstance(String matrixId, String roomId, String eventId, String previewMode, int layoutResId) { VectorMessageListFragment f = new VectorMessageListFragment(); Bundle args = new Bundle(); args.putInt(ARG_LAYOUT_ID, layoutResId); args.putString(ARG_MATRIX_ID, matrixId); args.putString(ARG_ROOM_ID, roomId); if (null != eventId) { args.putString(ARG_EVENT_ID, eventId); } if (null != previewMode) { args.putString(ARG_PREVIEW_MODE_ID, previewMode); } f.setArguments(args); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreateView"); View v = super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); // when an event id is defined, display a thick green line to its left if (args.containsKey(ARG_EVENT_ID) && (mAdapter instanceof VectorMessagesAdapter)) { ((VectorMessagesAdapter) mAdapter).setSearchedEventId(args.getString(ARG_EVENT_ID, "")); } if (null != mRoom) { ((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted = mRoom.isEncrypted(); } mMessageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onRowClick(position); } }); v.setBackgroundColor(ThemeUtils.getColor(getActivity(), R.attr.riot_primary_background_color)); return v; } @Override public MatrixMessagesFragment createMessagesFragmentInstance(String roomId) { return VectorMessagesFragment.newInstance(getSession(), roomId, this); } /** * @return the fragment tag to use to restore the matrix messages fragment */ protected String getMatrixMessagesFragmentTag() { return getClass().getName() + ".MATRIX_MESSAGE_FRAGMENT_TAG"; } /** * Called when a fragment is first attached to its activity. * {@link #onCreate(Bundle)} will be called after this. * * @param aHostActivity parent activity */ @Override public void onAttach(Activity aHostActivity) { super.onAttach(aHostActivity); try { mHostActivityListener = (IListFragmentEventListener) aHostActivity; } catch (ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG, "## onAttach(): host activity does not implement IListFragmentEventListener " + aHostActivity); mHostActivityListener = null; } mBackProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_back_progress); mForwardProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_forward_progress); mMainProgressView = aHostActivity.findViewById(R.id.main_progress_layout); } @Override public void onPause() { super.onPause(); if (mAdapter instanceof VectorMessagesAdapter) { VectorMessagesAdapter adapter = ((VectorMessagesAdapter) mAdapter); adapter.setVectorMessagesAdapterActionsListener(null); adapter.onPause(); } } @Override public void onResume() { super.onResume(); if (mAdapter instanceof VectorMessagesAdapter) { VectorMessagesAdapter adapter = ((VectorMessagesAdapter) mAdapter); adapter.setVectorMessagesAdapterActionsListener(this); } } /** * Called when the fragment is no longer attached to its activity. This * is called after {@link #onDestroy()}. */ @Override public void onDetach() { super.onDetach(); mHostActivityListener = null; mBackProgressView = null; mForwardProgressView = null; mMainProgressView = null; } @Override public MXSession getSession(String matrixId) { return Matrix.getMXSession(getActivity(), matrixId); } @Override public MXMediasCache getMXMediasCache() { return Matrix.getInstance(getActivity()).getMediasCache(); } @Override public AbstractMessagesAdapter createMessagesAdapter() { return new VectorMessagesAdapter(mSession, getActivity(), getMXMediasCache()); } /** * The user scrolls the list. * Apply an expected behaviour * * @param event the scroll event */ @Override public void onListTouch(MotionEvent event) { // the user scroll over the keyboard // hides the keyboard if (mCheckSlideToHide && (event.getY() > mMessageListView.getHeight())) { mCheckSlideToHide = false; MXCActionBarActivity.dismissKeyboard(getActivity()); } // notify host activity if (null != mHostActivityListener) mHostActivityListener.onListTouch(); } @Override protected boolean canAddEvent(Event event) { return TextUtils.equals(WidgetsManager.WIDGET_EVENT_TYPE, event.getType()) || super.canAddEvent(event); } /** * Update the encrypted status of the room * * @param isEncrypted true when the room is encrypted */ public void setIsRoomEncrypted(boolean isEncrypted) { if (((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted != isEncrypted) { ((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted = isEncrypted; mAdapter.notifyDataSetChanged(); } } /** * Get the message list view * * @return message list view */ public ListView getMessageListView() { return mMessageListView; } /** * Get the message adapter * * @return message adapter */ public AbstractMessagesAdapter getMessageAdapter() { return mAdapter; } /** * Cancel the messages selection mode. */ public void cancelSelectionMode() { if (null != mAdapter) { ((VectorMessagesAdapter) mAdapter).cancelSelectionMode(); } } private final ApiCallback<Void> mDeviceVerificationCallback = new ApiCallback<Void>() { @Override public void onSuccess(Void info) { mAdapter.notifyDataSetChanged(); } @Override public void onNetworkError(Exception e) { mAdapter.notifyDataSetChanged(); } @Override public void onMatrixError(MatrixError e) { mAdapter.notifyDataSetChanged(); } @Override public void onUnexpectedError(Exception e) { mAdapter.notifyDataSetChanged(); } }; /** * the user taps on the e2e icon * * @param event the event * @param deviceInfo the deviceinfo */ public void onE2eIconClick(final Event event, final MXDeviceInfo deviceInfo) { android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); EncryptedEventContent encryptedEventContent = JsonUtils.toEncryptedEventContent(event.getWireContent().getAsJsonObject()); View layout = inflater.inflate(R.layout.encrypted_event_info, null); TextView textView; textView = layout.findViewById(R.id.encrypted_info_user_id); textView.setText(event.getSender()); textView = layout.findViewById(R.id.encrypted_info_curve25519_identity_key); if (null != deviceInfo) { textView.setText(encryptedEventContent.sender_key); } else { textView.setText(getActivity().getString(R.string.encryption_information_none)); } textView = layout.findViewById(R.id.encrypted_info_claimed_ed25519_fingerprint_key); if (null != deviceInfo) { textView.setText(deviceInfo.fingerprint()); } else { textView.setText(getActivity().getString(R.string.encryption_information_none)); } textView = layout.findViewById(R.id.encrypted_info_algorithm); textView.setText(encryptedEventContent.algorithm); textView = layout.findViewById(R.id.encrypted_info_session_id); textView.setText(encryptedEventContent.session_id); View decryptionErrorLabelTextView = layout.findViewById(R.id.encrypted_info_decryption_error_label); textView = layout.findViewById(R.id.encrypted_info_decryption_error); if (null != event.getCryptoError()) { decryptionErrorLabelTextView.setVisibility(View.VISIBLE); textView.setVisibility(View.VISIBLE); textView.setText("**" + event.getCryptoError().getLocalizedMessage() + "**"); } else { decryptionErrorLabelTextView.setVisibility(View.GONE); textView.setVisibility(View.GONE); } View noDeviceInfoLayout = layout.findViewById(R.id.encrypted_info_no_device_information_layout); View deviceInfoLayout = layout.findViewById(R.id.encrypted_info_sender_device_information_layout); if (null != deviceInfo) { noDeviceInfoLayout.setVisibility(View.GONE); deviceInfoLayout.setVisibility(View.VISIBLE); textView = layout.findViewById(R.id.encrypted_info_name); textView.setText(deviceInfo.displayName()); textView = layout.findViewById(R.id.encrypted_info_device_id); textView.setText(deviceInfo.deviceId); textView = layout.findViewById(R.id.encrypted_info_verification); if (deviceInfo.isUnknown() || deviceInfo.isUnverified()) { textView.setText(getActivity().getString(R.string.encryption_information_not_verified)); } else if (deviceInfo.isVerified()) { textView.setText(getActivity().getString(R.string.encryption_information_verified)); } else { textView.setText(getActivity().getString(R.string.encryption_information_blocked)); } textView = layout.findViewById(R.id.encrypted_ed25519_fingerprint); textView.setText(deviceInfo.fingerprint()); } else { noDeviceInfoLayout.setVisibility(View.VISIBLE); deviceInfoLayout.setVisibility(View.GONE); } builder.setView(layout); builder.setTitle(R.string.encryption_information_title); builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // nothing to do } }); // the current id cannot be blocked, verified... if (!TextUtils.equals(encryptedEventContent.device_id, mSession.getCredentials().deviceId)) { if ((null == event.getCryptoError()) && (null != deviceInfo)) { if (deviceInfo.isUnverified() || deviceInfo.isUnknown()) { builder.setNegativeButton(R.string.encryption_information_verify, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CommonActivityUtils.displayDeviceVerificationDialog(deviceInfo, event.getSender(), mSession, getActivity(), mDeviceVerificationCallback); } }); builder.setPositiveButton(R.string.encryption_information_block, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); } else if (deviceInfo.isVerified()) { builder.setNegativeButton(R.string.encryption_information_unverify, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_UNVERIFIED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); builder.setPositiveButton(R.string.encryption_information_block, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); } else { // BLOCKED builder.setNegativeButton(R.string.encryption_information_verify, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CommonActivityUtils.displayDeviceVerificationDialog(deviceInfo, event.getSender(), mSession, getActivity(), mDeviceVerificationCallback); } }); builder.setPositiveButton(R.string.encryption_information_unblock, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_UNVERIFIED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); } } } final android.support.v7.app.AlertDialog dialog = builder.create(); dialog.show(); if (null == deviceInfo) { mSession.getCrypto().getDeviceList().downloadKeys(Collections.singletonList(event.getSender()), true, new ApiCallback<MXUsersDevicesMap<MXDeviceInfo>>() { @Override public void onSuccess(MXUsersDevicesMap<MXDeviceInfo> info) { Activity activity = getActivity(); if ((null != activity) && !activity.isFinishing() && dialog.isShowing()) { EncryptedEventContent encryptedEventContent = JsonUtils.toEncryptedEventContent(event.getWireContent().getAsJsonObject()); MXDeviceInfo deviceInfo = mSession.getCrypto().deviceWithIdentityKey(encryptedEventContent.sender_key, event.getSender(), encryptedEventContent.algorithm); if (null != deviceInfo) { dialog.cancel(); onE2eIconClick(event, deviceInfo); } } } @Override public void onNetworkError(Exception e) { } @Override public void onMatrixError(MatrixError e) { } @Override public void onUnexpectedError(Exception e) { } }); } } /** * An action has been triggered on an event. * * @param event the event. * @param textMsg the event text * @param action an action ic_action_vector_XXX */ public void onEventAction(final Event event, final String textMsg, final int action) { if (action == R.id.ic_action_vector_resend_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { resend(event); } }); } else if (action == R.id.ic_action_vector_redact_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setMessage(getString(R.string.redact) + " ?"); // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (event.isUndeliverable() || event.isUnkownDevice()) { // delete from the store mSession.getDataHandler().deleteRoomEvent(event); // remove from the adapter mAdapter.removeEventById(event.eventId); mAdapter.notifyDataSetChanged(); mEventSendingListener.onMessageRedacted(event); } else { redactEvent(event.eventId); } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }); } else if (action == R.id.ic_action_vector_copy) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { VectorUtils.copyToClipboard(getActivity(), textMsg); } }); } else if ((action == R.id.ic_action_vector_cancel_upload) || (action == R.id.ic_action_vector_cancel_download)) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setMessage((action == R.id.ic_action_vector_cancel_upload) ? R.string.attachment_cancel_upload : R.string.attachment_cancel_download) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mRoom.cancelEventSending(event); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } else if (action == R.id.ic_action_vector_quote) { Activity attachedActivity = getActivity(); if ((null != attachedActivity) && (attachedActivity instanceof VectorRoomActivity)) { // Quote all paragraphs instead String[] messageParagraphs = textMsg.split("\n\n"); String quotedTextMsg = ""; for (int i = 0; i < messageParagraphs.length; i++) { if (!messageParagraphs[i].trim().equals("")) { quotedTextMsg += "> " + messageParagraphs[i]; } if (!((i + 1) == messageParagraphs.length)) { quotedTextMsg += "\n\n"; } } ((VectorRoomActivity) attachedActivity).insertQuoteInTextEditor(quotedTextMsg + "\n\n"); } } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_save)) { // Message message = JsonUtils.toMessage(event.getContent()); String mediaUrl = null; String mediaMimeType = null; EncryptedFileInfo encryptedFileInfo = null; if (message instanceof ImageMessage) { ImageMessage imageMessage = (ImageMessage) message; mediaUrl = imageMessage.getUrl(); mediaMimeType = imageMessage.getMimeType(); encryptedFileInfo = imageMessage.file; } else if (message instanceof VideoMessage) { VideoMessage videoMessage = (VideoMessage) message; mediaUrl = videoMessage.getUrl(); encryptedFileInfo = videoMessage.file; if (null != videoMessage.info) { mediaMimeType = videoMessage.info.mimetype; } } else if (message instanceof FileMessage) { FileMessage fileMessage = (FileMessage) message; mediaUrl = fileMessage.getUrl(); mediaMimeType = fileMessage.getMimeType(); encryptedFileInfo = fileMessage.file; } // media file ? if (null != mediaUrl) { onMediaAction(action, mediaUrl, mediaMimeType, message.body, encryptedFileInfo); } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_quote)) { // use the body final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, textMsg); sendIntent.setType("text/plain"); if (action == R.id.ic_action_vector_forward) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } else if (action == R.id.ic_action_vector_permalink) { VectorUtils.copyToClipboard(getActivity(), VectorUtils.getPermalink(event.roomId, event.eventId)); } else if (action == R.id.ic_action_vector_report) { onMessageReport(event); } else if ((action == R.id.ic_action_view_source) || (action == R.id.ic_action_view_decrypted_source)) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_event_content, null); TextView textview = view.findViewById(R.id.event_content_text_view); Gson gson = new GsonBuilder().setPrettyPrinting().create(); textview.setText(gson.toJson(JsonUtils.toJson((action == R.id.ic_action_view_source) ? event : event.getClearEvent()))); builder.setView(view); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } }); } else if (action == R.id.ic_action_device_verification) { onE2eIconClick(event, ((VectorMessagesAdapter) mAdapter).getDeviceInfo(event.eventId)); } } /** * The user reports a content problem to the server * * @param event the event to report */ private void onMessageReport(final Event event) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.room_event_action_report_prompt_reason); // add a text input final EditText input = new EditText(getActivity()); builder.setView(input); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String reason = input.getText().toString(); mRoom.report(event.eventId, -100, reason, new SimpleApiCallback<Void>(getActivity()) { @Override public void onSuccess(Void info) { new AlertDialog.Builder(getActivity()) .setMessage(R.string.room_event_action_report_prompt_ignore_user) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ArrayList<String> userIdsList = new ArrayList<>(); userIdsList.add(event.sender); mSession.ignoreUsers(userIdsList, new SimpleApiCallback<Void>() { @Override public void onSuccess(Void info) { } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } /*** * Manage save / share / forward actions on a media file * * @param menuAction the menu action ACTION_VECTOR__XXX * @param mediaUrl the media URL (must be not null) * @param mediaMimeType the mime type * @param filename the filename */ void onMediaAction(final int menuAction, final String mediaUrl, final String mediaMimeType, final String filename, final EncryptedFileInfo encryptedFileInfo) { MXMediasCache mediasCache = Matrix.getInstance(getActivity()).getMediasCache(); File file = mediasCache.mediaCacheFile(mediaUrl, mediaMimeType); // check if the media has already been downloaded if (null != file) { // download if ((menuAction == ACTION_VECTOR_SAVE) || (menuAction == ACTION_VECTOR_OPEN)) { CommonActivityUtils.saveMediaIntoDownloads(getActivity(), file, filename, mediaMimeType, new SimpleApiCallback<String>() { @Override public void onSuccess(String savedMediaPath) { if (null != savedMediaPath) { if (menuAction == ACTION_VECTOR_SAVE) { Toast.makeText(getActivity(), getText(R.string.media_slider_saved), Toast.LENGTH_LONG).show(); } else { CommonActivityUtils.openMedia(getActivity(), savedMediaPath, mediaMimeType); } } } }); } else { // shared / forward Uri mediaUri = null; File renamedFile = file; if (!TextUtils.isEmpty(filename)) { try { InputStream fin = new FileInputStream(file); String tmpUrl = mediasCache.saveMedia(fin, filename, mediaMimeType); if (null != tmpUrl) { renamedFile = mediasCache.mediaCacheFile(tmpUrl, mediaMimeType); } } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction shared / forward failed : " + e.getLocalizedMessage()); } } if (null != renamedFile) { try { mediaUri = VectorContentProvider.absolutePathToUri(getActivity(), renamedFile.getAbsolutePath()); } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction VectorContentProvider.absolutePathToUri: " + e.getLocalizedMessage()); } } if (null != mediaUri) { final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.setType(mediaMimeType); sendIntent.putExtra(Intent.EXTRA_STREAM, mediaUri); if (menuAction == ACTION_VECTOR_FORWARD) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } } else { // else download it final String downloadId = mediasCache.downloadMedia(getActivity().getApplicationContext(), mSession.getHomeServerConfig(), mediaUrl, mediaMimeType, encryptedFileInfo); mAdapter.notifyDataSetChanged(); if (null != downloadId) { mediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() { @Override public void onDownloadError(String downloadId, JsonElement jsonElement) { MatrixError error = JsonUtils.toMatrixError(jsonElement); if ((null != error) && error.isSupportedErrorCode() && (null != VectorMessageListFragment.this.getActivity())) { Toast.makeText(VectorMessageListFragment.this.getActivity(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onDownloadComplete(String aDownloadId) { if (aDownloadId.equals(downloadId)) { VectorMessageListFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { onMediaAction(menuAction, mediaUrl, mediaMimeType, filename, encryptedFileInfo); } }); } } }); } } } /** * return true to display all the events. * else the unknown events will be hidden. */ @Override public boolean isDisplayAllEvents() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); return preferences.getBoolean(getString(R.string.settings_key_display_all_events), false); } private void setViewVisibility(View view, int visibility) { if ((null != view) && (null != getActivity())) { view.setVisibility(visibility); } } @Override public void showLoadingBackProgress() { setViewVisibility(mBackProgressView, View.VISIBLE); } @Override public void hideLoadingBackProgress() { setViewVisibility(mBackProgressView, View.GONE); } @Override public void showLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.VISIBLE); } @Override public void hideLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.GONE); } @Override public void showInitLoading() { setViewVisibility(mMainProgressView, View.VISIBLE); } @Override public void hideInitLoading() { setViewVisibility(mMainProgressView, View.GONE); } public boolean onRowLongClick(int position) { return false; } /** * @return the image and video messages list */ ArrayList<SlidableMediaInfo> listSlidableMessages() { ArrayList<SlidableMediaInfo> res = new ArrayList<>(); for (int position = 0; position < mAdapter.getCount(); position++) { MessageRow row = mAdapter.getItem(position); Message message = JsonUtils.toMessage(row.getEvent().getContent()); if (Message.MSGTYPE_IMAGE.equals(message.msgtype)) { ImageMessage imageMessage = (ImageMessage) message; SlidableMediaInfo info = new SlidableMediaInfo(); info.mMessageType = Message.MSGTYPE_IMAGE; info.mFileName = imageMessage.body; info.mMediaUrl = imageMessage.getUrl(); info.mRotationAngle = imageMessage.getRotation(); info.mOrientation = imageMessage.getOrientation(); info.mMimeType = imageMessage.getMimeType(); info.mEncryptedFileInfo = imageMessage.file; res.add(info); } else if (Message.MSGTYPE_VIDEO.equals(message.msgtype)) { SlidableMediaInfo info = new SlidableMediaInfo(); VideoMessage videoMessage = (VideoMessage) message; info.mMessageType = Message.MSGTYPE_VIDEO; info.mFileName = videoMessage.body; info.mMediaUrl = videoMessage.getUrl(); info.mThumbnailUrl = (null != videoMessage.info) ? videoMessage.info.thumbnail_url : null; info.mMimeType = videoMessage.getMimeType(); info.mEncryptedFileInfo = videoMessage.file; res.add(info); } } return res; } /** * Returns the mediaMessage position in listMediaMessages. * * @param mediaMessagesList the media messages list * @param mediaMessage the imageMessage * @return the imageMessage position. -1 if not found. */ int getMediaMessagePosition(ArrayList<SlidableMediaInfo> mediaMessagesList, Message mediaMessage) { String url = null; if (mediaMessage instanceof ImageMessage) { url = ((ImageMessage) mediaMessage).getUrl(); } else if (mediaMessage instanceof VideoMessage) { url = ((VideoMessage) mediaMessage).getUrl(); } // sanity check if (null == url) { return -1; } for (int index = 0; index < mediaMessagesList.size(); index++) { if (mediaMessagesList.get(index).mMediaUrl.equals(url)) { return index; } } return -1; } @Override public void onRowClick(int position) { try { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); // switch in section mode ((VectorMessagesAdapter) mAdapter).onEventTap(event.eventId); } catch (Exception e) { Log.e(LOG_TAG, "## onRowClick() failed " + e.getMessage()); } } @Override public void onContentClick(int position) { try { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); VectorMessagesAdapter vectorMessagesAdapter = (VectorMessagesAdapter) mAdapter; if (vectorMessagesAdapter.isInSelectionMode()) { // cancel the selection mode. vectorMessagesAdapter.onEventTap(null); return; } Message message = JsonUtils.toMessage(event.getContent()); // video and images are displayed inside a medias slider. if (Message.MSGTYPE_IMAGE.equals(message.msgtype) || (Message.MSGTYPE_VIDEO.equals(message.msgtype))) { ArrayList<SlidableMediaInfo> mediaMessagesList = listSlidableMessages(); int listPosition = getMediaMessagePosition(mediaMessagesList, message); if (listPosition >= 0) { Intent viewImageIntent = new Intent(getActivity(), VectorMediasViewerActivity.class); viewImageIntent.putExtra(VectorMediasViewerActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_WIDTH, mAdapter.getMaxThumbnailWidth()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_HEIGHT, mAdapter.getMaxThumbnailHeight()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST, mediaMessagesList); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST_INDEX, listPosition); getActivity().startActivity(viewImageIntent); } } else if (Message.MSGTYPE_FILE.equals(message.msgtype) || Message.MSGTYPE_AUDIO.equals(message.msgtype)) { FileMessage fileMessage = JsonUtils.toFileMessage(event.getContent()); if (null != fileMessage.getUrl()) { onMediaAction(ACTION_VECTOR_OPEN, fileMessage.getUrl(), fileMessage.getMimeType(), fileMessage.body, fileMessage.file); } } else { // switch in section mode vectorMessagesAdapter.onEventTap(event.eventId); } } catch (Exception e) { Log.e(LOG_TAG, "## onContentClick() failed " + e.getMessage()); } } @Override public boolean onContentLongClick(int position) { return onRowLongClick(position); } @Override public void onAvatarClick(String userId) { try { Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); // in preview mode // the room is stored in a temporary store // so provide an handle to retrieve it if (null != getRoomPreviewData()) { roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_STORE_ID, new Integer(Matrix.getInstance(getActivity()).addTmpStore(mEventTimeLine.getStore()))); } roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId()); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); getActivity().startActivityForResult(roomDetailsIntent, VectorRoomActivity.GET_MENTION_REQUEST_CODE); } catch (Exception e) { Log.e(LOG_TAG, "## onAvatarClick() failed " + e.getMessage()); } } @Override public boolean onAvatarLongClick(String userId) { if (getActivity() instanceof VectorRoomActivity) { try { RoomState state = mRoom.getLiveState(); if (null != state) { String displayName = state.getMemberName(userId); if (!TextUtils.isEmpty(displayName)) { ((VectorRoomActivity) getActivity()).insertUserDisplayNameInTextEditor(displayName); } } } catch (Exception e) { Log.e(LOG_TAG, "## onAvatarLongClick() failed " + e.getMessage()); } } return true; } @Override public void onSenderNameClick(String userId, String displayName) { if (getActivity() instanceof VectorRoomActivity) { try { ((VectorRoomActivity) getActivity()).insertUserDisplayNameInTextEditor(displayName); } catch (Exception e) { Log.e(LOG_TAG, "## onSenderNameClick() failed " + e.getMessage()); } } } @Override public void onMediaDownloaded(int position) { } @Override public void onMoreReadReceiptClick(String eventId) { try { FragmentManager fm = getActivity().getSupportFragmentManager(); VectorReadReceiptsDialogFragment fragment = (VectorReadReceiptsDialogFragment) fm.findFragmentByTag(TAG_FRAGMENT_RECEIPTS_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } fragment = VectorReadReceiptsDialogFragment.newInstance(mSession.getMyUserId(), mRoom.getRoomId(), eventId); fragment.show(fm, TAG_FRAGMENT_RECEIPTS_DIALOG); } catch (Exception e) { Log.e(LOG_TAG, "## onMoreReadReceiptClick() failed " + e.getMessage()); } } @Override public void onURLClick(Uri uri) { try { if (null != uri) { HashMap<String, String> universalParams = VectorUniversalLinkReceiver.parseUniversalLink(uri); if (null != universalParams) { // open the member sheet from the current activity if (universalParams.containsKey(VectorUniversalLinkReceiver.ULINK_MATRIX_USER_ID_KEY)) { Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, universalParams.get(VectorUniversalLinkReceiver.ULINK_MATRIX_USER_ID_KEY)); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); getActivity().startActivityForResult(roomDetailsIntent, VectorRoomActivity.GET_MENTION_REQUEST_CODE); } else { // pop to the home activity Intent intent = new Intent(getActivity(), VectorHomeActivity.class); intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(VectorHomeActivity.EXTRA_JUMP_TO_UNIVERSAL_LINK, uri); getActivity().startActivity(intent); } } else { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, getActivity().getPackageName()); getActivity().startActivity(intent); } } } catch (Exception e) { Log.e(LOG_TAG, "## onURLClick() failed " + e.getMessage()); } } @Override public void onMatrixUserIdClick(final String userId) { try { // start member details UI Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId()); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); startActivity(roomDetailsIntent); } catch (Exception e) { Log.e(LOG_TAG, "## onMatrixUserIdClick() failed " + e.getMessage()); } } @Override public void onRoomAliasClick(String roomAlias) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomAlias, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomAliasClick failed " + e.getLocalizedMessage()); } } @Override public void onRoomIdClick(String roomId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomId, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } @Override public void onMessageIdClick(String messageId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(mRoom.getRoomId(), messageId))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } private int mInvalidIndexesCount = 0; @Override public void onInvalidIndexes() { mInvalidIndexesCount++; // it should happen once // else we assume that the adapter is really corrupted // It seems better to close the linked activity to avoid infinite refresh. if (1 == mInvalidIndexesCount) { mMessageListView.post(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } else { mMessageListView.post(new Runnable() { @Override public void run() { if (null != getActivity()) { getActivity().finish(); } } }); } } private final HashMap<String, Boolean> mHighlightStatusByEventId = new HashMap<>(); @Override public boolean shouldHighlightEvent(Event event) { // sanity check if ((null == event) || (null == event.eventId)) { return false; } String eventId = event.eventId; Boolean status = mHighlightStatusByEventId.get(eventId); if (null != status) { return status; } boolean res = (null != mSession.getDataHandler().getBingRulesManager().fulfilledHighlightBingRule(event)); mHighlightStatusByEventId.put(eventId, res); return res; } }
vector/src/main/java/im/vector/fragments/VectorMessageListFragment.java
/* * Copyright 2015 OpenMarket Ltd * Copyright 2017 Vector Creations Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Browser; import android.support.v4.app.FragmentManager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.adapters.MessageRow; import org.matrix.androidsdk.adapters.AbstractMessagesAdapter; import org.matrix.androidsdk.crypto.data.MXDeviceInfo; import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.fragments.MatrixMessageListFragment; import org.matrix.androidsdk.fragments.MatrixMessagesFragment; import org.matrix.androidsdk.listeners.MXMediaDownloadListener; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.EncryptedEventContent; import org.matrix.androidsdk.rest.model.EncryptedFileInfo; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.FileMessage; import org.matrix.androidsdk.rest.model.ImageMessage; import org.matrix.androidsdk.rest.model.MatrixError; import org.matrix.androidsdk.rest.model.Message; import org.matrix.androidsdk.rest.model.VideoMessage; import org.matrix.androidsdk.util.JsonUtils; import org.matrix.androidsdk.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import im.vector.Matrix; import im.vector.R; import im.vector.activity.CommonActivityUtils; import im.vector.activity.MXCActionBarActivity; import im.vector.activity.VectorHomeActivity; import im.vector.activity.VectorMediasViewerActivity; import im.vector.activity.VectorMemberDetailsActivity; import im.vector.activity.VectorRoomActivity; import im.vector.adapters.VectorMessagesAdapter; import im.vector.db.VectorContentProvider; import im.vector.listeners.IMessagesAdapterActionsListener; import im.vector.receiver.VectorUniversalLinkReceiver; import im.vector.util.SlidableMediaInfo; import im.vector.util.ThemeUtils; import im.vector.util.VectorUtils; import im.vector.widgets.WidgetsManager; public class VectorMessageListFragment extends MatrixMessageListFragment implements IMessagesAdapterActionsListener { private static final String LOG_TAG = VectorMessageListFragment.class.getSimpleName(); public interface IListFragmentEventListener { void onListTouch(); } private static final String TAG_FRAGMENT_RECEIPTS_DIALOG = "TAG_FRAGMENT_RECEIPTS_DIALOG"; private IListFragmentEventListener mHostActivityListener; // onMediaAction actions // private static final int ACTION_VECTOR_SHARE = R.id.ic_action_vector_share; private static final int ACTION_VECTOR_FORWARD = R.id.ic_action_vector_forward; private static final int ACTION_VECTOR_SAVE = R.id.ic_action_vector_save; static final int ACTION_VECTOR_OPEN = 123456; // spinners private View mBackProgressView; private View mForwardProgressView; private View mMainProgressView; public static VectorMessageListFragment newInstance(String matrixId, String roomId, String eventId, String previewMode, int layoutResId) { VectorMessageListFragment f = new VectorMessageListFragment(); Bundle args = new Bundle(); args.putInt(ARG_LAYOUT_ID, layoutResId); args.putString(ARG_MATRIX_ID, matrixId); args.putString(ARG_ROOM_ID, roomId); if (null != eventId) { args.putString(ARG_EVENT_ID, eventId); } if (null != previewMode) { args.putString(ARG_PREVIEW_MODE_ID, previewMode); } f.setArguments(args); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreateView"); View v = super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); // when an event id is defined, display a thick green line to its left if (args.containsKey(ARG_EVENT_ID) && (mAdapter instanceof VectorMessagesAdapter)) { ((VectorMessagesAdapter) mAdapter).setSearchedEventId(args.getString(ARG_EVENT_ID, "")); } if (null != mRoom) { ((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted = mRoom.isEncrypted(); } mMessageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onRowClick(position); } }); v.setBackgroundColor(ThemeUtils.getColor(getActivity(), R.attr.riot_primary_background_color)); return v; } @Override public MatrixMessagesFragment createMessagesFragmentInstance(String roomId) { return VectorMessagesFragment.newInstance(getSession(), roomId, this); } /** * @return the fragment tag to use to restore the matrix messages fragment */ protected String getMatrixMessagesFragmentTag() { return getClass().getName() + ".MATRIX_MESSAGE_FRAGMENT_TAG"; } /** * Called when a fragment is first attached to its activity. * {@link #onCreate(Bundle)} will be called after this. * * @param aHostActivity parent activity */ @Override public void onAttach(Activity aHostActivity) { super.onAttach(aHostActivity); try { mHostActivityListener = (IListFragmentEventListener) aHostActivity; } catch (ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG, "## onAttach(): host activity does not implement IListFragmentEventListener " + aHostActivity); mHostActivityListener = null; } mBackProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_back_progress); mForwardProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_forward_progress); mMainProgressView = aHostActivity.findViewById(R.id.main_progress_layout); } @Override public void onPause() { super.onPause(); if (mAdapter instanceof VectorMessagesAdapter) { VectorMessagesAdapter adapter = ((VectorMessagesAdapter) mAdapter); adapter.setVectorMessagesAdapterActionsListener(null); adapter.onPause(); } } @Override public void onResume() { super.onResume(); if (mAdapter instanceof VectorMessagesAdapter) { VectorMessagesAdapter adapter = ((VectorMessagesAdapter) mAdapter); adapter.setVectorMessagesAdapterActionsListener(this); } } /** * Called when the fragment is no longer attached to its activity. This * is called after {@link #onDestroy()}. */ @Override public void onDetach() { super.onDetach(); mHostActivityListener = null; mBackProgressView = null; mForwardProgressView = null; mMainProgressView = null; } @Override public MXSession getSession(String matrixId) { return Matrix.getMXSession(getActivity(), matrixId); } @Override public MXMediasCache getMXMediasCache() { return Matrix.getInstance(getActivity()).getMediasCache(); } @Override public AbstractMessagesAdapter createMessagesAdapter() { return new VectorMessagesAdapter(mSession, getActivity(), getMXMediasCache()); } /** * The user scrolls the list. * Apply an expected behaviour * * @param event the scroll event */ @Override public void onListTouch(MotionEvent event) { // the user scroll over the keyboard // hides the keyboard if (mCheckSlideToHide && (event.getY() > mMessageListView.getHeight())) { mCheckSlideToHide = false; MXCActionBarActivity.dismissKeyboard(getActivity()); } // notify host activity if (null != mHostActivityListener) mHostActivityListener.onListTouch(); } @Override protected boolean canAddEvent(Event event) { return TextUtils.equals(WidgetsManager.WIDGET_EVENT_TYPE, event.getType()) || super.canAddEvent(event); } /** * Update the encrypted status of the room * * @param isEncrypted true when the room is encrypted */ public void setIsRoomEncrypted(boolean isEncrypted) { ((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted = isEncrypted; mAdapter.notifyDataSetChanged(); } /** * Get the message list view * * @return message list view */ public ListView getMessageListView() { return mMessageListView; } /** * Get the message adapter * * @return message adapter */ public AbstractMessagesAdapter getMessageAdapter() { return mAdapter; } /** * Cancel the messages selection mode. */ public void cancelSelectionMode() { if (null != mAdapter) { ((VectorMessagesAdapter) mAdapter).cancelSelectionMode(); } } private final ApiCallback<Void> mDeviceVerificationCallback = new ApiCallback<Void>() { @Override public void onSuccess(Void info) { mAdapter.notifyDataSetChanged(); } @Override public void onNetworkError(Exception e) { mAdapter.notifyDataSetChanged(); } @Override public void onMatrixError(MatrixError e) { mAdapter.notifyDataSetChanged(); } @Override public void onUnexpectedError(Exception e) { mAdapter.notifyDataSetChanged(); } }; /** * the user taps on the e2e icon * * @param event the event * @param deviceInfo the deviceinfo */ public void onE2eIconClick(final Event event, final MXDeviceInfo deviceInfo) { android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); EncryptedEventContent encryptedEventContent = JsonUtils.toEncryptedEventContent(event.getWireContent().getAsJsonObject()); View layout = inflater.inflate(R.layout.encrypted_event_info, null); TextView textView; textView = layout.findViewById(R.id.encrypted_info_user_id); textView.setText(event.getSender()); textView = layout.findViewById(R.id.encrypted_info_curve25519_identity_key); if (null != deviceInfo) { textView.setText(encryptedEventContent.sender_key); } else { textView.setText(getActivity().getString(R.string.encryption_information_none)); } textView = layout.findViewById(R.id.encrypted_info_claimed_ed25519_fingerprint_key); if (null != deviceInfo) { textView.setText(deviceInfo.fingerprint()); } else { textView.setText(getActivity().getString(R.string.encryption_information_none)); } textView = layout.findViewById(R.id.encrypted_info_algorithm); textView.setText(encryptedEventContent.algorithm); textView = layout.findViewById(R.id.encrypted_info_session_id); textView.setText(encryptedEventContent.session_id); View decryptionErrorLabelTextView = layout.findViewById(R.id.encrypted_info_decryption_error_label); textView = layout.findViewById(R.id.encrypted_info_decryption_error); if (null != event.getCryptoError()) { decryptionErrorLabelTextView.setVisibility(View.VISIBLE); textView.setVisibility(View.VISIBLE); textView.setText("**" + event.getCryptoError().getLocalizedMessage() + "**"); } else { decryptionErrorLabelTextView.setVisibility(View.GONE); textView.setVisibility(View.GONE); } View noDeviceInfoLayout = layout.findViewById(R.id.encrypted_info_no_device_information_layout); View deviceInfoLayout = layout.findViewById(R.id.encrypted_info_sender_device_information_layout); if (null != deviceInfo) { noDeviceInfoLayout.setVisibility(View.GONE); deviceInfoLayout.setVisibility(View.VISIBLE); textView = layout.findViewById(R.id.encrypted_info_name); textView.setText(deviceInfo.displayName()); textView = layout.findViewById(R.id.encrypted_info_device_id); textView.setText(deviceInfo.deviceId); textView = layout.findViewById(R.id.encrypted_info_verification); if (deviceInfo.isUnknown() || deviceInfo.isUnverified()) { textView.setText(getActivity().getString(R.string.encryption_information_not_verified)); } else if (deviceInfo.isVerified()) { textView.setText(getActivity().getString(R.string.encryption_information_verified)); } else { textView.setText(getActivity().getString(R.string.encryption_information_blocked)); } textView = layout.findViewById(R.id.encrypted_ed25519_fingerprint); textView.setText(deviceInfo.fingerprint()); } else { noDeviceInfoLayout.setVisibility(View.VISIBLE); deviceInfoLayout.setVisibility(View.GONE); } builder.setView(layout); builder.setTitle(R.string.encryption_information_title); builder.setNeutralButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // nothing to do } }); // the current id cannot be blocked, verified... if (!TextUtils.equals(encryptedEventContent.device_id, mSession.getCredentials().deviceId)) { if ((null == event.getCryptoError()) && (null != deviceInfo)) { if (deviceInfo.isUnverified() || deviceInfo.isUnknown()) { builder.setNegativeButton(R.string.encryption_information_verify, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CommonActivityUtils.displayDeviceVerificationDialog(deviceInfo, event.getSender(), mSession, getActivity(), mDeviceVerificationCallback); } }); builder.setPositiveButton(R.string.encryption_information_block, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); } else if (deviceInfo.isVerified()) { builder.setNegativeButton(R.string.encryption_information_unverify, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_UNVERIFIED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); builder.setPositiveButton(R.string.encryption_information_block, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); } else { // BLOCKED builder.setNegativeButton(R.string.encryption_information_verify, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { CommonActivityUtils.displayDeviceVerificationDialog(deviceInfo, event.getSender(), mSession, getActivity(), mDeviceVerificationCallback); } }); builder.setPositiveButton(R.string.encryption_information_unblock, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { mSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_UNVERIFIED, deviceInfo.deviceId, event.getSender(), mDeviceVerificationCallback); } }); } } } final android.support.v7.app.AlertDialog dialog = builder.create(); dialog.show(); if (null == deviceInfo) { mSession.getCrypto().getDeviceList().downloadKeys(Collections.singletonList(event.getSender()), true, new ApiCallback<MXUsersDevicesMap<MXDeviceInfo>>() { @Override public void onSuccess(MXUsersDevicesMap<MXDeviceInfo> info) { Activity activity = getActivity(); if ((null != activity) && !activity.isFinishing() && dialog.isShowing()) { EncryptedEventContent encryptedEventContent = JsonUtils.toEncryptedEventContent(event.getWireContent().getAsJsonObject()); MXDeviceInfo deviceInfo = mSession.getCrypto().deviceWithIdentityKey(encryptedEventContent.sender_key, event.getSender(), encryptedEventContent.algorithm); if (null != deviceInfo) { dialog.cancel(); onE2eIconClick(event, deviceInfo); } } } @Override public void onNetworkError(Exception e) { } @Override public void onMatrixError(MatrixError e) { } @Override public void onUnexpectedError(Exception e) { } }); } } /** * An action has been triggered on an event. * * @param event the event. * @param textMsg the event text * @param action an action ic_action_vector_XXX */ public void onEventAction(final Event event, final String textMsg, final int action) { if (action == R.id.ic_action_vector_resend_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { resend(event); } }); } else if (action == R.id.ic_action_vector_redact_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setMessage(getString(R.string.redact) + " ?"); // set dialog message alertDialogBuilder .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if (event.isUndeliverable() || event.isUnkownDevice()) { // delete from the store mSession.getDataHandler().deleteRoomEvent(event); // remove from the adapter mAdapter.removeEventById(event.eventId); mAdapter.notifyDataSetChanged(); mEventSendingListener.onMessageRedacted(event); } else { redactEvent(event.eventId); } } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); } }); } else if (action == R.id.ic_action_vector_copy) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { VectorUtils.copyToClipboard(getActivity(), textMsg); } }); } else if ((action == R.id.ic_action_vector_cancel_upload) || (action == R.id.ic_action_vector_cancel_download)) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(getActivity()) .setMessage((action == R.id.ic_action_vector_cancel_upload) ? R.string.attachment_cancel_upload : R.string.attachment_cancel_download) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mRoom.cancelEventSending(event); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } else if (action == R.id.ic_action_vector_quote) { Activity attachedActivity = getActivity(); if ((null != attachedActivity) && (attachedActivity instanceof VectorRoomActivity)) { // Quote all paragraphs instead String[] messageParagraphs = textMsg.split("\n\n"); String quotedTextMsg = ""; for (int i = 0; i < messageParagraphs.length; i++) { if (!messageParagraphs[i].trim().equals("")) { quotedTextMsg += "> " + messageParagraphs[i]; } if (!((i + 1) == messageParagraphs.length)) { quotedTextMsg += "\n\n"; } } ((VectorRoomActivity) attachedActivity).insertQuoteInTextEditor(quotedTextMsg + "\n\n"); } } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_save)) { // Message message = JsonUtils.toMessage(event.getContent()); String mediaUrl = null; String mediaMimeType = null; EncryptedFileInfo encryptedFileInfo = null; if (message instanceof ImageMessage) { ImageMessage imageMessage = (ImageMessage) message; mediaUrl = imageMessage.getUrl(); mediaMimeType = imageMessage.getMimeType(); encryptedFileInfo = imageMessage.file; } else if (message instanceof VideoMessage) { VideoMessage videoMessage = (VideoMessage) message; mediaUrl = videoMessage.getUrl(); encryptedFileInfo = videoMessage.file; if (null != videoMessage.info) { mediaMimeType = videoMessage.info.mimetype; } } else if (message instanceof FileMessage) { FileMessage fileMessage = (FileMessage) message; mediaUrl = fileMessage.getUrl(); mediaMimeType = fileMessage.getMimeType(); encryptedFileInfo = fileMessage.file; } // media file ? if (null != mediaUrl) { onMediaAction(action, mediaUrl, mediaMimeType, message.body, encryptedFileInfo); } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_quote)) { // use the body final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, textMsg); sendIntent.setType("text/plain"); if (action == R.id.ic_action_vector_forward) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } else if (action == R.id.ic_action_vector_permalink) { VectorUtils.copyToClipboard(getActivity(), VectorUtils.getPermalink(event.roomId, event.eventId)); } else if (action == R.id.ic_action_vector_report) { onMessageReport(event); } else if ((action == R.id.ic_action_view_source) || (action == R.id.ic_action_view_decrypted_source)) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View view = getActivity().getLayoutInflater().inflate(R.layout.dialog_event_content, null); TextView textview = view.findViewById(R.id.event_content_text_view); Gson gson = new GsonBuilder().setPrettyPrinting().create(); textview.setText(gson.toJson(JsonUtils.toJson((action == R.id.ic_action_view_source) ? event : event.getClearEvent()))); builder.setView(view); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } }); } else if (action == R.id.ic_action_device_verification) { onE2eIconClick(event, ((VectorMessagesAdapter) mAdapter).getDeviceInfo(event.eventId)); } } /** * The user reports a content problem to the server * * @param event the event to report */ private void onMessageReport(final Event event) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.room_event_action_report_prompt_reason); // add a text input final EditText input = new EditText(getActivity()); builder.setView(input); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String reason = input.getText().toString(); mRoom.report(event.eventId, -100, reason, new SimpleApiCallback<Void>(getActivity()) { @Override public void onSuccess(Void info) { new AlertDialog.Builder(getActivity()) .setMessage(R.string.room_event_action_report_prompt_ignore_user) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ArrayList<String> userIdsList = new ArrayList<>(); userIdsList.add(event.sender); mSession.ignoreUsers(userIdsList, new SimpleApiCallback<Void>() { @Override public void onSuccess(Void info) { } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } /*** * Manage save / share / forward actions on a media file * * @param menuAction the menu action ACTION_VECTOR__XXX * @param mediaUrl the media URL (must be not null) * @param mediaMimeType the mime type * @param filename the filename */ void onMediaAction(final int menuAction, final String mediaUrl, final String mediaMimeType, final String filename, final EncryptedFileInfo encryptedFileInfo) { MXMediasCache mediasCache = Matrix.getInstance(getActivity()).getMediasCache(); File file = mediasCache.mediaCacheFile(mediaUrl, mediaMimeType); // check if the media has already been downloaded if (null != file) { // download if ((menuAction == ACTION_VECTOR_SAVE) || (menuAction == ACTION_VECTOR_OPEN)) { CommonActivityUtils.saveMediaIntoDownloads(getActivity(), file, filename, mediaMimeType, new SimpleApiCallback<String>() { @Override public void onSuccess(String savedMediaPath) { if (null != savedMediaPath) { if (menuAction == ACTION_VECTOR_SAVE) { Toast.makeText(getActivity(), getText(R.string.media_slider_saved), Toast.LENGTH_LONG).show(); } else { CommonActivityUtils.openMedia(getActivity(), savedMediaPath, mediaMimeType); } } } }); } else { // shared / forward Uri mediaUri = null; File renamedFile = file; if (!TextUtils.isEmpty(filename)) { try { InputStream fin = new FileInputStream(file); String tmpUrl = mediasCache.saveMedia(fin, filename, mediaMimeType); if (null != tmpUrl) { renamedFile = mediasCache.mediaCacheFile(tmpUrl, mediaMimeType); } } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction shared / forward failed : " + e.getLocalizedMessage()); } } if (null != renamedFile) { try { mediaUri = VectorContentProvider.absolutePathToUri(getActivity(), renamedFile.getAbsolutePath()); } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction VectorContentProvider.absolutePathToUri: " + e.getLocalizedMessage()); } } if (null != mediaUri) { final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.setType(mediaMimeType); sendIntent.putExtra(Intent.EXTRA_STREAM, mediaUri); if (menuAction == ACTION_VECTOR_FORWARD) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } } else { // else download it final String downloadId = mediasCache.downloadMedia(getActivity().getApplicationContext(), mSession.getHomeServerConfig(), mediaUrl, mediaMimeType, encryptedFileInfo); mAdapter.notifyDataSetChanged(); if (null != downloadId) { mediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() { @Override public void onDownloadError(String downloadId, JsonElement jsonElement) { MatrixError error = JsonUtils.toMatrixError(jsonElement); if ((null != error) && error.isSupportedErrorCode() && (null != VectorMessageListFragment.this.getActivity())) { Toast.makeText(VectorMessageListFragment.this.getActivity(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onDownloadComplete(String aDownloadId) { if (aDownloadId.equals(downloadId)) { VectorMessageListFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { onMediaAction(menuAction, mediaUrl, mediaMimeType, filename, encryptedFileInfo); } }); } } }); } } } /** * return true to display all the events. * else the unknown events will be hidden. */ @Override public boolean isDisplayAllEvents() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); return preferences.getBoolean(getString(R.string.settings_key_display_all_events), false); } private void setViewVisibility(View view, int visibility) { if ((null != view) && (null != getActivity())) { view.setVisibility(visibility); } } @Override public void showLoadingBackProgress() { setViewVisibility(mBackProgressView, View.VISIBLE); } @Override public void hideLoadingBackProgress() { setViewVisibility(mBackProgressView, View.GONE); } @Override public void showLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.VISIBLE); } @Override public void hideLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.GONE); } @Override public void showInitLoading() { setViewVisibility(mMainProgressView, View.VISIBLE); } @Override public void hideInitLoading() { setViewVisibility(mMainProgressView, View.GONE); } public boolean onRowLongClick(int position) { return false; } /** * @return the image and video messages list */ ArrayList<SlidableMediaInfo> listSlidableMessages() { ArrayList<SlidableMediaInfo> res = new ArrayList<>(); for (int position = 0; position < mAdapter.getCount(); position++) { MessageRow row = mAdapter.getItem(position); Message message = JsonUtils.toMessage(row.getEvent().getContent()); if (Message.MSGTYPE_IMAGE.equals(message.msgtype)) { ImageMessage imageMessage = (ImageMessage) message; SlidableMediaInfo info = new SlidableMediaInfo(); info.mMessageType = Message.MSGTYPE_IMAGE; info.mFileName = imageMessage.body; info.mMediaUrl = imageMessage.getUrl(); info.mRotationAngle = imageMessage.getRotation(); info.mOrientation = imageMessage.getOrientation(); info.mMimeType = imageMessage.getMimeType(); info.mEncryptedFileInfo = imageMessage.file; res.add(info); } else if (Message.MSGTYPE_VIDEO.equals(message.msgtype)) { SlidableMediaInfo info = new SlidableMediaInfo(); VideoMessage videoMessage = (VideoMessage) message; info.mMessageType = Message.MSGTYPE_VIDEO; info.mFileName = videoMessage.body; info.mMediaUrl = videoMessage.getUrl(); info.mThumbnailUrl = (null != videoMessage.info) ? videoMessage.info.thumbnail_url : null; info.mMimeType = videoMessage.getMimeType(); info.mEncryptedFileInfo = videoMessage.file; res.add(info); } } return res; } /** * Returns the mediaMessage position in listMediaMessages. * * @param mediaMessagesList the media messages list * @param mediaMessage the imageMessage * @return the imageMessage position. -1 if not found. */ int getMediaMessagePosition(ArrayList<SlidableMediaInfo> mediaMessagesList, Message mediaMessage) { String url = null; if (mediaMessage instanceof ImageMessage) { url = ((ImageMessage) mediaMessage).getUrl(); } else if (mediaMessage instanceof VideoMessage) { url = ((VideoMessage) mediaMessage).getUrl(); } // sanity check if (null == url) { return -1; } for (int index = 0; index < mediaMessagesList.size(); index++) { if (mediaMessagesList.get(index).mMediaUrl.equals(url)) { return index; } } return -1; } @Override public void onRowClick(int position) { try { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); // switch in section mode ((VectorMessagesAdapter) mAdapter).onEventTap(event.eventId); } catch (Exception e) { Log.e(LOG_TAG, "## onRowClick() failed " + e.getMessage()); } } @Override public void onContentClick(int position) { try { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); VectorMessagesAdapter vectorMessagesAdapter = (VectorMessagesAdapter) mAdapter; if (vectorMessagesAdapter.isInSelectionMode()) { // cancel the selection mode. vectorMessagesAdapter.onEventTap(null); return; } Message message = JsonUtils.toMessage(event.getContent()); // video and images are displayed inside a medias slider. if (Message.MSGTYPE_IMAGE.equals(message.msgtype) || (Message.MSGTYPE_VIDEO.equals(message.msgtype))) { ArrayList<SlidableMediaInfo> mediaMessagesList = listSlidableMessages(); int listPosition = getMediaMessagePosition(mediaMessagesList, message); if (listPosition >= 0) { Intent viewImageIntent = new Intent(getActivity(), VectorMediasViewerActivity.class); viewImageIntent.putExtra(VectorMediasViewerActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_WIDTH, mAdapter.getMaxThumbnailWidth()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_HEIGHT, mAdapter.getMaxThumbnailHeight()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST, mediaMessagesList); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST_INDEX, listPosition); getActivity().startActivity(viewImageIntent); } } else if (Message.MSGTYPE_FILE.equals(message.msgtype) || Message.MSGTYPE_AUDIO.equals(message.msgtype)) { FileMessage fileMessage = JsonUtils.toFileMessage(event.getContent()); if (null != fileMessage.getUrl()) { onMediaAction(ACTION_VECTOR_OPEN, fileMessage.getUrl(), fileMessage.getMimeType(), fileMessage.body, fileMessage.file); } } else { // switch in section mode vectorMessagesAdapter.onEventTap(event.eventId); } } catch (Exception e) { Log.e(LOG_TAG, "## onContentClick() failed " + e.getMessage()); } } @Override public boolean onContentLongClick(int position) { return onRowLongClick(position); } @Override public void onAvatarClick(String userId) { try { Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); // in preview mode // the room is stored in a temporary store // so provide an handle to retrieve it if (null != getRoomPreviewData()) { roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_STORE_ID, new Integer(Matrix.getInstance(getActivity()).addTmpStore(mEventTimeLine.getStore()))); } roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId()); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); getActivity().startActivityForResult(roomDetailsIntent, VectorRoomActivity.GET_MENTION_REQUEST_CODE); } catch (Exception e) { Log.e(LOG_TAG, "## onAvatarClick() failed " + e.getMessage()); } } @Override public boolean onAvatarLongClick(String userId) { if (getActivity() instanceof VectorRoomActivity) { try { RoomState state = mRoom.getLiveState(); if (null != state) { String displayName = state.getMemberName(userId); if (!TextUtils.isEmpty(displayName)) { ((VectorRoomActivity) getActivity()).insertUserDisplayNameInTextEditor(displayName); } } } catch (Exception e) { Log.e(LOG_TAG, "## onAvatarLongClick() failed " + e.getMessage()); } } return true; } @Override public void onSenderNameClick(String userId, String displayName) { if (getActivity() instanceof VectorRoomActivity) { try { ((VectorRoomActivity) getActivity()).insertUserDisplayNameInTextEditor(displayName); } catch (Exception e) { Log.e(LOG_TAG, "## onSenderNameClick() failed " + e.getMessage()); } } } @Override public void onMediaDownloaded(int position) { } @Override public void onMoreReadReceiptClick(String eventId) { try { FragmentManager fm = getActivity().getSupportFragmentManager(); VectorReadReceiptsDialogFragment fragment = (VectorReadReceiptsDialogFragment) fm.findFragmentByTag(TAG_FRAGMENT_RECEIPTS_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } fragment = VectorReadReceiptsDialogFragment.newInstance(mSession.getMyUserId(), mRoom.getRoomId(), eventId); fragment.show(fm, TAG_FRAGMENT_RECEIPTS_DIALOG); } catch (Exception e) { Log.e(LOG_TAG, "## onMoreReadReceiptClick() failed " + e.getMessage()); } } @Override public void onURLClick(Uri uri) { try { if (null != uri) { HashMap<String, String> universalParams = VectorUniversalLinkReceiver.parseUniversalLink(uri); if (null != universalParams) { // open the member sheet from the current activity if (universalParams.containsKey(VectorUniversalLinkReceiver.ULINK_MATRIX_USER_ID_KEY)) { Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, universalParams.get(VectorUniversalLinkReceiver.ULINK_MATRIX_USER_ID_KEY)); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); getActivity().startActivityForResult(roomDetailsIntent, VectorRoomActivity.GET_MENTION_REQUEST_CODE); } else { // pop to the home activity Intent intent = new Intent(getActivity(), VectorHomeActivity.class); intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(VectorHomeActivity.EXTRA_JUMP_TO_UNIVERSAL_LINK, uri); getActivity().startActivity(intent); } } else { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, getActivity().getPackageName()); getActivity().startActivity(intent); } } } catch (Exception e) { Log.e(LOG_TAG, "## onURLClick() failed " + e.getMessage()); } } @Override public void onMatrixUserIdClick(final String userId) { try { // start member details UI Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId()); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); startActivity(roomDetailsIntent); } catch (Exception e) { Log.e(LOG_TAG, "## onMatrixUserIdClick() failed " + e.getMessage()); } } @Override public void onRoomAliasClick(String roomAlias) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomAlias, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomAliasClick failed " + e.getLocalizedMessage()); } } @Override public void onRoomIdClick(String roomId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomId, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } @Override public void onMessageIdClick(String messageId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(mRoom.getRoomId(), messageId))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } private int mInvalidIndexesCount = 0; @Override public void onInvalidIndexes() { mInvalidIndexesCount++; // it should happen once // else we assume that the adapter is really corrupted // It seems better to close the linked activity to avoid infinite refresh. if (1 == mInvalidIndexesCount) { mMessageListView.post(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } else { mMessageListView.post(new Runnable() { @Override public void run() { if (null != getActivity()) { getActivity().finish(); } } }); } } private final HashMap<String, Boolean> mHighlightStatusByEventId = new HashMap<>(); @Override public boolean shouldHighlightEvent(Event event) { // sanity check if ((null == event) || (null == event.eventId)) { return false; } String eventId = event.eventId; Boolean status = mHighlightStatusByEventId.get(eventId); if (null != status) { return status; } boolean res = (null != mSession.getDataHandler().getBingRulesManager().fulfilledHighlightBingRule(event)); mHighlightStatusByEventId.put(eventId, res); return res; } }
Reduce the number of messsages list refreshes
vector/src/main/java/im/vector/fragments/VectorMessageListFragment.java
Reduce the number of messsages list refreshes
<ide><path>ector/src/main/java/im/vector/fragments/VectorMessageListFragment.java <ide> * @param isEncrypted true when the room is encrypted <ide> */ <ide> public void setIsRoomEncrypted(boolean isEncrypted) { <del> ((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted = isEncrypted; <del> mAdapter.notifyDataSetChanged(); <add> if (((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted != isEncrypted) { <add> ((VectorMessagesAdapter) mAdapter).mIsRoomEncrypted = isEncrypted; <add> mAdapter.notifyDataSetChanged(); <add> } <ide> } <ide> <ide> /**
JavaScript
mit
669afc07c0f60b6099a205a6044f74d35b2c6f1a
0
fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg,fieldenms/tg
import '/resources/polymer/@polymer/polymer/polymer-legacy.js'; import '/resources/polymer/@polymer/iron-flex-layout/iron-flex-layout.js'; import '/resources/polymer/@polymer/iron-flex-layout/iron-flex-layout-classes.js'; import "/resources/polymer/@polymer/paper-styles/shadow.js"; import '/resources/element_loader/tg-element-loader.js'; import { Polymer } from '/resources/polymer/@polymer/polymer/lib/legacy/polymer-fn.js'; import { html } from '/resources/polymer/@polymer/polymer/lib/utils/html-tag.js'; import { IronResizableBehavior } from '/resources/polymer/@polymer/iron-resizable-behavior/iron-resizable-behavior.js'; const template = html` <style> :host { @apply --layout-vertical; } :host(:focus) { outline: none; } .view { background-color: white; } .master-insertion-point { overflow: auto; @apply --layout-vertical; } .master-container { border-radius: 2px; overflow: hidden; background-color: white; max-height: 100%; @apply --layout-vertical; @apply --shadow-elevation-2dp; } </style> <style include="iron-flex iron-flex-reverse iron-flex-alignment iron-flex-factors iron-positioning paper-material-styles"></style> <template is="dom-if" if="[[menuItem.view]]" restamp> <template is="dom-if" if="[[!_isCentre(menuItem)]]" on-dom-change="_viewWasDefined" restamp> <div class="master-container" id="customViewContainer"> <div class="master-insertion-point"> <tg-element-loader id="elementToLoad" class="layout vertical" style="min-height:0;" auto="[[autoLoad]]" import="[[menuItem.view.htmlImport]]" element-name="[[menuItem.view.elementName]]" attrs="[[menuItem.view.attrs]]" on-after-load="_afterLoadListener"></tg-element-loader> </div> </div> </template> <template is="dom-if" if="[[_isCentre(menuItem)]]" on-dom-change="_viewWasDefined" restamp> <tg-element-loader id="elementToLoad" auto="[[autoLoad]]" import="[[menuItem.view.htmlImport]]" element-name="[[menuItem.view.elementName]]" attrs="[[menuItem.view.attrs]]" on-after-load="_afterLoadListener"></tg-element-loader> </template> </template> <template is="dom-if" if="[[!menuItem.view]]" on-dom-change="_viewWasDefined" restamp> <div class="view"> Please specify view for <span>[[menuItem.key]]</span>. </div> </template>`; function isPropertyDefined (obj, property) { var dotIndex = property.indexOf("."); var firstProp; if (!obj) { return false; } else if (dotIndex < 0) { return !!obj[property] } else { firstProp = property.substr(0, dotIndex); return isPropertyDefined(obj[firstProp], property.slice(dotIndex + 1)) } }; Polymer({ _template: template, is: "tg-menu-item-view", properties: { menuItem: Object, autoLoad: { type: Boolean, value: false, reflectToAttribute: true }, moduleId: String, submoduleId: String, prefDim: { type: Object, observer: "_prefDimChanged" } }, behaviors: [IronResizableBehavior], hostAttributes: { "tabindex": "0" }, // ready: function () { // This setting could be helpful in case where master / centre views will need to be supported. // this._afterInitLoading = true; // }, attached: function () { var self = this; self.async(function () { if (isPropertyDefined(self, "menuItem.view.attrs")) { self.menuItem.view.attrs.uuid = self.moduleId + (self.submoduleId ? '/' + self.submoduleId : ''); self.menuItem.view.attrs.moduleId = self.moduleId; } }, 1); }, focusLoadedView: function () { var elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad && elementToLoad.wasLoaded && typeof elementToLoad.loadedElement.focusView === 'function') { elementToLoad.loadedElement.focusView(); } }, _isCentre: function (menuItem) { return menuItem.view.viewType === 'centre'; }, _afterLoadListener: function (e, detail, view) { var self = this; if (e.target === this.shadowRoot.querySelector("#elementToLoad")) { if (this.menuItem.view.viewType === 'centre') { const oldPostRetrieved = detail.postRetrieved; detail.postRetrieved = function (entity, bindingEntity, customObject) { if (oldPostRetrieved) { oldPostRetrieved(entity, bindingEntity, customObject); } detail._setQueryParams(); if (detail.autoRun || detail.queryPart) { detail.run(!detail.queryPart); // identify autoRunning situation only in case where centre has autoRun as true but does not represent 'link' centre (has no URI criteria values) delete detail.queryPart; } self.fire("menu-item-view-loaded", self.menuItem); detail.postRetrieved = oldPostRetrieved; }; detail.retrieve().catch(error => {}); } else if (this.menuItem.view.viewType === 'master') { detail.postRetrieved = function (entity, bindingEntity, customObject) { self.fire("menu-item-view-loaded", self.menuItem); }; detail.postValidated = function (validatedEntity, bindingEntity, customObject) {}; detail.postSaved = function (potentiallySavedOrNewEntity, newBindingEntity) {}; detail.retrieve().then(function(ironRequest) { if (detail.saveOnActivation === true) { return detail.save(); // saving promise } return Promise.resolve(ironRequest); // retrieval promise; resolves immediately }).catch(error => {}); } else { self.fire("menu-item-view-loaded", self.menuItem); } } }, /** * The callback that is invoked after template was defined and it's dom was changed. */ _viewWasDefined: function (e, detail) { var elementToLoad; if (this._afterInitLoading) { elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad) { if (!elementToLoad.wasLoaded) { elementToLoad.load(); } delete this._afterInitLoading; } } }, _setQueryIfPossible: function (queryPart) { if (this.menuItem.view.viewType === "centre" && queryPart) { this.menuItem.view.attrs.queryPart = queryPart; } }, _prefDimChanged: function (prefDim, oldPrefDim) { if (prefDim && !this._isCentre(this.menuItem)) { const width = (typeof prefDim.width === 'function' ? prefDim.width() : prefDim.width) + prefDim.widthUnit; const height = (typeof prefDim.height === 'function' ? prefDim.height() : prefDim.height) + prefDim.heightUnit; const viewContainer = this.shadowRoot.querySelector("#customViewContainer"); viewContainer.style.width = width; viewContainer.style.height = height; } }, load: function (queryPart) { const elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad && !elementToLoad.wasLoaded) { this._setQueryIfPossible(queryPart); elementToLoad.load(); } }, wasLoaded: function () { const elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad) { return elementToLoad.wasLoaded; } return true; }, canLeave: function () { const elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad && elementToLoad.wasLoaded && typeof elementToLoad.loadedElement.canLeave === 'function') { return elementToLoad.loadedElement.canLeave(); } return undefined; } });
platform-web-ui/src/main/web/ua/com/fielden/platform/web/views/tg-menu-item-view.js
import '/resources/polymer/@polymer/polymer/polymer-legacy.js'; import '/resources/polymer/@polymer/iron-flex-layout/iron-flex-layout.js'; import '/resources/polymer/@polymer/iron-flex-layout/iron-flex-layout-classes.js'; import "/resources/polymer/@polymer/paper-styles/shadow.js"; import '/resources/element_loader/tg-element-loader.js'; import { Polymer } from '/resources/polymer/@polymer/polymer/lib/legacy/polymer-fn.js'; import { html } from '/resources/polymer/@polymer/polymer/lib/utils/html-tag.js'; import { IronResizableBehavior } from '/resources/polymer/@polymer/iron-resizable-behavior/iron-resizable-behavior.js'; const template = html` <style> :host { @apply --layout-vertical; } :host(:focus) { outline: none; } .view { background-color: white; } .master-insertion-point { overflow: auto; @apply --layout-vertical; } .master-container { border-radius: 2px; overflow: hidden; background-color: white; max-height: 100%; @apply --layout-vertical; @apply --shadow-elevation-2dp; } </style> <style include="iron-flex iron-flex-reverse iron-flex-alignment iron-flex-factors iron-positioning paper-material-styles"></style> <template is="dom-if" if="[[menuItem.view]]" restamp> <template is="dom-if" if="[[!_isCentre(menuItem)]]" on-dom-change="_viewWasDefined" restamp> <div class="master-container" id="customViewContainer"> <div class="master-insertion-point"> <tg-element-loader id="elementToLoad" class="layout vertical" style="min-height:0;" auto="[[autoLoad]]" import="[[menuItem.view.htmlImport]]" element-name="[[menuItem.view.elementName]]" attrs="[[menuItem.view.attrs]]" on-after-load="_afterLoadListener"></tg-element-loader> </div> </div> </template> <template is="dom-if" if="[[_isCentre(menuItem)]]" on-dom-change="_viewWasDefined" restamp> <tg-element-loader id="elementToLoad" auto="[[autoLoad]]" import="[[menuItem.view.htmlImport]]" element-name="[[menuItem.view.elementName]]" attrs="[[menuItem.view.attrs]]" on-after-load="_afterLoadListener"></tg-element-loader> </template> </template> <template is="dom-if" if="[[!menuItem.view]]" on-dom-change="_viewWasDefined" restamp> <div class="view"> Please specify view for <span>[[menuItem.key]]</span>. </div> </template>`; function isPropertyDefined (obj, property) { var dotIndex = property.indexOf("."); var firstProp; if (!obj) { return false; } else if (dotIndex < 0) { return !!obj[property] } else { firstProp = property.substr(0, dotIndex); return isPropertyDefined(obj[firstProp], property.slice(dotIndex + 1)) } }; Polymer({ _template: template, is: "tg-menu-item-view", properties: { menuItem: Object, autoLoad: { type: Boolean, value: false, reflectToAttribute: true }, moduleId: String, submoduleId: String, prefDim: { type: Object, observer: "_prefDimChanged" } }, behaviors: [IronResizableBehavior], hostAttributes: { "tabindex": "0" }, // ready: function () { // This setting could be helpful in case where master / centre views will need to be supported. // this._afterInitLoading = true; // }, attached: function () { var self = this; self.async(function () { if (isPropertyDefined(self, "menuItem.view.attrs")) { self.menuItem.view.attrs.uuid = self.moduleId + (self.submoduleId ? '/' + self.submoduleId : ''); self.menuItem.view.attrs.moduleId = self.moduleId; } }, 1); }, focusLoadedView: function () { var elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad && elementToLoad.wasLoaded && typeof elementToLoad.loadedElement.focusView === 'function') { elementToLoad.loadedElement.focusView(); } }, _isCentre: function (menuItem) { return menuItem.view.viewType === 'centre'; }, _afterLoadListener: function (e, detail, view) { var self = this; if (e.target === this.shadowRoot.querySelector("#elementToLoad")) { if (this.menuItem.view.viewType === 'centre') { const oldPostRetrieved = detail.postRetrieved; detail.postRetrieved = function (entity, bindingEntity, customObject) { if (oldPostRetrieved) { oldPostRetrieved(entity, bindingEntity, customObject); } detail._setQueryParams(); if (detail.autoRun || detail.queryPart) { detail.run(!detail.queryPart); // identify autoRunning situation only in case where centre has autoRun as true but does not represent 'link' centre (has no URI criteria values) delete detail.queryPart; } self.fire("menu-item-view-loaded", self.menuItem); detail.postRetrieved = oldPostRetrieved; }; detail.retrieve(); } else if (this.menuItem.view.viewType === 'master') { detail.postRetrieved = function (entity, bindingEntity, customObject) { self.fire("menu-item-view-loaded", self.menuItem); }; detail.postValidated = function (validatedEntity, bindingEntity, customObject) {}; detail.postSaved = function (potentiallySavedOrNewEntity, newBindingEntity) {}; detail.retrieve().then(function(ironRequest) { if (detail.saveOnActivation === true) { return detail.save(); // saving promise } return Promise.resolve(ironRequest); // retrieval promise; resolves immediately }); } else { self.fire("menu-item-view-loaded", self.menuItem); } } }, /** * The callback that is invoked after template was defined and it's dom was changed. */ _viewWasDefined: function (e, detail) { var elementToLoad; if (this._afterInitLoading) { elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad) { if (!elementToLoad.wasLoaded) { elementToLoad.load(); } delete this._afterInitLoading; } } }, _setQueryIfPossible: function (queryPart) { if (this.menuItem.view.viewType === "centre" && queryPart) { this.menuItem.view.attrs.queryPart = queryPart; } }, _prefDimChanged: function (prefDim, oldPrefDim) { if (prefDim && !this._isCentre(this.menuItem)) { const width = (typeof prefDim.width === 'function' ? prefDim.width() : prefDim.width) + prefDim.widthUnit; const height = (typeof prefDim.height === 'function' ? prefDim.height() : prefDim.height) + prefDim.heightUnit; const viewContainer = this.shadowRoot.querySelector("#customViewContainer"); viewContainer.style.width = width; viewContainer.style.height = height; } }, load: function (queryPart) { const elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad && !elementToLoad.wasLoaded) { this._setQueryIfPossible(queryPart); elementToLoad.load(); } }, wasLoaded: function () { const elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad) { return elementToLoad.wasLoaded; } return true; }, canLeave: function () { const elementToLoad = this.shadowRoot.querySelector("#elementToLoad"); if (elementToLoad && elementToLoad.wasLoaded && typeof elementToLoad.loadedElement.canLeave === 'function') { return elementToLoad.loadedElement.canLeave(); } return undefined; } });
#1554 Made errors on retrieve for centres and masters on tg-menu-item-view more readable
platform-web-ui/src/main/web/ua/com/fielden/platform/web/views/tg-menu-item-view.js
#1554 Made errors on retrieve for centres and masters on tg-menu-item-view more readable
<ide><path>latform-web-ui/src/main/web/ua/com/fielden/platform/web/views/tg-menu-item-view.js <ide> self.fire("menu-item-view-loaded", self.menuItem); <ide> detail.postRetrieved = oldPostRetrieved; <ide> }; <del> detail.retrieve(); <add> detail.retrieve().catch(error => {}); <ide> } else if (this.menuItem.view.viewType === 'master') { <ide> detail.postRetrieved = function (entity, bindingEntity, customObject) { <ide> self.fire("menu-item-view-loaded", self.menuItem); <ide> return detail.save(); // saving promise <ide> } <ide> return Promise.resolve(ironRequest); // retrieval promise; resolves immediately <del> }); <add> }).catch(error => {}); <ide> } else { <ide> self.fire("menu-item-view-loaded", self.menuItem); <ide> }
Java
apache-2.0
ba1c8e7c5c0bc2f36ed56f864ace0cabf8544016
0
asymmetric/jstun2
package de.javawi.jstun.test.demo; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import de.javawi.jstun.attribute.exception.MessageAttributeException; import de.javawi.jstun.header.exception.MessageHeaderParsingException; import de.javawi.jstun.header.exception.MessageTypeException; import de.javawi.jstun.test.BindingRequestTest; import de.javawi.jstun.util.UtilityException; public class BindingRequestDemo implements Runnable { private static final Logger logger = Logger.getLogger("de.javawi.jstun"); InetAddress local; String stunServer; //= "numb.viagenie.ca"; int port = 3478; public BindingRequestDemo(InetAddress localAddress, String stunServer, int port) { this.local = localAddress; this.stunServer = stunServer; this.port = port; } public void run() { try { BindingRequestTest br = new BindingRequestTest(local, stunServer, port); br.test(); } catch (SocketException e) { logger.severe(local + ": Socket Exception: "+e.getMessage()); // TODO or simply e? } catch (UnknownHostException e) { logger.severe(local+": Unknown host: "+e.getMessage()); } catch (UtilityException e) { logger.severe(local+": Utility Exception: "+e.getMessage()); } catch (MessageHeaderParsingException e) { logger.severe(local+": MessageHeader Parsing Exception: "+e.getMessage()); } catch (MessageAttributeException e) { logger.severe(local+": Attribute Parsing Exception: "+e.getMessage()); } catch (IOException e) { logger.severe(local+": IO Exception: "+e.getMessage()); } catch (MessageTypeException e) { logger.severe(local+": Message Type Exception" + e.getMessage()); } } public static void main(String args[]) { try { Handler fh = new FileHandler("bindingreq.log"); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); logger.setLevel(Level.ALL); String stunserver = "numb.viagenie.ca"; int port = 3478; Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while( ifaces.hasMoreElements() ) { NetworkInterface iface = ifaces.nextElement(); Enumeration<InetAddress> iadds = iface.getInetAddresses(); while (iadds.hasMoreElements()) { InetAddress iadd = iadds.nextElement(); if (!iadd.isLoopbackAddress() && !iadd.isLoopbackAddress()) { Thread t = new Thread(new BindingRequestDemo(iadd, stunserver, port)); t.start(); } } } logger.fine("Tests run"); // TODO remove } catch (SecurityException e) { logger.warning("Warning: no logging permissions"); } catch (IOException e) { logger.warning("Warning: IO error prevented logger from starting"); } } }
src/de/javawi/jstun/test/demo/BindingRequestDemo.java
package de.javawi.jstun.test.demo; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import de.javawi.jstun.attribute.exception.MessageAttributeException; import de.javawi.jstun.header.exception.MessageHeaderParsingException; import de.javawi.jstun.header.exception.MessageTypeException; import de.javawi.jstun.test.BindingRequestTest; import de.javawi.jstun.util.UtilityException; public class BindingRequestDemo implements Runnable { private static final Logger logger = Logger.getLogger("de.javawi.jstun"); InetAddress local; String stunServer = "biascica.pipps.net"; int port = 3478; public BindingRequestDemo(InetAddress localAddress, String stunServer, int port) { this.local = localAddress; this.stunServer = stunServer; this.port = port; } public void run() { try { BindingRequestTest br = new BindingRequestTest(local, stunServer, port); br.test(); } catch (SocketException e) { logger.severe(local + ": Socket Exception: "+e.getMessage()); // TODO or simply e? } catch (UnknownHostException e) { logger.severe(local+": Unknown host: "+e.getMessage()); } catch (UtilityException e) { logger.severe(local+": Utility Exception: "+e.getMessage()); } catch (MessageHeaderParsingException e) { logger.severe(local+": MessageHeader Parsing Exception: "+e.getMessage()); } catch (MessageAttributeException e) { logger.severe(local+": Attribute Parsing Exception: "+e.getMessage()); } catch (IOException e) { logger.severe(local+": IO Exception: "+e.getMessage()); } catch (MessageTypeException e) { logger.severe(local+": Message Type Exception" + e.getMessage()); } } public static void main(String args[]) { try { Handler fh = new FileHandler("bindingreq.log"); fh.setFormatter(new SimpleFormatter()); logger.addHandler(fh); logger.setLevel(Level.ALL); String stunserver = "biascica.pipps.net"; int port = 3478; Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); while( ifaces.hasMoreElements() ) { NetworkInterface iface = ifaces.nextElement(); Enumeration<InetAddress> iadds = iface.getInetAddresses(); while (iadds.hasMoreElements()) { InetAddress iadd = iadds.nextElement(); if (!iadd.isLoopbackAddress() && !iadd.isLoopbackAddress()) { Thread t = new Thread(new BindingRequestDemo(iadd, stunserver, port)); t.start(); } } } logger.fine("Tests run"); // TODO remove } catch (SecurityException e) { logger.warning("Warning: no logging permissions"); } catch (IOException e) { logger.warning("Warning: IO error prevented logger from starting"); } } }
small bugfix
src/de/javawi/jstun/test/demo/BindingRequestDemo.java
small bugfix
<ide><path>rc/de/javawi/jstun/test/demo/BindingRequestDemo.java <ide> private static final Logger logger = Logger.getLogger("de.javawi.jstun"); <ide> <ide> InetAddress local; <del> String stunServer = "biascica.pipps.net"; <add> String stunServer; //= "numb.viagenie.ca"; <ide> int port = 3478; <ide> <ide> public BindingRequestDemo(InetAddress localAddress, String stunServer, int port) { <ide> logger.addHandler(fh); <ide> logger.setLevel(Level.ALL); <ide> <del> String stunserver = "biascica.pipps.net"; <add> String stunserver = "numb.viagenie.ca"; <ide> int port = 3478; <ide> <ide> Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
Java
bsd-2-clause
4026695dbc09cfaaff4bf29b68c8fdedb59ef6c6
0
TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej,biovoxxel/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.updater.core; import imagej.updater.core.Conflicts.Conflict; import imagej.updater.core.Conflicts.Resolution; import imagej.updater.core.FileObject.Status; import imagej.updater.util.Progress; import imagej.updater.util.AbstractProgressable; import imagej.updater.util.Util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.zip.ZipException; /** * A class to checksum and timestamp all the files shown in the Updater's UI. * * @author Johannes Schindelin * @author Yap Chin Kiet */ public class Checksummer extends AbstractProgressable { private FilesCollection files; private int counter, total; private Map<String, FileObject.Version> cachedChecksums; private boolean isWindows; // time tax for Redmont private Map<String, List<StringAndFile>> queue; public Checksummer(final FilesCollection files, final Progress progress) { this.files = files; if (progress != null) addProgress(progress); setTitle("Checksummer"); isWindows = Util.getPlatform().startsWith("win"); } protected static class StringAndFile { private String path; private File file; public long timestamp; public String checksum; StringAndFile(final String path, final File file) { this.path = path; this.file = file; } } public Map<String, FileObject.Version> getCachedChecksums() { return cachedChecksums; } /* follows symlinks */ protected boolean exists(final File file) { try { return file.getCanonicalFile().exists(); } catch (final IOException e) { files.log.error(e); } return false; } public void queueDir(final String[] dirs, final String[] extensions) { final Set<String> set = new HashSet<String>(); for (final String extension : extensions) set.add(extension); for (final String dir : dirs) queueDir(dir, set); } public void queueDir(final String dir, final Set<String> extensions) { File file = files.prefix(dir); if (!exists(file)) return; for (final String item : file.list()) { final String path = dir + "/" + item; file = files.prefix(path); if (item.startsWith(".")) continue; if (file.isDirectory()) { queueDir(path, extensions); continue; } if (!extensions.contains("")) { final int dot = item.lastIndexOf('.'); if (dot < 0 || !extensions.contains(item.substring(dot))) continue; } if (exists(file)) queue(path, file); } } protected void queueIfExists(final String path) { final File file = files.prefix(path); if (file.exists()) queue(path, file); } protected void queue(final String path) { queue(path, files.prefix(path)); } protected void queue(final String path, final File file) { String unversioned = FileObject.getFilename(path, true); if (!queue.containsKey(unversioned)) queue.put(unversioned, new ArrayList<StringAndFile>()); queue.get(unversioned).add(new StringAndFile(path, file)); } /** * Handle a single component, adding conflicts if there are multiple * versions. * * @param unversioned * the unversioned name of the component */ protected void handle(final String unversioned) { final List<StringAndFile> pairs = queue.get(unversioned); for (final StringAndFile pair : pairs) { addItem(pair.path); if (pair.file.exists()) try { pair.timestamp = Util.getTimestamp(pair.file); pair.checksum = getDigest(pair.path, pair.file, pair.timestamp); } catch (final ZipException e) { files.log.error("Problem digesting " + pair.file); } catch (final Exception e) { files.log.error(e); } counter += (int) pair.file.length(); itemDone(pair.path); setCount(counter, total); } if (pairs.size() == 1) { handle(pairs.get(0)); return; } // there are multiple versions of the same component; StringAndFile pair = null; FileObject object = files.get(unversioned); if (object == null || object.isObsolete()) { // the component is local-only; fall back to using the newest one for (StringAndFile p : pairs) if (pair == null || (p.file.lastModified() > pair.file.lastModified() && pair.path.equals(FileObject.getFilename(pair.path, true)))) pair = p; final List<File> obsoletes = new ArrayList<File>(); for (StringAndFile p : pairs) if (p != pair) obsoletes.add(p.file); addConflict(pair.path, "", false, obsoletes); } else { // let's find out whether there are obsoletes or locally-modified versions final List<StringAndFile> upToDates = new ArrayList<StringAndFile>(); final List<StringAndFile> obsoletes = new ArrayList<StringAndFile>(); final List<StringAndFile> locallyModifieds = new ArrayList<StringAndFile>(); for (final StringAndFile p : pairs) { if (object.current.checksum.equals(p.checksum)) upToDates.add(p); else if (object.hasPreviousVersion(p.checksum)) obsoletes.add(p); else locallyModifieds.add(p); } Comparator<StringAndFile> comparator = new Comparator<StringAndFile>() { @Override public int compare(StringAndFile a, StringAndFile b) { long diff = a.file.lastModified() - b.file.lastModified(); return diff < 0 ? +1 : diff > 0 ? -1 : 0; } }; Collections.sort(upToDates, comparator); Collections.sort(obsoletes, comparator); Collections.sort(locallyModifieds, comparator); if (upToDates.size() > 0) pair = pickNewest(upToDates); else if (obsoletes.size() > 0) pair = pickNewest(obsoletes); else pair = pickNewest(locallyModifieds); if (locallyModifieds.size() > 0) addConflict(pair.path, "locally-modified", true, convert(locallyModifieds)); if (obsoletes.size() > 0) addConflict(pair.path, "obsolete", false, convert(obsoletes)); if (upToDates.size() > 0) addConflict(pair.path, "up-to-date", false, convert(upToDates)); } handle(pair); } protected static StringAndFile pickNewest(final List<StringAndFile> list) { int index = 0; if (list.size() > 1) { final String filename = list.get(0).path; if (filename.equals(FileObject.getFilename(filename, true))) index++; } final StringAndFile result = list.get(index); list.remove(index); return result; } protected static List<File> convert(final List<StringAndFile> pairs) { final List<File> result = new ArrayList<File>(); for (final StringAndFile pair : pairs) result.add(pair.file); return result; } protected void addConflict(final String filename, String adjective, boolean isCritical, final List<File> toDelete) { if (!adjective.equals("") && !adjective.endsWith(" ")) adjective += " "; String conflictMessage = "Multiple " + adjective + "versions of " + filename + " exist: " + Util.join(", ", toDelete); Resolution ignore = new Resolution("Ignore for now") { @Override public void resolve() { removeConflict(filename); } }; Resolution delete = new Resolution("Delete!") { @Override public void resolve() { for (final File file : toDelete) file.delete(); removeConflict(filename); } }; files.conflicts.add(new Conflict(true, isCritical, filename, conflictMessage, ignore, delete)); } protected void removeConflict(final String filename) { if (files.conflicts == null) return; Iterator<Conflict> iterator = files.conflicts.iterator(); while (iterator.hasNext()) { Conflict conflict = iterator.next(); if (conflict.filename.equals(filename)) { iterator.remove(); return; } } } protected void handle(final StringAndFile pair) { if (pair.checksum != null) { FileObject object = files.get(pair.path); if (object == null) { object = new FileObject(null, pair.path, pair.file.length(), pair.checksum, pair.timestamp, Status.LOCAL_ONLY); if ((!isWindows && Util.canExecute(pair.file)) || pair.path.endsWith(".exe")) object.executable = true; tryToGuessPlatform(object); files.add(object); } else { if (!object.hasPreviousVersion(pair.checksum)) { final FileObject.Version obsoletes = cachedChecksums.get(":" + pair.checksum); if (obsoletes != null) { for (final String obsolete : obsoletes.checksum.split(":")) { if (object.hasPreviousVersion(obsolete)) { pair.checksum = obsolete; break; } } } } object.setLocalVersion(pair.path, pair.checksum, pair.timestamp); if (object.getStatus() == Status.OBSOLETE_UNINSTALLED) object .setStatus(Status.OBSOLETE); } if (pair.path.endsWith((".jar"))) try { POMParser.fillMetadataFromJar(object, pair.file); } catch (Exception e) { files.log.error("Could not read pom.xml from " + pair.path); } } else { final FileObject object = files.get(pair.path); if (object != null) { switch (object.getStatus()) { case OBSOLETE: case OBSOLETE_MODIFIED: object.setStatus(Status.OBSOLETE_UNINSTALLED); break; case INSTALLED: case MODIFIED: case UPDATEABLE: object.setStatus(Status.NOT_INSTALLED); break; case LOCAL_ONLY: files.remove(pair.path); break; case NEW: case NOT_INSTALLED: case OBSOLETE_UNINSTALLED: // leave as-is break; default: throw new RuntimeException("Unhandled status!"); } } } } protected void handleQueue() { total = 0; for (final String unversioned : queue.keySet()) for (final StringAndFile pair : queue.get(unversioned)) total += (int) pair.file.length(); counter = 0; for (final String unversioned : queue.keySet()) handle(unversioned); done(); writeCachedChecksums(); } public void updateFromLocal(final List<String> files) { queue = new LinkedHashMap<String, List<StringAndFile>>(); for (final String file : files) queue(file); handleQueue(); } protected boolean tryToGuessPlatform(final FileObject file) { // Look for platform names as subdirectories of lib/ and mm/ String platform; if (file.executable) { platform = Util.platformForLauncher(file.filename); if (platform == null) return false; } else { if (file.filename.startsWith("lib/")) platform = file.filename.substring(4); else if (file.filename.startsWith("mm/")) platform = file.filename.substring(3); else return false; final int slash = platform.indexOf('/'); if (slash < 0) return false; platform = platform.substring(0, slash); } if (platform.equals("linux")) platform = "linux32"; for (final String valid : files.util.platforms) if (platform.equals(valid)) { file.addPlatform(platform); return true; } return false; } public static final String[][] directories = { { "jars", "retro", "misc" }, { ".jar", ".class" }, { "plugins" }, { ".jar", ".class", ".txt", ".ijm", ".py", ".rb", ".clj", ".js", ".bsh" }, { "scripts" }, { ".py", ".rb", ".clj", ".js", ".bsh", ".m" }, { "macros" }, { ".txt", ".ijm" }, { "luts" }, { ".lut" }, { "images" }, { ".png" }, { "lib" }, { "" }, { "mm" }, { "" }, { "mmautofocus" }, { "" }, { "mmplugins" }, { "" } }; protected static final Map<String, Set<String>> extensions; static { extensions = new HashMap<String, Set<String>>(); for (int i = 0; i < directories.length; i += 2) { final Set<String> set = new HashSet<String>(); for (final String extension : directories[i + 1]) set.add(extension); for (final String dir : directories[i + 1]) extensions.put(dir, set); } } public boolean isCandidate(String path) { path = path.replace('\\', '/'); // Microsoft time toll final int slash = path.indexOf('/'); if (slash < 0) return files.util.isLauncher(path); final Set<String> exts = extensions.get(path.substring(0, slash)); final int dot = path.lastIndexOf('.'); return exts == null || dot < 0 ? false : exts.contains(path.substring(dot)); } protected void initializeQueue() { queue = new LinkedHashMap<String, List<StringAndFile>>(); for (final String launcher : files.util.launchers) queueIfExists(launcher); for (int i = 0; i < directories.length; i += 2) queueDir(directories[i], directories[i + 1]); for (final FileObject file : files) if (!queue.containsKey(file.getFilename(true))) queue(file.getFilename()); } public void updateFromLocal() { initializeQueue(); handleQueue(); } protected void readCachedChecksums() { cachedChecksums = new TreeMap<String, FileObject.Version>(); final File file = files.prefix(".checksums"); if (!file.exists()) return; try { final BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) try { final int space = line.indexOf(' '); if (space < 0) continue; final String checksum = line.substring(0, space); final int space2 = line.indexOf(' ', space + 1); if (space2 < 0) continue; final long timestamp = Long.parseLong(line.substring(space + 1, space2)); final String filename = line.substring(space2 + 1); cachedChecksums.put(filename, new FileObject.Version(checksum, timestamp)); } catch (final NumberFormatException e) { /* ignore line */ } reader.close(); } catch (final IOException e) { // ignore } } protected void writeCachedChecksums() { if (cachedChecksums == null) return; final File file = files.prefix(".checksums"); // file.canWrite() not applicable, as the file need not exist try { final Writer writer = new FileWriter(file); for (final String filename : cachedChecksums.keySet()) if (filename.startsWith(":") || files.prefix(filename).exists()) { final FileObject.Version version = cachedChecksums.get(filename); writer.write(version.checksum + " " + version.timestamp + " " + filename + "\n"); } writer.close(); } catch (final IOException e) { // ignore } } protected String getDigest(final String path, final File file, final long timestamp) throws IOException, NoSuchAlgorithmException, ZipException { if (cachedChecksums == null) readCachedChecksums(); FileObject.Version version = cachedChecksums.get(path); if (version == null || timestamp != version.timestamp) { final String checksum = path.equals("plugins/Fiji_Updater.jar") ? Util.getJarDigest(file, false, false, false) : Util.getDigest(path, file); version = new FileObject.Version(checksum, timestamp); cachedChecksums.put(path, version); } if (!cachedChecksums.containsKey(":" + version.checksum)) { final List<String> obsoletes = Util.getObsoleteDigests(path, file); if (obsoletes != null) { final StringBuilder builder = new StringBuilder(); for (final String obsolete : obsoletes) { if (builder.length() > 0) builder.append(':'); builder.append(obsolete); } cachedChecksums.put(":" + version.checksum, new FileObject.Version( builder.toString(), timestamp)); } } return version.checksum; } }
core/updater/core/src/main/java/imagej/updater/core/Checksummer.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.updater.core; import imagej.updater.core.Conflicts.Conflict; import imagej.updater.core.Conflicts.Resolution; import imagej.updater.core.FileObject.Status; import imagej.updater.util.Progress; import imagej.updater.util.AbstractProgressable; import imagej.updater.util.Util; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.zip.ZipException; /** * A class to checksum and timestamp all the files shown in the Updater's UI. * * @author Johannes Schindelin * @author Yap Chin Kiet */ public class Checksummer extends AbstractProgressable { private FilesCollection files; private int counter, total; private Map<String, FileObject.Version> cachedChecksums; private boolean isWindows; // time tax for Redmont private Map<String, List<StringAndFile>> queue; public Checksummer(final FilesCollection files, final Progress progress) { this.files = files; if (progress != null) addProgress(progress); setTitle("Checksummer"); isWindows = Util.getPlatform().startsWith("win"); } protected static class StringAndFile { private String path; private File file; public long timestamp; public String checksum; StringAndFile(final String path, final File file) { this.path = path; this.file = file; } } public Map<String, FileObject.Version> getCachedChecksums() { return cachedChecksums; } /* follows symlinks */ protected boolean exists(final File file) { try { return file.getCanonicalFile().exists(); } catch (final IOException e) { files.log.error(e); } return false; } public void queueDir(final String[] dirs, final String[] extensions) { final Set<String> set = new HashSet<String>(); for (final String extension : extensions) set.add(extension); for (final String dir : dirs) queueDir(dir, set); } public void queueDir(final String dir, final Set<String> extensions) { File file = files.prefix(dir); if (!exists(file)) return; for (final String item : file.list()) { final String path = dir + "/" + item; file = files.prefix(path); if (item.startsWith(".")) continue; if (file.isDirectory()) { queueDir(path, extensions); continue; } if (!extensions.contains("")) { final int dot = item.lastIndexOf('.'); if (dot < 0 || !extensions.contains(item.substring(dot))) continue; } if (exists(file)) queue(path, file); } } protected void queueIfExists(final String path) { final File file = files.prefix(path); if (file.exists()) queue(path, file); } protected void queue(final String path) { queue(path, files.prefix(path)); } protected void queue(final String path, final File file) { String unversioned = FileObject.getFilename(path, true); if (!queue.containsKey(unversioned)) queue.put(unversioned, new ArrayList<StringAndFile>()); queue.get(unversioned).add(new StringAndFile(path, file)); } /** * Handle a single component, adding conflicts if there are multiple * versions. * * @param unversioned * the unversioned name of the component */ protected void handle(final String unversioned) { final List<StringAndFile> pairs = queue.get(unversioned); for (final StringAndFile pair : pairs) { addItem(pair.path); if (pair.file.exists()) try { pair.timestamp = Util.getTimestamp(pair.file); pair.checksum = getDigest(pair.path, pair.file, pair.timestamp); } catch (final ZipException e) { files.log.error("Problem digesting " + pair.file); } catch (final Exception e) { files.log.error(e); } counter += (int) pair.file.length(); itemDone(pair.path); setCount(counter, total); } if (pairs.size() == 1) { handle(pairs.get(0)); return; } // there are multiple versions of the same component; StringAndFile pair = null; FileObject object = files.get(unversioned); if (object == null || object.isObsolete()) { // the component is local-only; fall back to using the newest one for (StringAndFile p : pairs) if (pair == null || (p.file.lastModified() > pair.file.lastModified() && pair.path.equals(FileObject.getFilename(pair.path, true)))) pair = p; final List<File> obsoletes = new ArrayList<File>(); for (StringAndFile p : pairs) if (p != pair) obsoletes.add(p.file); addConflict(pair.path, "", false, obsoletes); } else { // let's find out whether there are obsoletes or locally-modified versions final List<StringAndFile> upToDates = new ArrayList<StringAndFile>(); final List<StringAndFile> obsoletes = new ArrayList<StringAndFile>(); final List<StringAndFile> locallyModifieds = new ArrayList<StringAndFile>(); for (final StringAndFile p : pairs) { if (object.current.checksum.equals(p.checksum)) upToDates.add(p); else if (object.hasPreviousVersion(p.checksum)) obsoletes.add(p); else locallyModifieds.add(p); } Comparator<StringAndFile> comparator = new Comparator<StringAndFile>() { @Override public int compare(StringAndFile a, StringAndFile b) { long diff = a.file.lastModified() - b.file.lastModified(); return diff < 0 ? +1 : diff > 0 ? -1 : 0; } }; Collections.sort(upToDates, comparator); Collections.sort(obsoletes, comparator); Collections.sort(locallyModifieds, comparator); if (upToDates.size() > 0) pair = pickNewest(upToDates); else if (obsoletes.size() > 0) pair = pickNewest(obsoletes); else pair = pickNewest(locallyModifieds); if (locallyModifieds.size() > 0) addConflict(pair.path, "locally-modified", true, convert(locallyModifieds)); if (obsoletes.size() > 0) addConflict(pair.path, "obsolete", false, convert(obsoletes)); if (upToDates.size() > 0) addConflict(pair.path, "up-to-date", false, convert(upToDates)); } handle(pair); } protected static StringAndFile pickNewest(final List<StringAndFile> list) { int index = 0; if (list.size() > 1) { final String filename = list.get(0).path; if (filename.equals(FileObject.getFilename(filename, true))) index++; } final StringAndFile result = list.get(index); list.remove(index); return result; } protected static List<File> convert(final List<StringAndFile> pairs) { final List<File> result = new ArrayList<File>(); for (final StringAndFile pair : pairs) result.add(pair.file); return result; } protected void addConflict(final String filename, String adjective, boolean isCritical, final List<File> toDelete) { if (!adjective.equals("") && !adjective.endsWith(" ")) adjective += " "; String conflictMessage = "Multiple " + adjective + "versions of " + filename + " exist: " + Util.join(", ", toDelete); Resolution ignore = new Resolution("Ignore for now") { @Override public void resolve() { removeConflict(filename); } }; Resolution delete = new Resolution("Delete!") { @Override public void resolve() { for (final File file : toDelete) file.delete(); removeConflict(filename); } }; files.conflicts.add(new Conflict(true, isCritical, filename, conflictMessage, ignore, delete)); } protected void removeConflict(final String filename) { if (files.conflicts == null) return; Iterator<Conflict> iterator = files.conflicts.iterator(); while (iterator.hasNext()) { Conflict conflict = iterator.next(); if (conflict.filename.equals(filename)) { iterator.remove(); return; } } } protected void handle(final StringAndFile pair) { if (pair.checksum != null) { FileObject object = files.get(pair.path); if (object == null) { object = new FileObject(null, pair.path, pair.file.length(), pair.checksum, pair.timestamp, Status.LOCAL_ONLY); if ((!isWindows && Util.canExecute(pair.file)) || pair.path.endsWith(".exe")) object.executable = true; tryToGuessPlatform(object); files.add(object); } else { if (!object.hasPreviousVersion(pair.checksum)) { final FileObject.Version obsoletes = cachedChecksums.get(":" + pair.checksum); if (obsoletes != null) { for (final String obsolete : obsoletes.checksum.split(":")) { if (object.hasPreviousVersion(obsolete)) { pair.checksum = obsolete; break; } } } } object.setLocalVersion(pair.path, pair.checksum, pair.timestamp); if (object.getStatus() == Status.OBSOLETE_UNINSTALLED) object .setStatus(Status.OBSOLETE); } if (pair.path.endsWith((".jar"))) try { POMParser.fillMetadataFromJar(object, pair.file); } catch (Exception e) { files.log.error("Could not read pom.xml from " + pair.path); } } else { final FileObject object = files.get(pair.path); if (object != null) { switch (object.getStatus()) { case OBSOLETE: case OBSOLETE_MODIFIED: object.setStatus(Status.OBSOLETE_UNINSTALLED); break; case INSTALLED: case MODIFIED: case UPDATEABLE: object.setStatus(Status.NOT_INSTALLED); break; case LOCAL_ONLY: files.remove(pair.path); break; case NEW: case NOT_INSTALLED: case OBSOLETE_UNINSTALLED: // leave as-is break; default: throw new RuntimeException("Unhandled status!"); } } } } protected void handleQueue() { total = 0; for (final String unversioned : queue.keySet()) for (final StringAndFile pair : queue.get(unversioned)) total += (int) pair.file.length(); counter = 0; for (final String unversioned : queue.keySet()) handle(unversioned); done(); writeCachedChecksums(); } public void updateFromLocal(final List<String> files) { queue = new LinkedHashMap<String, List<StringAndFile>>(); for (final String file : files) queue(file); handleQueue(); } protected boolean tryToGuessPlatform(final FileObject file) { // Look for platform names as subdirectories of lib/ and mm/ String platform; if (file.executable) { platform = Util.platformForLauncher(file.filename); if (platform == null) return false; } else { if (file.filename.startsWith("lib/")) platform = file.filename.substring(4); else if (file.filename.startsWith("mm/")) platform = file.filename.substring(3); else return false; final int slash = platform.indexOf('/'); if (slash < 0) return false; platform = platform.substring(0, slash); } if (platform.equals("linux")) platform = "linux32"; for (final String valid : files.util.platforms) if (platform.equals(valid)) { file.addPlatform(platform); return true; } return false; } public static final String[][] directories = { { "jars", "retro", "misc" }, { ".jar", ".class" }, { "plugins" }, { ".jar", ".class", ".txt", ".ijm", ".py", ".rb", ".clj", ".js", ".bsh" }, { "scripts" }, { ".py", ".rb", ".clj", ".js", ".bsh", ".m" }, { "macros" }, { ".txt", ".ijm" }, { "luts" }, { ".lut" }, { "images" }, { ".png" }, { "lib" }, { "" }, { "mm" }, { "" }, { "mmautofocus" }, { "" }, { "mmplugins" }, { "" } }; protected static final Map<String, Set<String>> extensions; static { extensions = new HashMap<String, Set<String>>(); for (int i = 0; i < directories.length; i += 2) { final Set<String> set = new HashSet<String>(); for (final String extension : directories[i + 1]) set.add(extension); for (final String dir : directories[i + 1]) extensions.put(dir, set); } } public boolean isCandidate(String path) { path = path.replace('\\', '/'); // Microsoft time toll final int slash = path.indexOf('/'); if (slash < 0) return files.util.isLauncher(path); final Set<String> exts = extensions.get(path.substring(0, slash)); final int dot = path.lastIndexOf('.'); return exts == null || dot < 0 ? false : exts.contains(path.substring(dot)); } protected void initializeQueue() { queue = new LinkedHashMap<String, List<StringAndFile>>(); for (final String launcher : files.util.launchers) queueIfExists(launcher); for (int i = 0; i < directories.length; i += 2) queueDir(directories[i], directories[i + 1]); for (final FileObject file : files) if (!queue.containsKey(file.getFilename(true))) queue(file.getFilename()); } public void updateFromLocal() { initializeQueue(); handleQueue(); } protected void readCachedChecksums() { cachedChecksums = new TreeMap<String, FileObject.Version>(); final File file = files.prefix(".checksums"); if (!file.exists()) return; try { final BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) try { final int space = line.indexOf(' '); if (space < 0) continue; final String checksum = line.substring(0, space); final int space2 = line.indexOf(' ', space + 1); if (space2 < 0) continue; final long timestamp = Long.parseLong(line.substring(space + 1, space2)); final String filename = line.substring(space2 + 1); cachedChecksums.put(filename, new FileObject.Version(checksum, timestamp)); } catch (final NumberFormatException e) { /* ignore line */ } reader.close(); } catch (final IOException e) { // ignore } } protected void writeCachedChecksums() { if (cachedChecksums == null) return; final File file = files.prefix(".checksums"); // file.canWrite() not applicable, as the file need not exist try { final Writer writer = new FileWriter(file); for (final String filename : cachedChecksums.keySet()) if (filename.startsWith(":") || files.prefix(filename).exists()) { final FileObject.Version version = cachedChecksums.get(filename); writer.write(version.checksum + " " + version.timestamp + " " + filename + "\n"); } writer.close(); } catch (final IOException e) { // ignore } } protected String getDigest(final String path, final File file, final long timestamp) throws IOException, NoSuchAlgorithmException, ZipException { if (cachedChecksums == null) readCachedChecksums(); FileObject.Version version = cachedChecksums.get(path); if (version == null || timestamp != version.timestamp) { final String checksum = path.equals("plugins/Fiji_Updater.jar") ? Util.getJarDigest(file, false, false, false) : Util.getDigest(path, file); version = new FileObject.Version(checksum, timestamp); cachedChecksums.put(path, version); } if (!cachedChecksums.containsKey(":" + version.checksum)) { final List<String> obsoletes = Util.getObsoleteDigests(path, file); if (obsoletes != null) { final StringBuilder builder = new StringBuilder(); for (final String obsolete : obsoletes) { if (builder.length() > 0) builder.append(':'); builder.append(obsolete); } cachedChecksums.put(":" + version.checksum, new FileObject.Version( builder.toString(), timestamp)); } } return version.checksum; } }
Checksummer: format the directories more obviously Signed-off-by: Johannes Schindelin <[email protected]>
core/updater/core/src/main/java/imagej/updater/core/Checksummer.java
Checksummer: format the directories more obviously
<ide><path>ore/updater/core/src/main/java/imagej/updater/core/Checksummer.java <ide> return false; <ide> } <ide> <del> public static final String[][] directories = { { "jars", "retro", "misc" }, <del> { ".jar", ".class" }, { "plugins" }, <del> { ".jar", ".class", ".txt", ".ijm", ".py", ".rb", ".clj", ".js", ".bsh" }, <del> { "scripts" }, { ".py", ".rb", ".clj", ".js", ".bsh", ".m" }, { "macros" }, <del> { ".txt", ".ijm" }, { "luts" }, { ".lut" }, { "images" }, { ".png" }, <del> { "lib" }, { "" }, { "mm" }, { "" }, { "mmautofocus" }, { "" }, <del> { "mmplugins" }, { "" } }; <add> public static final String[][] directories = { <add> { "jars", "retro", "misc" }, { ".jar", ".class" }, <add> { "plugins" }, { ".jar", ".class", ".txt", ".ijm", ".py", ".rb", ".clj", ".js", ".bsh" }, <add> { "scripts" }, { ".py", ".rb", ".clj", ".js", ".bsh", ".m" }, <add> { "macros" }, { ".txt", ".ijm" }, <add> { "luts" }, { ".lut" }, <add> { "images" }, { ".png" }, <add> { "lib" }, { "" }, <add> { "mm" }, { "" }, <add> { "mmautofocus" }, { "" }, <add> { "mmplugins" }, { "" } <add> }; <ide> <ide> protected static final Map<String, Set<String>> extensions; <ide>
Java
agpl-3.0
44470cca294360c2381bb6cc311eb5692d5ab5dd
0
lat-lon/deegree-securityproxy
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2011 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.securityproxy.service.commons.responsefilter.clipping; import static org.apache.commons.io.IOUtils.closeQuietly; import static org.apache.commons.io.IOUtils.write; import static org.deegree.securityproxy.service.commons.responsefilter.ResponseFilterUtils.copyBufferedStream; import static org.deegree.securityproxy.service.commons.responsefilter.ResponseFilterUtils.isException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.deegree.securityproxy.authentication.ows.raster.GeometryFilterInfo; import org.deegree.securityproxy.authentication.ows.raster.RasterUser; import org.deegree.securityproxy.filter.StatusCodeResponseBodyWrapper; import org.deegree.securityproxy.request.OwsRequest; import org.deegree.securityproxy.responsefilter.ResponseFilterException; import org.deegree.securityproxy.responsefilter.ResponseFilterManager; import org.deegree.securityproxy.responsefilter.logging.ResponseClippingReport; import org.deegree.securityproxy.service.commons.responsefilter.clipping.exception.ClippingException; import org.deegree.securityproxy.service.commons.responsefilter.clipping.geometry.GeometryRetriever; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTWriter; /** * Provides filtering of {@link OwsRequest}s. * * @author <a href="mailto:[email protected]">Dirk Stenger</a> * @author last edited by: $Author: stenger $ * * @version $Revision: $, $Date: $ */ public abstract class AbstractClippingResponseFilterManager implements ResponseFilterManager { public static final String REQUEST_AREA_HEADER_KEY = "request_area"; public static final String NOT_A_CORRECT_REQUEST_MSG = "Request was not a GetCoverage- or GetMap-Request - clipping not required."; public static final String SERVICE_EXCEPTION_MSG = "Response is a ServiceException."; public static final int DEFAULT_STATUS_CODE = 500; public static final String DEFAULT_BODY = "Clipping failed!"; private static final Logger LOG = Logger.getLogger( AbstractClippingResponseFilterManager.class ); protected final String exceptionBody; protected final int exceptionStatusCode; @Autowired private GeometryRetriever geometryRetriever; @Autowired private ImageClipper imageClipper; /** * Instantiates a new {@link AbstractClippingResponseFilterManager} with default exception body (DEFAULT_BODY) and * status code (DEFAULT_STATUS_CODE). */ public AbstractClippingResponseFilterManager() { this.exceptionBody = DEFAULT_BODY; this.exceptionStatusCode = DEFAULT_STATUS_CODE; } /** * Instantiates a new {@link AbstractClippingResponseFilterManager} with the passed exception body and status code. * * @param pathToExceptionFile * if null or not available, the default exception body (DEFAULT_BODY) is used * @param exceptionStatusCode * the exception status code */ public AbstractClippingResponseFilterManager( String pathToExceptionFile, int exceptionStatusCode ) { this.exceptionBody = readExceptionBodyFromFile( pathToExceptionFile ); this.exceptionStatusCode = exceptionStatusCode; } @Override public ResponseClippingReport filterResponse( StatusCodeResponseBodyWrapper servletResponse, OwsRequest request, Authentication auth ) throws ResponseFilterException { checkParameters( servletResponse, request ); if ( canBeFiltered( request ) ) { LOG.info( "Apply filter for response of request " + request ); try { if ( isException( servletResponse ) ) { LOG.debug( "Response contains an exception!" ); copyBufferedStream( servletResponse ); return new ResponseClippingReport( SERVICE_EXCEPTION_MSG ); } Geometry clippingGeometry = retrieveGeometryUsedForClipping( auth, request ); return processClippingAndAddHeaderInfo( servletResponse, clippingGeometry ); } catch ( ParseException e ) { LOG.error( "Calculating clipped result image failed!", e ); writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } catch ( IOException e ) { LOG.error( "Calculating clipped result image failed!", e ); writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } } LOG.debug( "Request was not a GetCoverage request. Will be ignored by this filter manager!" ); copyBufferedStream( servletResponse ); return new ResponseClippingReport( NOT_A_CORRECT_REQUEST_MSG ); } @Override public boolean canBeFiltered( OwsRequest request ) { checkIfRequestEqualsNull( request ); return isCorrectRequestType( request ) && isCorrectRequest( request ); } /** * @param request * never <code>null</code> * @return true if request is from the supported type */ protected abstract boolean isCorrectRequestType( OwsRequest request ); /** * @param owsRequest * never <code>null</code> * @return true if request is a supported request */ protected abstract boolean isCorrectRequest( OwsRequest owsRequest ); /** * * @param request * never <code>null</code> * @return layer name */ protected abstract String retrieveLayerName( OwsRequest request ); private void checkIfRequestEqualsNull( OwsRequest request ) { if ( request == null ) throw new IllegalArgumentException( "Request must not be null!" ); } private void checkParameters( HttpServletResponse servletResponse, OwsRequest request ) { if ( servletResponse == null ) throw new IllegalArgumentException( "Parameter servletResponse may not be null!" ); if ( request == null ) throw new IllegalArgumentException( "Parameter request may not be null!" ); if ( !isCorrectRequestType( request ) ) throw new IllegalArgumentException( "OwsRequest of class " + request.getClass().getCanonicalName() + " is not supported!" ); } private ResponseClippingReport processClippingAndAddHeaderInfo( StatusCodeResponseBodyWrapper servletResponse, Geometry clippingGeometry ) throws IOException { try { InputStream imageAsStream = servletResponse.getBufferedStream(); ByteArrayOutputStream destination = new ByteArrayOutputStream(); ResponseClippingReport clippedImageReport = imageClipper.calculateClippedImage( imageAsStream, clippingGeometry, destination ); addHeaderInfoIfNoFailureOccurred( servletResponse, clippedImageReport ); // required to set the header (must be set BEFORE any data is written to the response) destination.writeTo( servletResponse.getRealOutputStream() ); return clippedImageReport; } catch ( ClippingException e ) { writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } } private void writeExceptionBodyAndSetExceptionStatusCode( StatusCodeResponseBodyWrapper servletResponse ) { try { OutputStream destination = servletResponse.getRealOutputStream(); writeExceptionBodyAndSetExceptionStatusCode( servletResponse, destination ); } catch ( IOException e ) { LOG.error( "An error occurred during writing the exception response!", e ); } } private void writeExceptionBodyAndSetExceptionStatusCode( StatusCodeResponseBodyWrapper servletResponse, OutputStream destination ) throws IOException { servletResponse.setStatus( exceptionStatusCode ); write( exceptionBody, destination ); } private Geometry retrieveGeometryUsedForClipping( Authentication auth, OwsRequest wcsRequest ) throws IllegalArgumentException, ParseException { RasterUser rasterUser = retrieveRasterUser( auth ); List<GeometryFilterInfo> geometryFilterInfos = rasterUser.getWcsGeometryFilterInfos(); String coverageName = retrieveLayerName( wcsRequest ); return geometryRetriever.retrieveGeometry( coverageName, geometryFilterInfos ); } private RasterUser retrieveRasterUser( Authentication auth ) { Object principal = auth.getPrincipal(); if ( !( principal instanceof RasterUser ) ) { throw new IllegalArgumentException( "Principal is not a WcsUser!" ); } return (RasterUser) principal; } private void addHeaderInfoIfNoFailureOccurred( StatusCodeResponseBodyWrapper servletResponse, ResponseClippingReport clippedImageReport ) { if ( noFailureOccured( clippedImageReport ) ) { WKTWriter writer = new WKTWriter(); String requestAreaWkt = writer.write( clippedImageReport.getReturnedVisibleArea() ); LOG.debug( "Add header '" + REQUEST_AREA_HEADER_KEY + "': " + requestAreaWkt ); servletResponse.addHeader( REQUEST_AREA_HEADER_KEY, requestAreaWkt ); } } private boolean noFailureOccured( ResponseClippingReport clippedImageReport ) { return clippedImageReport.getFailure() == null && clippedImageReport.getReturnedVisibleArea() != null; } protected String readExceptionBodyFromFile( String pathToExceptionFile ) { LOG.info( "Reading exception body from " + pathToExceptionFile ); if ( pathToExceptionFile != null && pathToExceptionFile.length() > 0 ) { InputStream exceptionAsStream = null; try { File exceptionFile = new File( pathToExceptionFile ); exceptionAsStream = new FileInputStream( exceptionFile ); return IOUtils.toString( exceptionAsStream ); } catch ( FileNotFoundException e ) { LOG.warn( "Could not read exception message from file: File not found! Defaulting to " + DEFAULT_BODY ); } catch ( IOException e ) { LOG.warn( "Could not read exception message from file. Defaulting to " + DEFAULT_BODY + "Reason: " + e.getMessage() ); } finally { closeQuietly( exceptionAsStream ); } } return DEFAULT_BODY; } }
deegree-securityproxy-service-commons/src/main/java/org/deegree/securityproxy/service/commons/responsefilter/clipping/AbstractClippingResponseFilterManager.java
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2011 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.securityproxy.service.commons.responsefilter.clipping; import static org.apache.commons.io.IOUtils.closeQuietly; import static org.apache.commons.io.IOUtils.write; import static org.deegree.securityproxy.service.commons.responsefilter.ResponseFilterUtils.copyBufferedStream; import static org.deegree.securityproxy.service.commons.responsefilter.ResponseFilterUtils.isException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.deegree.securityproxy.authentication.ows.raster.GeometryFilterInfo; import org.deegree.securityproxy.authentication.ows.raster.RasterUser; import org.deegree.securityproxy.filter.StatusCodeResponseBodyWrapper; import org.deegree.securityproxy.request.OwsRequest; import org.deegree.securityproxy.responsefilter.ResponseFilterException; import org.deegree.securityproxy.responsefilter.ResponseFilterManager; import org.deegree.securityproxy.responsefilter.logging.ResponseClippingReport; import org.deegree.securityproxy.service.commons.responsefilter.clipping.exception.ClippingException; import org.deegree.securityproxy.service.commons.responsefilter.clipping.geometry.GeometryRetriever; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTWriter; /** * Provides filtering of {@link OwsRequest}s. * * @author <a href="mailto:[email protected]">Dirk Stenger</a> * @author last edited by: $Author: stenger $ * * @version $Revision: $, $Date: $ */ public abstract class AbstractClippingResponseFilterManager implements ResponseFilterManager { public static final String REQUEST_AREA_HEADER_KEY = "request_area"; public static final String NOT_A_CORRECT_REQUEST_MSG = "Request was not a GetCoverage- or GetMap-Request - clipping not required."; public static final String SERVICE_EXCEPTION_MSG = "Response is a ServiceException."; public static final int DEFAULT_STATUS_CODE = 500; public static final String DEFAULT_BODY = "Clipping failed!"; private static final Logger LOG = Logger.getLogger( AbstractClippingResponseFilterManager.class ); protected final String exceptionBody; protected final int exceptionStatusCode; @Autowired private GeometryRetriever geometryRetriever; @Autowired private ImageClipper imageClipper; /** * Instantiates a new {@link AbstractClippingResponseFilterManager} with default exception body (DEFAULT_BODY) and * status code (DEFAULT_STATUS_CODE). */ public AbstractClippingResponseFilterManager() { this.exceptionBody = DEFAULT_BODY; this.exceptionStatusCode = DEFAULT_STATUS_CODE; } /** * Instantiates a new {@link AbstractClippingResponseFilterManager} with the passed exception body and status code. * * @param pathToExceptionFile * if null or not available, the default exception body (DEFAULT_BODY) is used * @param exceptionStatusCode * the exception status code */ public AbstractClippingResponseFilterManager( String pathToExceptionFile, int exceptionStatusCode ) { this.exceptionBody = readExceptionBodyFromFile( pathToExceptionFile ); this.exceptionStatusCode = exceptionStatusCode; } @Override public ResponseClippingReport filterResponse( StatusCodeResponseBodyWrapper servletResponse, OwsRequest request, Authentication auth ) throws ResponseFilterException { checkParameters( servletResponse, request ); if ( canBeFiltered( request ) ) { LOG.info( "Apply filter for response of request " + request ); try { if ( isException( servletResponse ) ) { LOG.debug( "Response contains an exception!" ); copyBufferedStream( servletResponse ); return new ResponseClippingReport( SERVICE_EXCEPTION_MSG ); } Geometry clippingGeometry = retrieveGeometryUseForClipping( auth, request ); return processClippingAndAddHeaderInfo( servletResponse, clippingGeometry ); } catch ( ParseException e ) { LOG.error( "Calculating clipped result image failed!", e ); writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } catch ( IOException e ) { LOG.error( "Calculating clipped result image failed!", e ); writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } } LOG.debug( "Request was not a GetCoverage request. Will be ignored by this filter manager!" ); copyBufferedStream( servletResponse ); return new ResponseClippingReport( NOT_A_CORRECT_REQUEST_MSG ); } @Override public boolean canBeFiltered( OwsRequest request ) { checkIfRequestEqualsNull( request ); return isCorrectRequestType( request ) && isCorrectRequest( request ); } /** * @param request * never <code>null</code> * @return true if request is from the supported type */ protected abstract boolean isCorrectRequestType( OwsRequest request ); /** * @param owsRequest * never <code>null</code> * @return true if request is a supported request */ protected abstract boolean isCorrectRequest( OwsRequest owsRequest ); /** * * @param request * never <code>null</code> * @return layer name */ protected abstract String retrieveLayerName( OwsRequest request ); private void checkIfRequestEqualsNull( OwsRequest request ) { if ( request == null ) throw new IllegalArgumentException( "Request must not be null!" ); } private void checkParameters( HttpServletResponse servletResponse, OwsRequest request ) { if ( servletResponse == null ) throw new IllegalArgumentException( "Parameter servletResponse may not be null!" ); if ( request == null ) throw new IllegalArgumentException( "Parameter request may not be null!" ); if ( !isCorrectRequestType( request ) ) throw new IllegalArgumentException( "OwsRequest of class " + request.getClass().getCanonicalName() + " is not supported!" ); } private ResponseClippingReport processClippingAndAddHeaderInfo( StatusCodeResponseBodyWrapper servletResponse, Geometry clippingGeometry ) throws IOException { try { InputStream imageAsStream = servletResponse.getBufferedStream(); ByteArrayOutputStream destination = new ByteArrayOutputStream(); ResponseClippingReport clippedImageReport = imageClipper.calculateClippedImage( imageAsStream, clippingGeometry, destination ); addHeaderInfoIfNoFailureOccurred( servletResponse, clippedImageReport ); // required to set the header (must be set BEFORE any data is written to the response) destination.writeTo( servletResponse.getRealOutputStream() ); return clippedImageReport; } catch ( ClippingException e ) { writeExceptionBodyAndSetExceptionStatusCode( servletResponse ); return new ResponseClippingReport( "" + e.getMessage() ); } } private void writeExceptionBodyAndSetExceptionStatusCode( StatusCodeResponseBodyWrapper servletResponse ) { try { OutputStream destination = servletResponse.getRealOutputStream(); writeExceptionBodyAndSetExceptionStatusCode( servletResponse, destination ); } catch ( IOException e ) { LOG.error( "An error occurred during writing the exception response!", e ); } } private void writeExceptionBodyAndSetExceptionStatusCode( StatusCodeResponseBodyWrapper servletResponse, OutputStream destination ) throws IOException { servletResponse.setStatus( exceptionStatusCode ); write( exceptionBody, destination ); } private Geometry retrieveGeometryUseForClipping( Authentication auth, OwsRequest wcsRequest ) throws IllegalArgumentException, ParseException { RasterUser wcsUser = retrieveWcsUser( auth ); List<GeometryFilterInfo> geometryFilterInfos = wcsUser.getWcsGeometryFilterInfos(); String coverageName = retrieveLayerName( wcsRequest ); return geometryRetriever.retrieveGeometry( coverageName, geometryFilterInfos ); } private RasterUser retrieveWcsUser( Authentication auth ) { Object principal = auth.getPrincipal(); if ( !( principal instanceof RasterUser ) ) { throw new IllegalArgumentException( "Principal is not a WcsUser!" ); } return (RasterUser) principal; } private void addHeaderInfoIfNoFailureOccurred( StatusCodeResponseBodyWrapper servletResponse, ResponseClippingReport clippedImageReport ) { if ( noFailureOccured( clippedImageReport ) ) { WKTWriter writer = new WKTWriter(); String requestAreaWkt = writer.write( clippedImageReport.getReturnedVisibleArea() ); LOG.debug( "Add header '" + REQUEST_AREA_HEADER_KEY + "': " + requestAreaWkt ); servletResponse.addHeader( REQUEST_AREA_HEADER_KEY, requestAreaWkt ); } } private boolean noFailureOccured( ResponseClippingReport clippedImageReport ) { return clippedImageReport.getFailure() == null && clippedImageReport.getReturnedVisibleArea() != null; } protected String readExceptionBodyFromFile( String pathToExceptionFile ) { LOG.info( "Reading exception body from " + pathToExceptionFile ); if ( pathToExceptionFile != null && pathToExceptionFile.length() > 0 ) { InputStream exceptionAsStream = null; try { File exceptionFile = new File( pathToExceptionFile ); exceptionAsStream = new FileInputStream( exceptionFile ); return IOUtils.toString( exceptionAsStream ); } catch ( FileNotFoundException e ) { LOG.warn( "Could not read exception message from file: File not found! Defaulting to " + DEFAULT_BODY ); } catch ( IOException e ) { LOG.warn( "Could not read exception message from file. Defaulting to " + DEFAULT_BODY + "Reason: " + e.getMessage() ); } finally { closeQuietly( exceptionAsStream ); } } return DEFAULT_BODY; } }
Minor refactorings of AbstractClippingResponseFilterManager
deegree-securityproxy-service-commons/src/main/java/org/deegree/securityproxy/service/commons/responsefilter/clipping/AbstractClippingResponseFilterManager.java
Minor refactorings of AbstractClippingResponseFilterManager
<ide><path>eegree-securityproxy-service-commons/src/main/java/org/deegree/securityproxy/service/commons/responsefilter/clipping/AbstractClippingResponseFilterManager.java <ide> copyBufferedStream( servletResponse ); <ide> return new ResponseClippingReport( SERVICE_EXCEPTION_MSG ); <ide> } <del> Geometry clippingGeometry = retrieveGeometryUseForClipping( auth, request ); <add> Geometry clippingGeometry = retrieveGeometryUsedForClipping( auth, request ); <ide> return processClippingAndAddHeaderInfo( servletResponse, clippingGeometry ); <ide> } catch ( ParseException e ) { <ide> LOG.error( "Calculating clipped result image failed!", e ); <ide> write( exceptionBody, destination ); <ide> } <ide> <del> private Geometry retrieveGeometryUseForClipping( Authentication auth, OwsRequest wcsRequest ) <add> private Geometry retrieveGeometryUsedForClipping( Authentication auth, OwsRequest wcsRequest ) <ide> throws IllegalArgumentException, ParseException { <del> RasterUser wcsUser = retrieveWcsUser( auth ); <del> List<GeometryFilterInfo> geometryFilterInfos = wcsUser.getWcsGeometryFilterInfos(); <add> RasterUser rasterUser = retrieveRasterUser( auth ); <add> List<GeometryFilterInfo> geometryFilterInfos = rasterUser.getWcsGeometryFilterInfos(); <ide> String coverageName = retrieveLayerName( wcsRequest ); <ide> return geometryRetriever.retrieveGeometry( coverageName, geometryFilterInfos ); <ide> } <ide> <del> private RasterUser retrieveWcsUser( Authentication auth ) { <add> private RasterUser retrieveRasterUser( Authentication auth ) { <ide> Object principal = auth.getPrincipal(); <ide> if ( !( principal instanceof RasterUser ) ) { <ide> throw new IllegalArgumentException( "Principal is not a WcsUser!" );
Java
apache-2.0
6fad274cb6189a9c9c36c5e3320ad73b8f4ed70f
0
bkosawa/android-app-recommendation
package br.com.kosawalabs.apprecommendation.presentation.list; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; 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.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.util.List; import br.com.kosawalabs.apprecommendation.R; import br.com.kosawalabs.apprecommendation.data.network.AppNetworkRepository; import br.com.kosawalabs.apprecommendation.data.pojo.App; import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailActivity; import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailFragment; import br.com.kosawalabs.apprecommendation.service.UploadMyAppsIService; import br.com.kosawalabs.apprecommendation.visual.ImageLoaderFacade; import static android.view.View.GONE; import static android.view.View.VISIBLE; import static br.com.kosawalabs.apprecommendation.MainApplication.EXTRAS_SESSION_TOKEN; public class AppListActivity extends AppCompatActivity implements AppListView, View.OnClickListener { private boolean mTwoPane; private boolean isRecommended; private AppListPresenterImpl presenter; private String token; private LinearLayoutManager layoutManager; private SimpleItemRecyclerViewAdapter listAdapter; private ProgressBar progress; private RecyclerView listFrame; private View errorFrame; private TextView errorDesc; private View sendDataFrame; private Button sendDataButton; public static void start(Activity activity, String token) { Intent intent = new Intent(activity, AppListActivity.class); intent.putExtra(EXTRAS_SESSION_TOKEN, token); activity.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(new MyBottomNavListener()); listFrame = (RecyclerView) findViewById(R.id.list_frame); assert listFrame != null; layoutManager = new LinearLayoutManager(this); listFrame.setLayoutManager(layoutManager); listFrame.addOnScrollListener(new AppListOnScrollListener()); if (findViewById(R.id.app_detail_container) != null) { mTwoPane = true; } progress = (ProgressBar) findViewById(R.id.progress_bar); errorFrame = findViewById(R.id.error_frame); errorDesc = (TextView) findViewById(R.id.list_error_description); sendDataFrame = findViewById(R.id.send_data_frame); sendDataButton = (Button) findViewById(R.id.send_data_button); sendDataButton.setOnClickListener(this); token = getIntent().getStringExtra(EXTRAS_SESSION_TOKEN); presenter = new AppListPresenterImpl(this, new AppNetworkRepository(token)); } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.update_my_apps: sendMyAppList(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { super.onResume(); refreshList(); } @Override public void showApps(List<App> apps) { progress.setVisibility(GONE); errorFrame.setVisibility(GONE); sendDataFrame.setVisibility(GONE); listFrame.setVisibility(VISIBLE); listAdapter = new SimpleItemRecyclerViewAdapter(apps); listFrame.setAdapter(listAdapter); } @Override public void showMoreApps(List<App> apps) { progress.setVisibility(GONE); errorFrame.setVisibility(GONE); sendDataFrame.setVisibility(GONE); listFrame.setVisibility(VISIBLE); listAdapter.setApps(apps); } @Override public void showError(String errorCause) { progress.setVisibility(GONE); listFrame.setVisibility(GONE); sendDataFrame.setVisibility(GONE); errorFrame.setVisibility(VISIBLE); errorDesc.setText(errorCause); } @Override public void showSendDataButton() { progress.setVisibility(GONE); listFrame.setVisibility(GONE); errorFrame.setVisibility(GONE); sendDataFrame.setVisibility(VISIBLE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.send_data_button: sendMyAppList(); return; } } private void refreshList() { if (presenter.shouldLoadMore()) { if (!isRecommended) { presenter.fetchFirstPage(); } else { presenter.fetchRecommendedFirstPage(); } } } private void loadMore() { if (!isRecommended) { presenter.fetchNextPage(); } else { presenter.fetchRecommendedNextPage(); } } private boolean listIsAtTheEnd() { int visibleItemCount = getVisibleItemCount(); int totalItemCount = getTotalItemCount(); int firstVisibleItemPosition = getFirstVisibleItemPosition(); return (visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0 && totalItemCount >= presenter.getPageSize(); } private int getVisibleItemCount() { return layoutManager.getChildCount(); } private int getTotalItemCount() { return layoutManager.getItemCount(); } private int getFirstVisibleItemPosition() { return layoutManager.findFirstVisibleItemPosition(); } private void sendMyAppList() { Toast.makeText(this, R.string.toast_sending_packages, Toast.LENGTH_SHORT).show(); UploadMyAppsIService.startActionUploadApps(this); } public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> { private final List<App> apps; public SimpleItemRecyclerViewAdapter(List<App> apps) { this.apps = apps; } public void setApps(List<App> moreApps) { this.apps.addAll(moreApps); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.app_list_content, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { App app = this.apps.get(position); holder.mItem = app; ImageLoaderFacade.loadImage(AppListActivity.this, app.getIconUrl(), holder.mIcon); holder.mName.setText(app.getName()); holder.mDeveloper.setText(String.valueOf(app.getDeveloperName())); holder.mCategory.setText(String.valueOf(app.getCategoryKey())); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mTwoPane) { Bundle arguments = new Bundle(); arguments.putInt(AppDetailFragment.ARG_ITEM_ID, holder.mItem.getId()); arguments.putString(EXTRAS_SESSION_TOKEN, token); AppDetailFragment fragment = new AppDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.app_detail_container, fragment) .commit(); } else { Context context = v.getContext(); Intent intent = new Intent(context, AppDetailActivity.class); Bundle arguments = new Bundle(); arguments.putInt(AppDetailFragment.ARG_ITEM_ID, holder.mItem.getId()); arguments.putString(EXTRAS_SESSION_TOKEN, token); intent.putExtras(arguments); context.startActivity(intent); } } }); } @Override public int getItemCount() { return this.apps.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; private final ImageView mIcon; public final TextView mName; private final TextView mDeveloper; private final TextView mCategory; public App mItem; public ViewHolder(View view) { super(view); mView = view; mIcon = (ImageView) view.findViewById(R.id.list_icon); mName = (TextView) view.findViewById(R.id.list_name); mDeveloper = (TextView) view.findViewById(R.id.list_developer); mCategory = (TextView) view.findViewById(R.id.list_category); } @Override public String toString() { return super.toString() + " '" + mName.getText() + "'"; } } } private class AppListOnScrollListener extends RecyclerView.OnScrollListener { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (presenter.shouldLoadMore()) { if (listIsAtTheEnd()) { loadMore(); } } } } private class MyBottomNavListener implements BottomNavigationView.OnNavigationItemSelectedListener { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.action_list: isRecommended = false; break; case R.id.action_list_recommended: isRecommended = true; break; default: return false; } refreshList(); return true; } } }
app/src/main/java/br/com/kosawalabs/apprecommendation/presentation/list/AppListActivity.java
package br.com.kosawalabs.apprecommendation.presentation.list; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; 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.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import java.util.List; import br.com.kosawalabs.apprecommendation.R; import br.com.kosawalabs.apprecommendation.data.network.AppNetworkRepository; import br.com.kosawalabs.apprecommendation.data.pojo.App; import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailActivity; import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailFragment; import br.com.kosawalabs.apprecommendation.service.UploadMyAppsIService; import static android.view.View.GONE; import static android.view.View.VISIBLE; import static br.com.kosawalabs.apprecommendation.MainApplication.EXTRAS_SESSION_TOKEN; public class AppListActivity extends AppCompatActivity implements AppListView, View.OnClickListener { private boolean mTwoPane; private boolean isRecommended; private AppListPresenterImpl presenter; private String token; private LinearLayoutManager layoutManager; private SimpleItemRecyclerViewAdapter listAdapter; private ProgressBar progress; private RecyclerView listFrame; private View errorFrame; private TextView errorDesc; private View sendDataFrame; private Button sendDataButton; public static void start(Activity activity, String token) { Intent intent = new Intent(activity, AppListActivity.class); intent.putExtra(EXTRAS_SESSION_TOKEN, token); activity.startActivity(intent); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_app_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle(getTitle()); final BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(new MyBottomNavListener()); listFrame = (RecyclerView) findViewById(R.id.list_frame); assert listFrame != null; layoutManager = new LinearLayoutManager(this); listFrame.setLayoutManager(layoutManager); listFrame.addOnScrollListener(new AppListOnScrollListener()); if (findViewById(R.id.app_detail_container) != null) { mTwoPane = true; } progress = (ProgressBar) findViewById(R.id.progress_bar); errorFrame = findViewById(R.id.error_frame); errorDesc = (TextView) findViewById(R.id.list_error_description); sendDataFrame = findViewById(R.id.send_data_frame); sendDataButton = (Button) findViewById(R.id.send_data_button); sendDataButton.setOnClickListener(this); token = getIntent().getStringExtra(EXTRAS_SESSION_TOKEN); presenter = new AppListPresenterImpl(this, new AppNetworkRepository(token)); } public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.update_my_apps: sendMyAppList(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { super.onResume(); refreshList(); } @Override public void showApps(List<App> apps) { progress.setVisibility(GONE); errorFrame.setVisibility(GONE); sendDataFrame.setVisibility(GONE); listFrame.setVisibility(VISIBLE); listAdapter = new SimpleItemRecyclerViewAdapter(apps); listFrame.setAdapter(listAdapter); } @Override public void showMoreApps(List<App> apps) { progress.setVisibility(GONE); errorFrame.setVisibility(GONE); sendDataFrame.setVisibility(GONE); listFrame.setVisibility(VISIBLE); listAdapter.setApps(apps); } @Override public void showError(String errorCause) { progress.setVisibility(GONE); listFrame.setVisibility(GONE); sendDataFrame.setVisibility(GONE); errorFrame.setVisibility(VISIBLE); errorDesc.setText(errorCause); } @Override public void showSendDataButton() { progress.setVisibility(GONE); listFrame.setVisibility(GONE); errorFrame.setVisibility(GONE); sendDataFrame.setVisibility(VISIBLE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.send_data_button: sendMyAppList(); return; } } private void refreshList() { if (presenter.shouldLoadMore()) { if (!isRecommended) { presenter.fetchFirstPage(); } else { presenter.fetchRecommendedFirstPage(); } } } private void loadMore() { if (!isRecommended) { presenter.fetchNextPage(); } else { presenter.fetchRecommendedNextPage(); } } private boolean listIsAtTheEnd() { int visibleItemCount = getVisibleItemCount(); int totalItemCount = getTotalItemCount(); int firstVisibleItemPosition = getFirstVisibleItemPosition(); return (visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0 && totalItemCount >= presenter.getPageSize(); } private int getVisibleItemCount() { return layoutManager.getChildCount(); } private int getTotalItemCount() { return layoutManager.getItemCount(); } private int getFirstVisibleItemPosition() { return layoutManager.findFirstVisibleItemPosition(); } private void sendMyAppList() { Toast.makeText(this, R.string.toast_sending_packages, Toast.LENGTH_SHORT).show(); UploadMyAppsIService.startActionUploadApps(this); } public class SimpleItemRecyclerViewAdapter extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> { private final List<App> apps; public SimpleItemRecyclerViewAdapter(List<App> apps) { this.apps = apps; } public void setApps(List<App> moreApps) { this.apps.addAll(moreApps); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.app_list_content, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mItem = this.apps.get(position); holder.mContentView.setText(this.apps.get(position).getName()); holder.mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mTwoPane) { Bundle arguments = new Bundle(); arguments.putInt(AppDetailFragment.ARG_ITEM_ID, holder.mItem.getId()); arguments.putString(EXTRAS_SESSION_TOKEN, token); AppDetailFragment fragment = new AppDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.app_detail_container, fragment) .commit(); } else { Context context = v.getContext(); Intent intent = new Intent(context, AppDetailActivity.class); Bundle arguments = new Bundle(); arguments.putInt(AppDetailFragment.ARG_ITEM_ID, holder.mItem.getId()); arguments.putString(EXTRAS_SESSION_TOKEN, token); intent.putExtras(arguments); context.startActivity(intent); } } }); } @Override public int getItemCount() { return this.apps.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final TextView mContentView; public App mItem; public ViewHolder(View view) { super(view); mView = view; mContentView = (TextView) view.findViewById(R.id.list_name); } @Override public String toString() { return super.toString() + " '" + mContentView.getText() + "'"; } } } private class AppListOnScrollListener extends RecyclerView.OnScrollListener { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (presenter.shouldLoadMore()) { if (listIsAtTheEnd()) { loadMore(); } } } } private class MyBottomNavListener implements BottomNavigationView.OnNavigationItemSelectedListener { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.action_list: isRecommended = false; break; case R.id.action_list_recommended: isRecommended = true; break; default: return false; } refreshList(); return true; } } }
Binding new list layout to content
app/src/main/java/br/com/kosawalabs/apprecommendation/presentation/list/AppListActivity.java
Binding new list layout to content
<ide><path>pp/src/main/java/br/com/kosawalabs/apprecommendation/presentation/list/AppListActivity.java <ide> import android.view.View; <ide> import android.view.ViewGroup; <ide> import android.widget.Button; <add>import android.widget.ImageView; <ide> import android.widget.ProgressBar; <ide> import android.widget.TextView; <ide> import android.widget.Toast; <ide> import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailActivity; <ide> import br.com.kosawalabs.apprecommendation.presentation.detail.AppDetailFragment; <ide> import br.com.kosawalabs.apprecommendation.service.UploadMyAppsIService; <add>import br.com.kosawalabs.apprecommendation.visual.ImageLoaderFacade; <ide> <ide> import static android.view.View.GONE; <ide> import static android.view.View.VISIBLE; <ide> <ide> @Override <ide> public void onBindViewHolder(final ViewHolder holder, int position) { <del> holder.mItem = this.apps.get(position); <del> holder.mContentView.setText(this.apps.get(position).getName()); <add> App app = this.apps.get(position); <add> holder.mItem = app; <add> ImageLoaderFacade.loadImage(AppListActivity.this, app.getIconUrl(), holder.mIcon); <add> holder.mName.setText(app.getName()); <add> holder.mDeveloper.setText(String.valueOf(app.getDeveloperName())); <add> holder.mCategory.setText(String.valueOf(app.getCategoryKey())); <ide> <ide> holder.mView.setOnClickListener(new View.OnClickListener() { <ide> @Override <ide> <ide> public class ViewHolder extends RecyclerView.ViewHolder { <ide> public final View mView; <del> public final TextView mContentView; <add> private final ImageView mIcon; <add> public final TextView mName; <add> private final TextView mDeveloper; <add> private final TextView mCategory; <ide> <ide> public App mItem; <ide> <ide> public ViewHolder(View view) { <ide> super(view); <ide> mView = view; <del> mContentView = (TextView) view.findViewById(R.id.list_name); <add> mIcon = (ImageView) view.findViewById(R.id.list_icon); <add> mName = (TextView) view.findViewById(R.id.list_name); <add> mDeveloper = (TextView) view.findViewById(R.id.list_developer); <add> mCategory = (TextView) view.findViewById(R.id.list_category); <ide> } <ide> <ide> @Override <ide> public String toString() { <del> return super.toString() + " '" + mContentView.getText() + "'"; <add> return super.toString() + " '" + mName.getText() + "'"; <ide> } <ide> } <ide>
JavaScript
unlicense
331de863135fa856c159f9f71283f94f342a47c0
0
wangyisong1996/Tomasulo_algorithm_simulator,wangyisong1996/Tomasulo_algorithm_simulator
var config; var utils; var ui; var CPU; var HDL; var CPU = (function() { console.log("loading CPU module"); var conf; var has_power = false; var cycles; var load_queue; var store_queue; var RS_add; var RS_mul; var FP_regs; var INT_regs; var memory; var instructions; var ui_ele; var PC; var memory_controller; var FP_adder; var FP_multiplier; var FP_divider; var WB_name; var WB_value; // TODO : drag these to config file // hardcoded memory size : 4096 const mem_size = 4096; const mem_bits = 12; var get_memory_module = () => { // memory submodule ... var mem; var do_load = () => { mem = []; mem.length = mem_size; }; // init from config var do_initialize = () => { for (var i = 0; i < mem_size; i++) { mem[i] = { value : 0.0, modified : false, signal : undefined }; } // load vals from config var values_list = conf.mem_vals.trim().split("\n"); values_list.forEach((s) => { var tmp = s.trim().split(" "); var addr = parseInt(tmp[0]); var val = parseFloat(tmp[1]); if (isNaN(addr) || isNaN(val)) return; if (addr < 0 || addr >= mem_size) return; mem_write(addr, val); }); }; var mem_write = (addr, val) => { // write memory if (addr < 0 || addr >= mem_size) { throw "invalid addr " + addr; } if (!mem[addr].modified) { // add this entry to ui mem[addr].modified = true; add_entry(addr); } mem[addr].value = val; mem[addr].signal.set(val); }; var mem_read = (addr) => { // read memory return mem[addr].value; }; var add_entry = (addr) => { var count = 0; for (var i = 0; i < addr; i++) { count += mem[i].modified ? 1 : 0; } var e = ui.add_memory_table_entry(count); HDL.signal(ui.update_func(e.addr)).set(addr); mem[addr].signal = HDL.signal(ui.update_func(e.val)); }; return { do_load : do_load, initialize : do_initialize, mem_read : mem_read, mem_write : mem_write }; }; var get_instructions_module = () => { var ins; var do_load = () => { ins = []; }; // init from config var do_initialize = () => { ins.length = 0; // load instructions from config var ins_list = conf.instructions.trim().split("\n"); ins_list.forEach((s) => { var tmp = parse_instruction(s); if (!tmp) { alert("Invalid instruction `" + s + "`"); return; } tmp.PC = ins.length; tmp.issue = ""; tmp.execution = ""; tmp.writeback = ""; // add this instruction to ui var tr = ui.add_instruction_queue_table_entry(); // console.log(tr); for (var i in tr) { tmp[i] = HDL.signal(ui.update_func(tr[i])).set(tmp[i]); } ins.push(tmp); }); }; var parse_int = (s) => { s = s.trim(); var x = parseInt(s); if (x + "" != s) { return undefined; } return x; }; var parse_FP_reg = (s) => { s = s.trim(); if (s[0] != "F") { return undefined; } var id = parse_int(s.substr(1)); if (isNaN(id)) { return undefined; } if (id < 0 || id >= conf.n_FP_registers) { return undefined; } return "F" + id; }; var parse_INT_reg = (s) => { s = s.trim(); if (s[0] != "R") { return undefined; } var id = parse_int(s.substr(1)); if (isNaN(id)) { return undefined; } if (id < 0 || id >= conf.n_INT_registers) { return undefined; } return "R" + id; }; var parse_addr = (s) => { s = s.trim(); var pos_1 = s.indexOf("("); var pos_2 = s.indexOf(")"); if (pos_1 == -1 || pos_2 == -1 || pos_1 > pos_2) { return undefined; } var offset = parse_int(s.substr(0, pos_1)); if (isNaN(offset)) { return undefined; } var reg = parse_INT_reg(s.substr(pos_1 + 1, pos_2 - pos_1 - 1)); if (!reg) { return undefined; } if (s.substr(pos_2 + 1).trim() != "") { return undefined; } return { offset : offset, reg : reg }; }; var parse_mem_arglist = (s) => { var l = s.split(","); if (l.length != 2) { return undefined; } var dest = parse_FP_reg(l[0]); if (!dest) { return undefined; } var source = parse_addr(l[1]); if (!source) { return undefined; } return { dest : dest, source : source }; }; var parse_arith_arglist = (s) => { var l = s.split(","); if (l.length != 3) { return undefined; } var dest = parse_FP_reg(l[0]); if (!dest) { return undefined; } var src1 = parse_FP_reg(l[1]); if (!src1) { return undefined; } var src2 = parse_FP_reg(l[2]); if (!src2) { return undefined; } return { dest : dest, src1 : src1, src2 : src2 }; }; var parse_instruction = (s) => { // returns: object -- name, dest, src1, src2 // (1) load / store { const names = ["LD", "ST"]; for (var i in names) { var name = names[i]; if (s.substr(0, name.length + 1) == name + " ") { var tmp = parse_mem_arglist(s.substr(name.length + 1)); if (!tmp) return undefined; return { name : name, dest : tmp.dest, src1 : tmp.source.offset, src2 : tmp.source.reg }; } } } // (2) add / sub / mul / div { const names = ["ADDD", "SUBD", "MULD", "DIVD"]; for (var i in names) { var name = names[i]; if (s.substr(0, name.length + 1) == name + " ") { var tmp = parse_arith_arglist(s.substr(name.length + 1)); if (!tmp) return undefined; return { name : name, dest : tmp.dest, src1 : tmp.src1, src2 : tmp.src2 }; } } } return undefined; }; var do_peek_name = () => { if (PC.val() >= ins.length) { return undefined; } else { return ins[PC.val()].name.val(); } }; var do_fetch = () => { PC.set(PC.val() + 1); var ret = ins[PC.val()]; ret.issue.set(cycles.val()); return ret; }; var do_set_execution = (id) => { ins[id].execution.set(cycles.val()); }; var do_set_writeback = (id) => { ins[id].writeback.set(cycles.val()); }; return { do_load : do_load, initialize : do_initialize, peek_name : do_peek_name, fetch : do_fetch, set_execution : do_set_execution, set_writeback : do_set_writeback }; }; var CPU_exec_id = 0; var CPU_exec_delay_time = 1000; // HDL-like CPU clock function var get_CPU_clock_func = function() { var id = ++CPU_exec_id; var load_queue_allocate = () => { for (var i in load_queue) { if (load_queue[i].busy.val() == "No" || load_queue[i].name == WB_name) { return load_queue[i]; } } return undefined; }; var store_queue_allocate = () => { for (var i in store_queue) { if (store_queue[i].busy.val() == "No" || store_queue[i].name == WB_name) { return store_queue[i]; } } return undefined; }; var RS_add_allocate = () => { for (var i in RS_add) { if (RS_add[i].busy.val() == "No" || RS_add[i].name == WB_name) { return RS_add[i]; } } return undefined; }; var RS_mul_allocate = () => { for (var i in RS_mul) { if (RS_mul[i].busy.val() == "No" || RS_mul[i].name == WB_name) { return RS_mul[i]; } } return undefined; }; var get_reg_value = (reg, V, Q) => { var reg_val = reg.val(); if (reg_val == WB_name) { // WB->IF fowarding V.set(WB_value); Q.set(""); } else if (isNaN(reg_val)) { // in a reservation station V.set(""); Q.set(reg_val); } else { // value get V.set(reg_val); Q.set(""); } }; var IF = () => { var ins_name = instructions.peek_name(); if (!ins_name) { // no more instruction return; } const ins_name_to_type = { LD : "load", ST : "store", ADDD : "add", SUBD : "add", MULD : "mul", DIVD : "mul" }; var ins_type = ins_name_to_type[ins_name]; // check if possible to issue the instruction if (ins_type == "load") { var e = load_queue_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.PC.set(ins.PC.val()); e.addr.set(ins.src1.val() + INT_regs[ins.src2.val()].val()); FP_regs[ins.dest.val()].set(e.name); // dest } if (ins_type == "store") { var e = store_queue_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.PC.set(ins.PC.val()); e.addr.set(ins.src1.val() + INT_regs[ins.src2.val()].val()); get_reg_value(FP_regs[ins.dest.val()], e.Vk, e.Qk); } if (ins_type == "add") { var e = RS_add_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.op.set(ins_name); e.PC.set(ins.PC.val()); get_reg_value(FP_regs[ins.src1.val()], e.Vj, e.Qj); // src1 get_reg_value(FP_regs[ins.src2.val()], e.Vk, e.Qk); // src2 FP_regs[ins.dest.val()].set(e.name); // dest } if (ins_type == "mul") { var e = RS_mul_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.op.set(ins_name); e.PC.set(ins.PC.val()); get_reg_value(FP_regs[ins.src1.val()], e.Vj, e.Qj); // src1 get_reg_value(FP_regs[ins.src2.val()], e.Vk, e.Qk); // src2 FP_regs[ins.dest.val()].set(e.name); // dest } }; var EXE_load_store = () => { // strictly in PC order if (memory_controller.is_running.val() == true) { // is running var t_r = memory_controller.t_remaining.val(); if (t_r == 1) { // done if (memory_controller.type.val() == "load") { // load : get XXX from mem var tmp = memory.mem_read(memory_controller.addr.val()); memory_controller.value.set(tmp); } else { // store : nothing to do ... } // mark as done memory_controller.t_remaining.set(0); instructions.set_execution(memory_controller.PC.val()); } else if (t_r > 1) { // working in progress memory_controller.t_remaining.set( memory_controller.t_remaining.val() - 1); } } // [immediately after CDB broadcast] if (memory_controller.is_running.val() == false || memory_controller.name.val() == WB_name) { // not running : try to get a request from the queues var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e || t.PC.val() < e.PC.val()) { e = t; } }; for (var i in load_queue) check(load_queue[i]); for (var i in store_queue) check(store_queue[i]); if (!e) return; // load : waiting for data // notice that store instruction check this in WB stage var is_load = e.name.substr(0, 4) == "Load"; if (is_load && e.Qk.val() != "") return; e.is_running.set(true); if (is_load) { memory_controller.type.set("load"); memory_controller.value.set(""); memory_controller.t_remaining.set(conf.t_load - 1); } else { memory_controller.type.set("store"); if (e.Qk.val() != "") { memory_controller.value.set(e.Qk.val()); } else { memory_controller.value.set(e.Vk.val()); } memory_controller.t_remaining.set(conf.t_store - 1); } memory_controller.is_running.set(true); memory_controller.addr.set(e.addr.val()); memory_controller.name.set(e.name); memory_controller.PC.set(e.PC.val()); } }; var EXE_add_sub = () => { // completely rewrite ... // feel awkward about pipelines // detect & run in reverse order // O(n) lines, O(n) latency var n = conf.t_add_sub.length; var can_advance; for (var i = n - 1; i >= 0; i--) { var FPA = FP_adder[i]; var has_advanced; if (FPA.is_running.val() == true) { var t_r = FPA.t_remaining.val(); if (i == n - 1 && t_r == 1) { // done if (FPA.type.val() == "add") { var tmp = FPA.src1.val() + FPA.src2.val(); FPA.value.set(tmp); } else { var tmp = FPA.src1.val() - FPA.src2.val(); FPA.value.set(tmp); } // mark as done instructions.set_execution(FPA.PC.val()); } if (t_r > 0) { FPA.t_remaining.set(t_r - 1); } if (i < n - 1 && t_r == 0 && can_advance) { // advance to i + 1 var FPA_next = FP_adder[i + 1]; FPA_next.is_running.set(true); FPA_next.type.set(FPA.type.val()); FPA_next.src1.set(FPA.src1.val()); FPA_next.src2.set(FPA.src2.val()); FPA_next.name.set(FPA.name.val()); FPA_next.value.set(FPA.value.val()); FPA_next.PC.set(FPA.PC.val()); FPA_next.t_remaining.set(conf.t_add_sub[i + 1] - 1); // special case if (i == n - 2 && conf.t_add_sub[i + 1] - 1 == 0) { // done if (FPA.type.val() == "add") { var tmp = FPA.src1.val() + FPA.src2.val(); FPA_next.value.set(tmp); } else { var tmp = FPA.src1.val() - FPA.src2.val(); FPA_next.value.set(tmp); } // mark as done instructions.set_execution(FPA.PC.val()); } FPA.is_running.set(false); FPA.type.set(""); FPA.src1.set(""); FPA.src2.set(""); FPA.name.set(""); FPA.value.set(""); FPA.PC.set(""); FPA.t_remaining.set(""); has_advanced = true; } else { has_advanced = false; } } // can advance to stage i ? if (i == n - 1) { can_advance = !FPA.is_running.val() || FPA.name.val() == WB_name; } else { can_advance = !FPA.is_running.val() || has_advanced; } } if (can_advance) { // find a RS var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e && t.Qj.val() == "" && t.Qk.val() == "") { e = t; } }; for (var i in RS_add) check(RS_add[i]); if (!e) return; var is_add = e.op.val() == "ADDD"; e.is_running.set(true); if (is_add) { FP_adder[0].type.set("add"); } else { FP_adder[0].type.set("sub"); } FP_adder[0].t_remaining.set(conf.t_add_sub[0] - 1); FP_adder[0].src1.set(e.Vj.val()); FP_adder[0].src2.set(e.Vk.val()); FP_adder[0].name.set(e.name); FP_adder[0].value.set(""); FP_adder[0].is_running.set(true); FP_adder[0].PC.set(e.PC.val()); } }; var EXE_mul = () => { // detect & run in reverse order // O(n) lines, O(n) latency var n = conf.t_mul.length; var can_advance; for (var i = n - 1; i >= 0; i--) { var FPM = FP_multiplier[i]; var has_advanced; if (FPM.is_running.val() == true) { var t_r = FPM.t_remaining.val(); if (i == n - 1 && t_r == 1) { // done var tmp = FPM.src1.val() * FPM.src2.val(); FPM.value.set(tmp); // mark as done instructions.set_execution(FPM.PC.val()); } if (t_r > 0) { FPM.t_remaining.set(t_r - 1); } if (i < n - 1 && t_r == 0 && can_advance) { // advance to i + 1 var FPM_next = FP_multiplier[i + 1]; FPM_next.is_running.set(true); FPM_next.type.set(FPM.type.val()); FPM_next.src1.set(FPM.src1.val()); FPM_next.src2.set(FPM.src2.val()); FPM_next.name.set(FPM.name.val()); FPM_next.value.set(FPM.value.val()); FPM_next.PC.set(FPM.PC.val()); FPM_next.t_remaining.set(conf.t_mul[i + 1] - 1); // special case if (i == n - 2 && conf.t_mul[i + 1] - 1 == 0) { // done var tmp = FPM.src1.val() * FPM.src2.val(); FPM_next.value.set(tmp); // mark as done instructions.set_execution(FPM.PC.val()); } FPM.is_running.set(false); FPM.type.set(""); FPM.src1.set(""); FPM.src2.set(""); FPM.name.set(""); FPM.value.set(""); FPM.PC.set(""); FPM.t_remaining.set(""); has_advanced = true; } else { has_advanced = false; } } // can advance to stage i ? if (i == n - 1) { can_advance = !FPM.is_running.val() || FPM.name.val() == WB_name; } else { can_advance = !FPM.is_running.val() || has_advanced; } } if (can_advance) { // find a RS var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e && t.op.val() == "MULD" && t.Qj.val() == "" && t.Qk.val() == "") { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); if (!e) return; e.is_running.set(true); FP_multiplier[0].type.set("mul"); FP_multiplier[0].t_remaining.set(conf.t_mul[0] - 1); FP_multiplier[0].src1.set(e.Vj.val()); FP_multiplier[0].src2.set(e.Vk.val()); FP_multiplier[0].name.set(e.name); FP_multiplier[0].value.set(""); FP_multiplier[0].is_running.set(true); FP_multiplier[0].PC.set(e.PC.val()); } }; var EXE_div = () => { if (FP_divider.is_running.val() == true) { // is running // [removed some useless and buggy code] var t_r = FP_divider.t_remaining.val(); if (t_r == 1) { // done var tmp = FP_divider.src1.val() / FP_divider.src2.val(); FP_divider.value.set(tmp); // mark as done FP_divider.t_remaining.set(0); instructions.set_execution(FP_divider.PC.val()); } else if (t_r > 1) { // WIP FP_divider.t_remaining.set(FP_divider.t_remaining.val() - 1); } } // [immediately after CDB broadcast] if (FP_divider.is_running.val() == false || FP_divider.name.val() == WB_name) { // not running : find a ready RS var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e && t.op.val() == "DIVD" && t.Qj.val() == "" && t.Qk.val() == "") { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); if (!e) return; e.is_running.set(true); FP_divider.type.set("div"); FP_divider.t_remaining.set(conf.t_div - 1); FP_divider.src1.set(e.Vj.val()); FP_divider.src2.set(e.Vk.val()); FP_divider.name.set(e.name); FP_divider.value.set(""); FP_divider.is_running.set(true); FP_divider.PC.set(e.PC.val()); } }; var EXE = () => { // (1) load & store EXE_load_store(); // (2) add & sub EXE_add_sub(); // (3) mul & div EXE_mul(); EXE_div(); }; var CDB_write = (name, value) => { WB_name = name; WB_value = value; if (memory_controller.is_running.val() == true) { if (memory_controller.value.val() == name) { memory_controller.value.set(value); } } var check_load_store = (e) => { if (e.busy.val() == "Yes") { if (e.Qk.val() == name) { e.Qk.set(""); e.Vk.set(value); } } }; for (var i in load_queue) check_load_store(load_queue[i]); for (var i in store_queue) check_load_store(store_queue[i]); var check_RS = (e) => { if (e.busy.val() == "Yes") { if (e.Qj.val() == name) { e.Qj.set(""); e.Vj.set(value); } if (e.Qk.val() == name) { e.Qk.set(""); e.Vk.set(value); } } }; for (var i in RS_add) check_RS(RS_add[i]); for (var i in RS_mul) check_RS(RS_mul[i]); var check_reg = (e) => { if (e.val() == name) { e.set(value); } }; for (var i in FP_regs) check_reg(FP_regs[i]); // no need to check int regs ... }; // returns true if succeed var WB_load_store = () => { if (memory_controller.is_running.val() == false) { return false; } if (memory_controller.t_remaining.val() != 0) { return false; } if (memory_controller.type.val() == "load") { // load : write to CDB CDB_write(memory_controller.name.val(), memory_controller.value.val()); memory_controller.is_running.set(false); memory_controller.type.set(""); memory_controller.addr.set(""); memory_controller.name.set(""); memory_controller.value.set(""); memory_controller.t_remaining.set(""); memory_controller.PC.set(""); // update the load queue var e = undefined; var check = (t) => { if (t.is_running.val()) { e = t; } }; for (var i in load_queue) check(load_queue[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vk.set(""); e.Qk.set(""); e.addr.set(""); instructions.set_writeback(e.PC.val()); return true; } else { // store : write to mem // check the requirements first if (isNaN(memory_controller.value.val())) { return false; } memory.mem_write(memory_controller.addr.val(), memory_controller.value.val()); memory_controller.is_running.set(false); memory_controller.type.set(""); memory_controller.addr.set(""); memory_controller.name.set(""); memory_controller.value.set(""); memory_controller.t_remaining.set(""); memory_controller.PC.set(""); // update the load queue var e = undefined; var check = (t) => { if (t.is_running.val()) { e = t; } }; for (var i in store_queue) check(store_queue[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vk.set(""); e.Qk.set(""); e.addr.set(""); instructions.set_writeback(e.PC.val()); return true; } }; var WB_add_sub = () => { var n = conf.t_add_sub.length; var FPA_last = FP_adder[n - 1]; if (FPA_last.is_running.val() == false) { return false; } if (FPA_last.t_remaining.val() != 0) { return false; } // add/sub : write to CDB CDB_write(FPA_last.name.val(), FPA_last.value.val()); FPA_last.is_running.set(false); FPA_last.type.set(""); FPA_last.name.set(""); FPA_last.value.set(""); FPA_last.t_remaining.set(""); FPA_last.src1.set(""); FPA_last.src2.set(""); FPA_last.PC.set(""); var e = undefined; var check = (t) => { if (t.name == FPA_last.name.val()) { e = t; } }; for (var i in RS_add) check(RS_add[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vj.set(""); e.Qj.set(""); e.Vk.set(""); e.Qk.set(""); e.op.set(""); instructions.set_writeback(e.PC.val()); return true; }; var WB_mul = () => { var n = conf.t_mul.length; var FPM_last = FP_multiplier[n - 1]; if (FPM_last.is_running.val() == false) { return false; } if (FPM_last.t_remaining.val() != 0) { return false; } // mul/div : write to CDB CDB_write(FPM_last.name.val(), FPM_last.value.val()); FPM_last.is_running.set(false); FPM_last.type.set(""); FPM_last.name.set(""); FPM_last.value.set(""); FPM_last.t_remaining.set(""); FPM_last.src1.set(""); FPM_last.src2.set(""); FPM_last.PC.set(""); var e = undefined; var check = (t) => { if (t.name == WB_name) { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vj.set(""); e.Qj.set(""); e.Vk.set(""); e.Qk.set(""); e.op.set(""); instructions.set_writeback(e.PC.val()); return true; }; var WB_div = () => { if (FP_divider.is_running.val() == false) { return false; } if (FP_divider.t_remaining.val() != 0) { return false; } // mul/div : write to CDB CDB_write(FP_divider.name.val(), FP_divider.value.val()); FP_divider.is_running.set(false); FP_divider.type.set(""); FP_divider.name.set(""); FP_divider.value.set(""); FP_divider.t_remaining.set(""); FP_divider.src1.set(""); FP_divider.src2.set(""); FP_divider.PC.set(""); var e = undefined; var check = (t) => { if (t.name == WB_name) { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vj.set(""); e.Qj.set(""); e.Vk.set(""); e.Qk.set(""); e.op.set(""); instructions.set_writeback(e.PC.val()); return true; }; var WB = () => { WB_name = ""; WB_value = ""; // (1) load & store if (WB_load_store() == true) return; // (2) add & sub if (WB_add_sub() == true) return; // (3) mul & div if (WB_mul() == true) return; if (WB_div() == true) return; }; var f = function() { if (id != CPU_exec_id) { return; } // combinational logic // (0) update cycles cycles.set(cycles.val() + 1); // (3) writeback WB(); // (1) instruction fetch // IF needs forwarding from WB IF(); // (2) execution // needs WB -> EXE forwarding for zero-latency EXE chains EXE(); // rising edge HDL.rising_edge(); setTimeout(f, CPU_exec_delay_time); }; return f; }; var CPU_do_load = function() { console.log("CPU.do_load"); // load memory submodule memory = get_memory_module(); memory.do_load(); // load instructions submodule instructions = get_instructions_module(); instructions.do_load(); // 2017-06-04 @wys // must load config manually }; // DANGER ! This function immediately resets all CPU states & ui var CPU_load_config = function(_conf) { if (has_power) { throw "ERROR: Can't set config while power on"; } console.log("CPU load config ..."); conf = _conf; // load config ui.reload_ui(conf); ui_ele = ui.get_elements(); console.log(ui_ele); // leave HDL un-initialized }; var CPU_power_on = function() { if (has_power) { throw "ERROR: already powered on"; } console.log("CPU power on ..."); has_power = true; HDL.re_init(); // (0) cycles & PC // bug fix [2017-05-31] @wys cycles = HDL.signal(ui.CPU_cycles_update_func()); cycles.set(1); // should not be '0' PC = HDL.signal(ui.CPU_PC_update_func()); PC.set(0); // (1) load queue [load by ui] load_queue = {}; for (var i in ui_ele.load_queue) { var e = ui_ele.load_queue[i]; load_queue[i] = { name : i }; for (var j in e) if (j != "name") { load_queue[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } load_queue[i].busy.set("No"); load_queue[i].is_running = HDL.signal(() => 0).set(false); } // (2) store queue [load by ui] store_queue = {}; for (var i in ui_ele.store_queue) { var e = ui_ele.store_queue[i]; store_queue[i] = { name : i }; for (var j in e) if (j != "name") { store_queue[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } store_queue[i].busy.set("No"); store_queue[i].is_running = HDL.signal(() => 0).set(false); } // (3) RS add [load by ui] RS_add = {}; for (var i in ui_ele.RS_add) { var e = ui_ele.RS_add[i]; RS_add[i] = { name : i }; for (var j in e) if (j != "name") { RS_add[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } RS_add[i].busy.set("No"); RS_add[i].is_running = HDL.signal(() => 0).set(false); } // (4) RS mul [load by ui] RS_mul = {}; for (var i in ui_ele.RS_mul) { var e = ui_ele.RS_mul[i]; RS_mul[i] = { name : i }; for (var j in e) if (j != "name") { RS_mul[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } RS_mul[i].busy.set("No"); RS_mul[i].is_running = HDL.signal(() => 0).set(false); } // (5) FP regs [load by ui] FP_regs = {}; for (var i in ui_ele.FP_regs) { FP_regs[i] = HDL.signal(ui.update_func(ui_ele.FP_regs[i])).set(0.0); } // load FP reg vals from config (() => { var values_list = conf.FP_reg_vals.trim().split("\n"); values_list.forEach((s) => { var tmp = s.trim().split(" "); if (tmp[0][0] != "F") return; var addr = parseInt(tmp[0].substr(1)); var val = parseFloat(tmp[1]); if (isNaN(addr) || isNaN(val)) return; if (addr < 0 || addr >= conf.n_FP_registers) return; FP_regs["F" + addr].set(val); }); })(); // (6) INT regs [load by ui] INT_regs = {}; for (var i in ui_ele.INT_regs) { INT_regs[i] = HDL.signal(ui.update_func(ui_ele.INT_regs[i])).set(0); } // load INT reg vals from config (() => { var values_list = conf.INT_reg_vals.trim().split("\n"); values_list.forEach((s) => { var tmp = s.trim().split(" "); if (tmp[0][0] != "R") return; var addr = parseInt(tmp[0].substr(1)); var val = parseInt(tmp[1]); if (isNaN(addr) || isNaN(val)) return; if (addr < 0 || addr >= conf.n_INT_registers) return; INT_regs["R" + addr].set(val); }); })(); // (7) memory ui.clear_memory_table(); memory.initialize(); // (8) instructions ui.clear_instruction_queue_table(); instructions.initialize(); // (9) memory controller memory_controller = { is_running : HDL.signal( ui.update_func(ui_ele.MC.is_running)).set(false), type : HDL.signal(ui.update_func(ui_ele.MC.type)).set(""), PC : HDL.signal(() => 0).set(""), addr : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(ui_ele.MC.name)).set(""), value : HDL.signal(() => 0).set(""), t_remaining : HDL.signal(ui.update_func(ui_ele.MC.time)).set("") }; // (10) FP adder (() => { var n = conf.t_add_sub.length; FP_adder = []; for (var i = 0; i < n; i++) { var FPA = ui_ele.FPA[i]; FP_adder.push({ is_running : HDL.signal( ui.update_func(FPA.busy)).set(false), type : HDL.signal(ui.update_func(FPA.op)).set(""), PC : HDL.signal(() => 0).set(""), src1 : HDL.signal(() => 0).set(""), src2 : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(FPA.name)).set(""), value : HDL.signal(ui.update_func(FPA.value)).set(""), t_remaining : HDL.signal(ui.update_func(FPA.time)).set("") }); } })(); // (11) FP multiplier (() => { var n = conf.t_mul.length; FP_multiplier = []; for (var i = 0; i < n; i++) { var FPM = ui_ele.FPM[i]; FP_multiplier.push({ is_running : HDL.signal( ui.update_func(FPM.busy)).set(false), type : HDL.signal(ui.update_func(FPM.op)).set(""), PC : HDL.signal(() => 0).set(""), src1 : HDL.signal(() => 0).set(""), src2 : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(FPM.name)).set(""), value : HDL.signal(ui.update_func(FPM.value)).set(""), t_remaining : HDL.signal(ui.update_func(FPM.time)).set("") }); } })(); // (12) FP divider FP_divider = { is_running : HDL.signal( ui.update_func(ui_ele.FPD.is_running)).set(false), type : HDL.signal(ui.update_func(ui_ele.FPD.type)).set(""), PC : HDL.signal(() => 0).set(""), src1 : HDL.signal(() => 0).set(""), src2 : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(ui_ele.FPD.name)).set(""), value : HDL.signal(() => 0).set(""), t_remaining : HDL.signal(ui.update_func(ui_ele.FPD.time)).set("") }; HDL.rising_edge(); // setTimeout(get_CPU_clock_func(), CPU_exec_delay_time + 1000); }; var CPU_power_off = function() { if (!has_power) { throw "ERROR: already powered off"; } ++CPU_exec_id; has_power = false; }; var CPU_run = () => { if (!has_power) { throw "ERROR: run while powered off"; } setTimeout(get_CPU_clock_func(), 100); }; var CPU_pause = () => { ++CPU_exec_id; } var CPU_step = () => { if (!has_power) { throw "ERROR: step while powered off"; } get_CPU_clock_func()(); ++CPU_exec_id; }; return { do_load : CPU_do_load, load_config : CPU_load_config, power_on : CPU_power_on, power_off : CPU_power_off, run : CPU_run, pause : CPU_pause, step : CPU_step, get_config : function() { return conf; } }; })();
js/CPU.js
var config; var utils; var ui; var CPU; var HDL; var CPU = (function() { console.log("loading CPU module"); var conf; var has_power = false; var cycles; var load_queue; var store_queue; var RS_add; var RS_mul; var FP_regs; var INT_regs; var memory; var instructions; var ui_ele; var PC; var memory_controller; var FP_adder; var FP_multiplier; var FP_divider; var WB_name; var WB_value; // TODO : drag these to config file // hardcoded memory size : 4096 const mem_size = 4096; const mem_bits = 12; var get_memory_module = () => { // memory submodule ... var mem; var do_load = () => { mem = []; mem.length = mem_size; }; // init from config var do_initialize = () => { for (var i = 0; i < mem_size; i++) { mem[i] = { value : 0.0, modified : false, signal : undefined }; } // load vals from config var values_list = conf.mem_vals.trim().split("\n"); values_list.forEach((s) => { var tmp = s.trim().split(" "); var addr = parseInt(tmp[0]); var val = parseFloat(tmp[1]); if (isNaN(addr) || isNaN(val)) return; if (addr < 0 || addr >= mem_size) return; mem_write(addr, val); }); }; var mem_write = (addr, val) => { // write memory if (addr < 0 || addr >= mem_size) { throw "invalid addr " + addr; } if (!mem[addr].modified) { // add this entry to ui mem[addr].modified = true; add_entry(addr); } mem[addr].value = val; mem[addr].signal.set(val); }; var mem_read = (addr) => { // read memory return mem[addr].value; }; var add_entry = (addr) => { var count = 0; for (var i = 0; i < addr; i++) { count += mem[i].modified ? 1 : 0; } var e = ui.add_memory_table_entry(count); HDL.signal(ui.update_func(e.addr)).set(addr); mem[addr].signal = HDL.signal(ui.update_func(e.val)); }; return { do_load : do_load, initialize : do_initialize, mem_read : mem_read, mem_write : mem_write }; }; var get_instructions_module = () => { var ins; var do_load = () => { ins = []; }; // init from config var do_initialize = () => { ins.length = 0; // load instructions from config var ins_list = conf.instructions.trim().split("\n"); ins_list.forEach((s) => { var tmp = parse_instruction(s); if (!tmp) { alert("Invalid instruction `" + s + "`"); return; } tmp.PC = ins.length; tmp.issue = ""; tmp.execution = ""; tmp.writeback = ""; // add this instruction to ui var tr = ui.add_instruction_queue_table_entry(); // console.log(tr); for (var i in tr) { tmp[i] = HDL.signal(ui.update_func(tr[i])).set(tmp[i]); } ins.push(tmp); }); }; var parse_int = (s) => { s = s.trim(); var x = parseInt(s); if (x + "" != s) { return undefined; } return x; }; var parse_FP_reg = (s) => { s = s.trim(); if (s[0] != "F") { return undefined; } var id = parse_int(s.substr(1)); if (isNaN(id)) { return undefined; } if (id < 0 || id >= conf.n_FP_registers) { return undefined; } return "F" + id; }; var parse_INT_reg = (s) => { s = s.trim(); if (s[0] != "R") { return undefined; } var id = parse_int(s.substr(1)); if (isNaN(id)) { return undefined; } if (id < 0 || id >= conf.n_INT_registers) { return undefined; } return "R" + id; }; var parse_addr = (s) => { s = s.trim(); var pos_1 = s.indexOf("("); var pos_2 = s.indexOf(")"); if (pos_1 == -1 || pos_2 == -1 || pos_1 > pos_2) { return undefined; } var offset = parse_int(s.substr(0, pos_1)); if (isNaN(offset)) { return undefined; } var reg = parse_INT_reg(s.substr(pos_1 + 1, pos_2 - pos_1 - 1)); if (!reg) { return undefined; } if (s.substr(pos_2 + 1).trim() != "") { return undefined; } return { offset : offset, reg : reg }; }; var parse_mem_arglist = (s) => { var l = s.split(","); if (l.length != 2) { return undefined; } var dest = parse_FP_reg(l[0]); if (!dest) { return undefined; } var source = parse_addr(l[1]); if (!source) { return undefined; } return { dest : dest, source : source }; }; var parse_arith_arglist = (s) => { var l = s.split(","); if (l.length != 3) { return undefined; } var dest = parse_FP_reg(l[0]); if (!dest) { return undefined; } var src1 = parse_FP_reg(l[1]); if (!src1) { return undefined; } var src2 = parse_FP_reg(l[2]); if (!src2) { return undefined; } return { dest : dest, src1 : src1, src2 : src2 }; }; var parse_instruction = (s) => { // returns: object -- name, dest, src1, src2 // (1) load / store { const names = ["LD", "ST"]; for (var i in names) { var name = names[i]; if (s.substr(0, name.length + 1) == name + " ") { var tmp = parse_mem_arglist(s.substr(name.length + 1)); if (!tmp) return undefined; return { name : name, dest : tmp.dest, src1 : tmp.source.offset, src2 : tmp.source.reg }; } } } // (2) add / sub / mul / div { const names = ["ADDD", "SUBD", "MULD", "DIVD"]; for (var i in names) { var name = names[i]; if (s.substr(0, name.length + 1) == name + " ") { var tmp = parse_arith_arglist(s.substr(name.length + 1)); if (!tmp) return undefined; return { name : name, dest : tmp.dest, src1 : tmp.src1, src2 : tmp.src2 }; } } } return undefined; }; var do_peek_name = () => { if (PC.val() >= ins.length) { return undefined; } else { return ins[PC.val()].name.val(); } }; var do_fetch = () => { PC.set(PC.val() + 1); var ret = ins[PC.val()]; ret.issue.set(cycles.val()); return ret; }; var do_set_execution = (id) => { ins[id].execution.set(cycles.val()); }; var do_set_writeback = (id) => { ins[id].writeback.set(cycles.val()); }; return { do_load : do_load, initialize : do_initialize, peek_name : do_peek_name, fetch : do_fetch, set_execution : do_set_execution, set_writeback : do_set_writeback }; }; var CPU_exec_id = 0; var CPU_exec_delay_time = 1000; // HDL-like CPU clock function var get_CPU_clock_func = function() { var id = ++CPU_exec_id; var load_queue_allocate = () => { for (var i in load_queue) { if (load_queue[i].busy.val() == "No" || load_queue[i].name == WB_name) { return load_queue[i]; } } return undefined; }; var store_queue_allocate = () => { for (var i in store_queue) { if (store_queue[i].busy.val() == "No" || store_queue[i].name == WB_name) { return store_queue[i]; } } return undefined; }; var RS_add_allocate = () => { for (var i in RS_add) { if (RS_add[i].busy.val() == "No" || RS_add[i].name == WB_name) { return RS_add[i]; } } return undefined; }; var RS_mul_allocate = () => { for (var i in RS_mul) { if (RS_mul[i].busy.val() == "No" || RS_mul[i].name == WB_name) { return RS_mul[i]; } } return undefined; }; var get_reg_value = (reg, V, Q) => { var reg_val = reg.val(); if (reg_val == WB_name) { // WB->IF fowarding V.set(WB_value); Q.set(""); } else if (isNaN(reg_val)) { // in a reservation station V.set(""); Q.set(reg_val); } else { // value get V.set(reg_val); Q.set(""); } }; var IF = () => { var ins_name = instructions.peek_name(); if (!ins_name) { // no more instruction return; } const ins_name_to_type = { LD : "load", ST : "store", ADDD : "add", SUBD : "add", MULD : "mul", DIVD : "mul" }; var ins_type = ins_name_to_type[ins_name]; // check if possible to issue the instruction if (ins_type == "load") { var e = load_queue_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.PC.set(ins.PC.val()); e.addr.set(ins.src1.val() + INT_regs[ins.src2.val()].val()); FP_regs[ins.dest.val()].set(e.name); // dest } if (ins_type == "store") { var e = store_queue_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.PC.set(ins.PC.val()); e.addr.set(ins.src1.val() + INT_regs[ins.src2.val()].val()); get_reg_value(FP_regs[ins.dest.val()], e.Vk, e.Qk); } if (ins_type == "add") { var e = RS_add_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.op.set(ins_name); e.PC.set(ins.PC.val()); get_reg_value(FP_regs[ins.src1.val()], e.Vj, e.Qj); // src1 get_reg_value(FP_regs[ins.src2.val()], e.Vk, e.Qk); // src2 FP_regs[ins.dest.val()].set(e.name); // dest } if (ins_type == "mul") { var e = RS_mul_allocate(); if (!e) return; var ins = instructions.fetch(); e.busy.set("Yes"); e.op.set(ins_name); e.PC.set(ins.PC.val()); get_reg_value(FP_regs[ins.src1.val()], e.Vj, e.Qj); // src1 get_reg_value(FP_regs[ins.src2.val()], e.Vk, e.Qk); // src2 FP_regs[ins.dest.val()].set(e.name); // dest } }; var EXE_load_store = () => { // strictly in PC order if (memory_controller.is_running.val() == true) { // is running var t_r = memory_controller.t_remaining.val(); if (t_r == 1) { // done if (memory_controller.type.val() == "load") { // load : get XXX from mem var tmp = memory.mem_read(memory_controller.addr.val()); memory_controller.value.set(tmp); } else { // store : nothing to do ... } // mark as done memory_controller.t_remaining.set(0); instructions.set_execution(memory_controller.PC.val()); } else if (t_r > 1) { // working in progress memory_controller.t_remaining.set( memory_controller.t_remaining.val() - 1); } } // [immediately after CDB broadcast] if (memory_controller.is_running.val() == false || memory_controller.name.val() == WB_name) { // not running : try to get a request from the queues var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e || t.PC.val() < e.PC.val()) { e = t; } }; for (var i in load_queue) check(load_queue[i]); for (var i in store_queue) check(store_queue[i]); if (!e) return; // load : waiting for data // notice that store instruction check this in WB stage var is_load = e.name.substr(0, 4) == "Load"; if (is_load && e.Qk.val() != "") return; e.is_running.set(true); if (is_load) { memory_controller.type.set("load"); memory_controller.value.set(""); memory_controller.t_remaining.set(conf.t_load - 1); } else { memory_controller.type.set("store"); if (e.Qk.val() != "") { memory_controller.value.set(e.Qk.val()); } else { memory_controller.value.set(e.Vk.val()); } memory_controller.t_remaining.set(conf.t_store - 1); } memory_controller.is_running.set(true); memory_controller.addr.set(e.addr.val()); memory_controller.name.set(e.name); memory_controller.PC.set(e.PC.val()); } }; var EXE_add_sub = () => { // completely rewrite ... // feel awkward about pipelines // detect & run in reverse order // O(n) lines, O(n) latency var n = conf.t_add_sub.length; var can_advance; for (var i = n - 1; i >= 0; i--) { var FPA = FP_adder[i]; var has_advanced; if (FPA.is_running.val() == true) { var t_r = FPA.t_remaining.val(); if (i == n - 1 && t_r == 1) { // done if (FPA.type.val() == "add") { var tmp = FPA.src1.val() + FPA.src2.val(); FPA.value.set(tmp); } else { var tmp = FPA.src1.val() - FPA.src2.val(); FPA.value.set(tmp); } // mark as done instructions.set_execution(FPA.PC.val()); } if (t_r > 0) { FPA.t_remaining.set(t_r - 1); } if (i < n - 1 && t_r == 0 && can_advance) { // advance to i + 1 var FPA_next = FP_adder[i + 1]; FPA_next.is_running.set(true); FPA_next.type.set(FPA.type.val()); FPA_next.src1.set(FPA.src1.val()); FPA_next.src2.set(FPA.src2.val()); FPA_next.name.set(FPA.name.val()); FPA_next.value.set(FPA.value.val()); FPA_next.PC.set(FPA.PC.val()); FPA_next.t_remaining.set(conf.t_add_sub[i + 1] - 1); // special case if (i == n - 2 && conf.t_add_sub[i + 1] - 1 == 0) { // done if (FPA.type.val() == "add") { var tmp = FPA.src1.val() + FPA.src2.val(); FPA_next.value.set(tmp); } else { var tmp = FPA.src1.val() - FPA.src2.val(); FPA_next.value.set(tmp); } // mark as done instructions.set_execution(FPA.PC.val()); } FPA.is_running.set(false); FPA.type.set(""); FPA.src1.set(""); FPA.src2.set(""); FPA.name.set(""); FPA.value.set(""); FPA.PC.set(""); FPA.t_remaining.set(""); has_advanced = true; } else { has_advanced = false; } } // can advance to stage i ? if (i == n - 1) { can_advance = !FPA.is_running.val() || FPA.name.val() == WB_name; } else { can_advance = !FPA.is_running.val() || has_advanced; } } if (can_advance) { // find a RS var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e && t.Qj.val() == "" && t.Qk.val() == "") { e = t; } }; for (var i in RS_add) check(RS_add[i]); if (!e) return; var is_add = e.op.val() == "ADDD"; e.is_running.set(true); if (is_add) { FP_adder[0].type.set("add"); } else { FP_adder[0].type.set("sub"); } FP_adder[0].t_remaining.set(conf.t_add_sub[0] - 1); FP_adder[0].src1.set(e.Vj.val()); FP_adder[0].src2.set(e.Vk.val()); FP_adder[0].name.set(e.name); FP_adder[0].value.set(""); FP_adder[0].is_running.set(true); FP_adder[0].PC.set(e.PC.val()); } }; var EXE_mul = () => { // detect & run in reverse order // O(n) lines, O(n) latency var n = conf.t_mul.length; var can_advance; for (var i = n - 1; i >= 0; i--) { var FPM = FP_multiplier[i]; var has_advanced; if (FPM.is_running.val() == true) { var t_r = FPM.t_remaining.val(); if (i == n - 1 && t_r == 1) { // done var tmp = FPM.src1.val() * FPM.src2.val(); FPM.value.set(tmp); // mark as done instructions.set_execution(FPM.PC.val()); } if (t_r > 0) { FPM.t_remaining.set(t_r - 1); } if (i < n - 1 && t_r == 0 && can_advance) { // advance to i + 1 var FPM_next = FP_multiplier[i + 1]; FPM_next.is_running.set(true); FPM_next.type.set(FPM.type.val()); FPM_next.src1.set(FPM.src1.val()); FPM_next.src2.set(FPM.src2.val()); FPM_next.name.set(FPM.name.val()); FPM_next.value.set(FPM.value.val()); FPM_next.PC.set(FPM.PC.val()); FPM_next.t_remaining.set(conf.t_mul[i + 1] - 1); // special case if (i == n - 2 && conf.t_mul[i + 1] - 1 == 0) { // done var tmp = FPM.src1.val() * FPM.src2.val(); FPM_next.value.set(tmp); // mark as done instructions.set_execution(FPM.PC.val()); } FPM.is_running.set(false); FPM.type.set(""); FPM.src1.set(""); FPM.src2.set(""); FPM.name.set(""); FPM.value.set(""); FPM.PC.set(""); FPM.t_remaining.set(""); has_advanced = true; } else { has_advanced = false; } } // can advance to stage i ? if (i == n - 1) { can_advance = !FPM.is_running.val() || FPM.name.val() == WB_name; } else { can_advance = !FPM.is_running.val() || has_advanced; } } if (can_advance) { // find a RS var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e && t.op.val() == "MULD" && t.Qj.val() == "" && t.Qk.val() == "") { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); if (!e) return; e.is_running.set(true); FP_multiplier[0].type.set("mul"); FP_multiplier[0].t_remaining.set(conf.t_mul[0] - 1); FP_multiplier[0].src1.set(e.Vj.val()); FP_multiplier[0].src2.set(e.Vk.val()); FP_multiplier[0].name.set(e.name); FP_multiplier[0].value.set(""); FP_multiplier[0].is_running.set(true); FP_multiplier[0].PC.set(e.PC.val()); } }; var EXE_div = () => { if (FP_divider.is_running.val() == true) { // is running // [removed some useless and buggy code] var t_r = FP_divider.t_remaining.val(); if (t_r == 1) { // done var tmp = FP_divider.src1.val() / FP_divider.src2.val(); FP_divider.value.set(tmp); // mark as done FP_divider.t_remaining.set(0); instructions.set_execution(FP_divider.PC.val()); } else if (t_r > 1) { // WIP FP_divider.t_remaining.set(FP_divider.t_remaining.val() - 1); } } // [immediately after CDB broadcast] if (FP_divider.is_running.val() == false || FP_divider.name.val() == WB_name) { // not running : find a ready RS var e = undefined; var check = (t) => { if (t.busy.val() != "Yes" || t.is_running.val() == true) { return; } if (!e && t.op.val() == "DIVD" && t.Qj.val() == "" && t.Qk.val() == "") { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); if (!e) return; e.is_running.set(true); FP_divider.type.set("div"); FP_divider.t_remaining.set(conf.t_div - 1); FP_divider.src1.set(e.Vj.val()); FP_divider.src2.set(e.Vk.val()); FP_divider.name.set(e.name); FP_divider.value.set(""); FP_divider.is_running.set(true); FP_divider.PC.set(e.PC.val()); } }; var EXE = () => { // (1) load & store EXE_load_store(); // (2) add & sub EXE_add_sub(); // (3) mul & div EXE_mul(); EXE_div(); }; var CDB_write = (name, value) => { WB_name = name; WB_value = value; if (memory_controller.is_running.val() == true) { if (memory_controller.value.val() == name) { memory_controller.value.set(value); } } var check_load_store = (e) => { if (e.busy.val() == "Yes") { if (e.Qk.val() == name) { e.Qk.set(""); e.Vk.set(value); } } }; for (var i in load_queue) check_load_store(load_queue[i]); for (var i in store_queue) check_load_store(store_queue[i]); var check_RS = (e) => { if (e.busy.val() == "Yes") { if (e.Qj.val() == name) { e.Qj.set(""); e.Vj.set(value); } if (e.Qk.val() == name) { e.Qk.set(""); e.Vk.set(value); } } }; for (var i in RS_add) check_RS(RS_add[i]); for (var i in RS_mul) check_RS(RS_mul[i]); var check_reg = (e) => { if (e.val() == name) { e.set(value); } }; for (var i in FP_regs) check_reg(FP_regs[i]); // no need to check int regs ... }; // returns true if succeed var WB_load_store = () => { if (memory_controller.is_running.val() == false) { return false; } if (memory_controller.t_remaining.val() != 0) { return false; } if (memory_controller.type.val() == "load") { // load : write to CDB CDB_write(memory_controller.name.val(), memory_controller.value.val()); memory_controller.is_running.set(false); memory_controller.type.set(""); memory_controller.addr.set(""); memory_controller.name.set(""); memory_controller.value.set(""); memory_controller.t_remaining.set(""); memory_controller.PC.set(""); // update the load queue var e = undefined; var check = (t) => { if (t.is_running.val()) { e = t; } }; for (var i in load_queue) check(load_queue[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vk.set(""); e.Qk.set(""); e.addr.set(""); instructions.set_writeback(e.PC.val()); return true; } else { // store : write to mem // check the requirements first if (isNaN(memory_controller.value.val())) { return false; } memory.mem_write(memory_controller.addr.val(), memory_controller.value.val()); memory_controller.is_running.set(false); memory_controller.type.set(""); memory_controller.addr.set(""); memory_controller.name.set(""); memory_controller.value.set(""); memory_controller.t_remaining.set(""); memory_controller.PC.set(""); // update the load queue var e = undefined; var check = (t) => { if (t.is_running.val()) { e = t; } }; for (var i in store_queue) check(store_queue[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vk.set(""); e.Qk.set(""); e.addr.set(""); instructions.set_writeback(e.PC.val()); return true; } }; var WB_add_sub = () => { var n = conf.t_add_sub.length; var FPA_last = FP_adder[n - 1]; if (FPA_last.is_running.val() == false) { return false; } if (FPA_last.t_remaining.val() != 0) { return false; } // add/sub : write to CDB CDB_write(FPA_last.name.val(), FPA_last.value.val()); FPA_last.is_running.set(false); FPA_last.type.set(""); FPA_last.name.set(""); FPA_last.value.set(""); FPA_last.t_remaining.set(""); FPA_last.src1.set(""); FPA_last.src2.set(""); FPA_last.PC.set(""); var e = undefined; var check = (t) => { if (t.name == FPA_last.name.val()) { e = t; } }; for (var i in RS_add) check(RS_add[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vj.set(""); e.Qj.set(""); e.Vk.set(""); e.Qk.set(""); e.op.set(""); instructions.set_writeback(e.PC.val()); return true; }; var WB_mul = () => { var n = conf.t_mul.length; var FPM_last = FP_multiplier[n - 1]; if (FPM_last.is_running.val() == false) { return false; } if (FPM_last.t_remaining.val() != 0) { return false; } // mul/div : write to CDB CDB_write(FPM_last.name.val(), FPM_last.value.val()); FPM_last.is_running.set(false); FPM_last.type.set(""); FPM_last.name.set(""); FPM_last.value.set(""); FPM_last.t_remaining.set(""); FPM_last.src1.set(""); FPM_last.src2.set(""); FPM_last.PC.set(""); var e = undefined; var check = (t) => { if (t.is_running.val()) { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vj.set(""); e.Qj.set(""); e.Vk.set(""); e.Qk.set(""); e.op.set(""); instructions.set_writeback(e.PC.val()); return true; }; var WB_div = () => { if (FP_divider.is_running.val() == false) { return false; } if (FP_divider.t_remaining.val() != 0) { return false; } // mul/div : write to CDB CDB_write(FP_divider.name.val(), FP_divider.value.val()); FP_divider.is_running.set(false); FP_divider.type.set(""); FP_divider.name.set(""); FP_divider.value.set(""); FP_divider.t_remaining.set(""); FP_divider.src1.set(""); FP_divider.src2.set(""); FP_divider.PC.set(""); var e = undefined; var check = (t) => { if (t.is_running.val()) { e = t; } }; for (var i in RS_mul) check(RS_mul[i]); e.is_running.set(false); e.busy.set("No"); e.PC.set(""); e.Vj.set(""); e.Qj.set(""); e.Vk.set(""); e.Qk.set(""); e.op.set(""); instructions.set_writeback(e.PC.val()); return true; }; var WB = () => { WB_name = ""; WB_value = ""; // (1) load & store if (WB_load_store() == true) return; // (2) add & sub if (WB_add_sub() == true) return; // (3) mul & div if (WB_mul() == true) return; if (WB_div() == true) return; }; var f = function() { if (id != CPU_exec_id) { return; } // combinational logic // (0) update cycles cycles.set(cycles.val() + 1); // (3) writeback WB(); // (1) instruction fetch // IF needs forwarding from WB IF(); // (2) execution // needs WB -> EXE forwarding for zero-latency EXE chains EXE(); // rising edge HDL.rising_edge(); setTimeout(f, CPU_exec_delay_time); }; return f; }; var CPU_do_load = function() { console.log("CPU.do_load"); // load memory submodule memory = get_memory_module(); memory.do_load(); // load instructions submodule instructions = get_instructions_module(); instructions.do_load(); // 2017-06-04 @wys // must load config manually }; // DANGER ! This function immediately resets all CPU states & ui var CPU_load_config = function(_conf) { if (has_power) { throw "ERROR: Can't set config while power on"; } console.log("CPU load config ..."); conf = _conf; // load config ui.reload_ui(conf); ui_ele = ui.get_elements(); console.log(ui_ele); // leave HDL un-initialized }; var CPU_power_on = function() { if (has_power) { throw "ERROR: already powered on"; } console.log("CPU power on ..."); has_power = true; HDL.re_init(); // (0) cycles & PC // bug fix [2017-05-31] @wys cycles = HDL.signal(ui.CPU_cycles_update_func()); cycles.set(1); // should not be '0' PC = HDL.signal(ui.CPU_PC_update_func()); PC.set(0); // (1) load queue [load by ui] load_queue = {}; for (var i in ui_ele.load_queue) { var e = ui_ele.load_queue[i]; load_queue[i] = { name : i }; for (var j in e) if (j != "name") { load_queue[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } load_queue[i].busy.set("No"); load_queue[i].is_running = HDL.signal(() => 0).set(false); } // (2) store queue [load by ui] store_queue = {}; for (var i in ui_ele.store_queue) { var e = ui_ele.store_queue[i]; store_queue[i] = { name : i }; for (var j in e) if (j != "name") { store_queue[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } store_queue[i].busy.set("No"); store_queue[i].is_running = HDL.signal(() => 0).set(false); } // (3) RS add [load by ui] RS_add = {}; for (var i in ui_ele.RS_add) { var e = ui_ele.RS_add[i]; RS_add[i] = { name : i }; for (var j in e) if (j != "name") { RS_add[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } RS_add[i].busy.set("No"); RS_add[i].is_running = HDL.signal(() => 0).set(false); } // (4) RS mul [load by ui] RS_mul = {}; for (var i in ui_ele.RS_mul) { var e = ui_ele.RS_mul[i]; RS_mul[i] = { name : i }; for (var j in e) if (j != "name") { RS_mul[i][j] = HDL.signal(ui.update_func(e[j])).set(""); } RS_mul[i].busy.set("No"); RS_mul[i].is_running = HDL.signal(() => 0).set(false); } // (5) FP regs [load by ui] FP_regs = {}; for (var i in ui_ele.FP_regs) { FP_regs[i] = HDL.signal(ui.update_func(ui_ele.FP_regs[i])).set(0.0); } // load FP reg vals from config (() => { var values_list = conf.FP_reg_vals.trim().split("\n"); values_list.forEach((s) => { var tmp = s.trim().split(" "); if (tmp[0][0] != "F") return; var addr = parseInt(tmp[0].substr(1)); var val = parseFloat(tmp[1]); if (isNaN(addr) || isNaN(val)) return; if (addr < 0 || addr >= conf.n_FP_registers) return; FP_regs["F" + addr].set(val); }); })(); // (6) INT regs [load by ui] INT_regs = {}; for (var i in ui_ele.INT_regs) { INT_regs[i] = HDL.signal(ui.update_func(ui_ele.INT_regs[i])).set(0); } // load INT reg vals from config (() => { var values_list = conf.INT_reg_vals.trim().split("\n"); values_list.forEach((s) => { var tmp = s.trim().split(" "); if (tmp[0][0] != "R") return; var addr = parseInt(tmp[0].substr(1)); var val = parseInt(tmp[1]); if (isNaN(addr) || isNaN(val)) return; if (addr < 0 || addr >= conf.n_INT_registers) return; INT_regs["R" + addr].set(val); }); })(); // (7) memory ui.clear_memory_table(); memory.initialize(); // (8) instructions ui.clear_instruction_queue_table(); instructions.initialize(); // (9) memory controller memory_controller = { is_running : HDL.signal( ui.update_func(ui_ele.MC.is_running)).set(false), type : HDL.signal(ui.update_func(ui_ele.MC.type)).set(""), PC : HDL.signal(() => 0).set(""), addr : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(ui_ele.MC.name)).set(""), value : HDL.signal(() => 0).set(""), t_remaining : HDL.signal(ui.update_func(ui_ele.MC.time)).set("") }; // (10) FP adder (() => { var n = conf.t_add_sub.length; FP_adder = []; for (var i = 0; i < n; i++) { var FPA = ui_ele.FPA[i]; FP_adder.push({ is_running : HDL.signal( ui.update_func(FPA.busy)).set(false), type : HDL.signal(ui.update_func(FPA.op)).set(""), PC : HDL.signal(() => 0).set(""), src1 : HDL.signal(() => 0).set(""), src2 : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(FPA.name)).set(""), value : HDL.signal(ui.update_func(FPA.value)).set(""), t_remaining : HDL.signal(ui.update_func(FPA.time)).set("") }); } })(); // (11) FP multiplier (() => { var n = conf.t_mul.length; FP_multiplier = []; for (var i = 0; i < n; i++) { var FPM = ui_ele.FPM[i]; FP_multiplier.push({ is_running : HDL.signal( ui.update_func(FPM.busy)).set(false), type : HDL.signal(ui.update_func(FPM.op)).set(""), PC : HDL.signal(() => 0).set(""), src1 : HDL.signal(() => 0).set(""), src2 : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(FPM.name)).set(""), value : HDL.signal(ui.update_func(FPM.value)).set(""), t_remaining : HDL.signal(ui.update_func(FPM.time)).set("") }); } })(); // (12) FP divider FP_divider = { is_running : HDL.signal( ui.update_func(ui_ele.FPD.is_running)).set(false), type : HDL.signal(ui.update_func(ui_ele.FPD.type)).set(""), PC : HDL.signal(() => 0).set(""), src1 : HDL.signal(() => 0).set(""), src2 : HDL.signal(() => 0).set(""), name : HDL.signal(ui.update_func(ui_ele.FPD.name)).set(""), value : HDL.signal(() => 0).set(""), t_remaining : HDL.signal(ui.update_func(ui_ele.FPD.time)).set("") }; HDL.rising_edge(); // setTimeout(get_CPU_clock_func(), CPU_exec_delay_time + 1000); }; var CPU_power_off = function() { if (!has_power) { throw "ERROR: already powered off"; } ++CPU_exec_id; has_power = false; }; var CPU_run = () => { if (!has_power) { throw "ERROR: run while powered off"; } setTimeout(get_CPU_clock_func(), 100); }; var CPU_pause = () => { ++CPU_exec_id; } var CPU_step = () => { if (!has_power) { throw "ERROR: step while powered off"; } get_CPU_clock_func()(); ++CPU_exec_id; }; return { do_load : CPU_do_load, load_config : CPU_load_config, power_on : CPU_power_on, power_off : CPU_power_off, run : CPU_run, pause : CPU_pause, step : CPU_step, get_config : function() { return conf; } }; })();
fix a bug in FPM/FPD
js/CPU.js
fix a bug in FPM/FPD
<ide><path>s/CPU.js <ide> <ide> var e = undefined; <ide> var check = (t) => { <del> if (t.is_running.val()) { <add> if (t.name == WB_name) { <ide> e = t; <ide> } <ide> }; <ide> <ide> var e = undefined; <ide> var check = (t) => { <del> if (t.is_running.val()) { <add> if (t.name == WB_name) { <ide> e = t; <ide> } <ide> };
Java
apache-2.0
55e6d4e1398f27d897795a174a332d6e18642b08
0
gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger,gzsombor/ranger
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ranger.biz; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.entity.XXGroupPermission; import org.apache.ranger.entity.XXModuleDef; import org.apache.ranger.entity.XXUserPermission; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem; import org.apache.ranger.service.RangerPolicyService; import org.apache.ranger.service.XGroupPermissionService; import org.apache.ranger.service.XModuleDefService; import org.apache.ranger.service.XPortalUserService; import org.apache.ranger.service.XResourceService; import org.apache.ranger.service.XUserPermissionService; import org.apache.ranger.view.VXGroupPermission; import org.apache.ranger.view.VXModuleDef; import org.apache.ranger.view.VXUserPermission; import org.apache.log4j.Logger; import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXAuditMapDao; import org.apache.ranger.db.XXAuthSessionDao; import org.apache.ranger.db.XXGroupDao; import org.apache.ranger.db.XXGroupGroupDao; import org.apache.ranger.db.XXGroupPermissionDao; import org.apache.ranger.db.XXGroupUserDao; import org.apache.ranger.db.XXPermMapDao; import org.apache.ranger.db.XXPolicyDao; import org.apache.ranger.db.XXPortalUserDao; import org.apache.ranger.db.XXPortalUserRoleDao; import org.apache.ranger.db.XXResourceDao; import org.apache.ranger.db.XXUserDao; import org.apache.ranger.db.XXUserPermissionDao; import org.apache.ranger.entity.XXAuditMap; import org.apache.ranger.entity.XXAuthSession; import org.apache.ranger.entity.XXGroup; import org.apache.ranger.entity.XXGroupGroup; import org.apache.ranger.entity.XXGroupUser; import org.apache.ranger.entity.XXPermMap; import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.entity.XXResource; import org.apache.ranger.entity.XXTrxLog; import org.apache.ranger.entity.XXUser; import org.apache.ranger.service.XGroupService; import org.apache.ranger.service.XUserService; import org.apache.ranger.view.VXAuditMap; import org.apache.ranger.view.VXAuditMapList; import org.apache.ranger.view.VXGroup; import org.apache.ranger.view.VXGroupGroup; import org.apache.ranger.view.VXGroupList; import org.apache.ranger.view.VXGroupUser; import org.apache.ranger.view.VXGroupUserInfo; import org.apache.ranger.view.VXGroupUserList; import org.apache.ranger.view.VXLong; import org.apache.ranger.view.VXPermMap; import org.apache.ranger.view.VXPermMapList; import org.apache.ranger.view.VXPortalUser; import org.apache.ranger.view.VXUser; import org.apache.ranger.view.VXUserGroupInfo; import org.apache.ranger.view.VXUserList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import org.apache.ranger.view.VXResponse; import org.apache.ranger.entity.XXPortalUserRole; import org.apache.ranger.view.VXString; import org.apache.ranger.view.VXStringList; @Component public class XUserMgr extends XUserMgrBase { @Autowired XUserService xUserService; @Autowired XGroupService xGroupService; @Autowired RangerBizUtil msBizUtil; @Autowired UserMgr userMgr; @Autowired RangerDaoManager daoManager; @Autowired RangerBizUtil xaBizUtil; @Autowired XModuleDefService xModuleDefService; @Autowired XUserPermissionService xUserPermissionService; @Autowired XGroupPermissionService xGroupPermissionService; @Autowired XPortalUserService xPortalUserService; @Autowired XResourceService xResourceService; @Autowired SessionMgr sessionMgr; @Autowired RangerPolicyService policyService; @Autowired ServiceDBStore svcStore; @Autowired GUIDUtil guidUtil; static final Logger logger = Logger.getLogger(XUserMgr.class); public VXUser getXUserByUserName(String userName) { VXUser vXUser=null; vXUser=xUserService.getXUserByUserName(userName); if(vXUser!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ vXUser=getMaskedVXUser(vXUser); } return vXUser; } public VXGroup getGroupByGroupName(String groupName) { VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); if (vxGroup == null) { throw restErrorUtil.createRESTException( groupName + " is Not Found", MessageEnums.DATA_NOT_FOUND); } return vxGroup; } public VXUser createXUser(VXUser vXUser) { checkAdminAccess(); validatePassword(vXUser); String userName = vXUser.getName(); if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { throw restErrorUtil.createRESTException( "Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA); } if (vXUser.getDescription() == null) { setUserDesc(vXUser); } String actualPassword = vXUser.getPassword(); VXPortalUser vXPortalUser = new VXPortalUser(); vXPortalUser.setLoginId(userName); vXPortalUser.setFirstName(vXUser.getFirstName()); if("null".equalsIgnoreCase(vXPortalUser.getFirstName())){ vXPortalUser.setFirstName(""); } vXPortalUser.setLastName(vXUser.getLastName()); if("null".equalsIgnoreCase(vXPortalUser.getLastName())){ vXPortalUser.setLastName(""); } vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); } else { vXPortalUser.setPublicScreenName(vXUser.getName()); } vXPortalUser.setPassword(actualPassword); vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); vXPortalUser = userMgr.createDefaultAccountUser(vXPortalUser); VXUser createdXUser = xUserService.createResource(vXUser); createdXUser.setPassword(actualPassword); List<XXTrxLog> trxLogList = xUserService.getTransactionLog( createdXUser, "create"); String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); createdXUser.setPassword(hiddenPassword); Collection<Long> groupIdList = vXUser.getGroupIdList(); List<VXGroupUser> vXGroupUsers = new ArrayList<VXGroupUser>(); if (groupIdList != null) { for (Long groupId : groupIdList) { VXGroupUser vXGroupUser = createXGroupUser( createdXUser.getId(), groupId); // trxLogList.addAll(xGroupUserService.getTransactionLog( // vXGroupUser, "create")); vXGroupUsers.add(vXGroupUser); } } for (VXGroupUser vXGroupUser : vXGroupUsers) { trxLogList.addAll(xGroupUserService.getTransactionLog(vXGroupUser, "create")); } // xaBizUtil.createTrxLog(trxLogList); if(vXPortalUser!=null){ assignPermissionToUser(vXPortalUser, true); } return createdXUser; } public void assignPermissionToUser(VXPortalUser vXPortalUser, boolean isCreate) { HashMap<String, Long> moduleNameId = getAllModuleNameAndIdMap(); if(moduleNameId!=null && vXPortalUser!=null){ if(CollectionUtils.isNotEmpty(vXPortalUser.getUserRoleList())){ for (String role : vXPortalUser.getUserRoleList()) { if (role.equals(RangerConstants.ROLE_USER)) { createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); } else if (role.equals(RangerConstants.ROLE_SYS_ADMIN)) { createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_AUDIT), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_USER_GROUPS), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES), isCreate); } else if (role.equals(RangerConstants.ROLE_KEY_ADMIN)) { createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_KEY_MANAGER), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); } } } } } // Insert or Updating Mapping permissions depending upon roles public void createOrUpdateUserPermisson(VXPortalUser portalUser, Long moduleId, boolean isCreate) { VXUserPermission vXUserPermission; XXUserPermission xUserPermission = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(portalUser.getId(), moduleId); if (xUserPermission == null) { vXUserPermission = new VXUserPermission(); // When Creating XXUserPermission UI sends xUserId, to keep it consistent here xUserId should be used XXUser xUser = daoManager.getXXUser().findByPortalUserId(portalUser.getId()); if (xUser == null) { logger.warn("Could not found corresponding xUser for username: [" + portalUser.getLoginId() + "], So not assigning permission to this user"); return; } else { vXUserPermission.setUserId(xUser.getId()); } vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); vXUserPermission.setModuleId(moduleId); try { vXUserPermission = this.createXUserPermission(vXUserPermission); logger.info("Permission assigned to user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); } catch (Exception e) { logger.error("Error while assigning permission to user: [" + portalUser.getLoginId() + "] for module: [" + moduleId + "]", e); } } else if (isCreate) { vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); vXUserPermission = this.updateXUserPermission(vXUserPermission); logger.info("Permission Updated for user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); } } public HashMap<String, Long> getAllModuleNameAndIdMap() { List<XXModuleDef> xXModuleDefs = daoManager.getXXModuleDef().getAll(); if (!CollectionUtils.isEmpty(xXModuleDefs)) { HashMap<String, Long> moduleNameAndIdMap = new HashMap<String, Long>(); for (XXModuleDef xXModuleDef : xXModuleDefs) { moduleNameAndIdMap.put(xXModuleDef.getModule(), xXModuleDef.getId()); } return moduleNameAndIdMap; } return null; } private VXGroupUser createXGroupUser(Long userId, Long groupId) { VXGroupUser vXGroupUser = new VXGroupUser(); vXGroupUser.setParentGroupId(groupId); vXGroupUser.setUserId(userId); VXGroup vXGroup = xGroupService.readResource(groupId); vXGroupUser.setName(vXGroup.getName()); vXGroupUser = xGroupUserService.createResource(vXGroupUser); return vXGroupUser; } public VXUser updateXUser(VXUser vXUser) { if (vXUser == null || vXUser.getName() == null || "null".equalsIgnoreCase(vXUser.getName()) || vXUser.getName().trim().isEmpty()) { throw restErrorUtil.createRESTException("Please provide a valid " + "username.", MessageEnums.INVALID_INPUT_DATA); } checkAccess(vXUser.getName()); VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser .getName()); VXPortalUser vXPortalUser = new VXPortalUser(); if (oldUserProfile != null && oldUserProfile.getId() != null) { vXPortalUser.setId(oldUserProfile.getId()); } // TODO : There is a possibility that old user may not exist. vXPortalUser.setFirstName(vXUser.getFirstName()); if("null".equalsIgnoreCase(vXPortalUser.getFirstName())){ vXPortalUser.setFirstName(""); } vXPortalUser.setLastName(vXUser.getLastName()); if("null".equalsIgnoreCase(vXPortalUser.getLastName())){ vXPortalUser.setLastName(""); } vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); vXPortalUser.setLoginId(vXUser.getName()); vXPortalUser.setStatus(vXUser.getStatus()); vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); } else { vXPortalUser.setPublicScreenName(vXUser.getName()); } vXPortalUser.setUserSource(vXUser.getUserSource()); String hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); String password = vXUser.getPassword(); if (oldUserProfile != null && password != null && password.equals(hiddenPasswordString)) { vXPortalUser.setPassword(oldUserProfile.getPassword()); } else if(password != null){ validatePassword(vXUser); vXPortalUser.setPassword(password); } Collection<Long> groupIdList = vXUser.getGroupIdList(); XXPortalUser xXPortalUser = new XXPortalUser(); xXPortalUser = userMgr.updateUserWithPass(vXPortalUser); //update permissions start Collection<String> roleListUpdatedProfile =new ArrayList<String>(); if (oldUserProfile != null && oldUserProfile.getId() != null) { if(vXUser!=null && vXUser.getUserRoleList()!=null){ Collection<String> roleListOldProfile = oldUserProfile.getUserRoleList(); Collection<String> roleListNewProfile = vXUser.getUserRoleList(); if(roleListNewProfile!=null && roleListOldProfile!=null){ for (String role : roleListNewProfile) { if(role!=null && !roleListOldProfile.contains(role)){ roleListUpdatedProfile.add(role); } } } } } if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ vXPortalUser.setUserRoleList(roleListUpdatedProfile); List<XXUserPermission> xuserPermissionList = daoManager .getXXUserPermission() .findByUserPermissionId(vXPortalUser.getId()); if (xuserPermissionList!=null && xuserPermissionList.size()>0){ for (XXUserPermission xXUserPermission : xuserPermissionList) { if (xXUserPermission != null) { try { xUserPermissionService.deleteResource(xXUserPermission.getId()); } catch (Exception e) { logger.error(e.getMessage()); } } } } assignPermissionToUser(vXPortalUser,true); } //update permissions end Collection<String> roleList = new ArrayList<String>(); if (xXPortalUser != null) { roleList = userMgr.getRolesForUser(xXPortalUser); } if (roleList == null || roleList.size() == 0) { roleList = new ArrayList<String>(); roleList.add(RangerConstants.ROLE_USER); } // TODO I've to get the transaction log from here. // There is nothing to log anything in XXUser so far. vXUser = xUserService.updateResource(vXUser); vXUser.setUserRoleList(roleList); vXUser.setPassword(password); List<XXTrxLog> trxLogList = xUserService.getTransactionLog(vXUser, oldUserProfile, "update"); vXUser.setPassword(hiddenPasswordString); Long userId = vXUser.getId(); List<Long> groupUsersToRemove = new ArrayList<Long>(); if (groupIdList != null) { SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xUserId", userId); VXGroupUserList vXGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList(); if (vXGroupUsers != null) { // Create for (Long groupId : groupIdList) { boolean found = false; for (VXGroupUser vXGroupUser : vXGroupUsers) { if (groupId.equals(vXGroupUser.getParentGroupId())) { found = true; break; } } if (!found) { VXGroupUser vXGroupUser = createXGroupUser(userId, groupId); trxLogList.addAll(xGroupUserService.getTransactionLog( vXGroupUser, "create")); } } // Delete for (VXGroupUser vXGroupUser : vXGroupUsers) { boolean found = false; for (Long groupId : groupIdList) { if (groupId.equals(vXGroupUser.getParentGroupId())) { trxLogList.addAll(xGroupUserService .getTransactionLog(vXGroupUser, "update")); found = true; break; } } if (!found) { // TODO I've to get the transaction log from here. trxLogList.addAll(xGroupUserService.getTransactionLog( vXGroupUser, "delete")); groupUsersToRemove.add(vXGroupUser.getId()); // xGroupUserService.deleteResource(vXGroupUser.getId()); } } } else { for (Long groupId : groupIdList) { VXGroupUser vXGroupUser = createXGroupUser(userId, groupId); trxLogList.addAll(xGroupUserService.getTransactionLog( vXGroupUser, "create")); } } vXUser.setGroupIdList(groupIdList); } else { logger.debug("Group id list can't be null for user. Group user " + "mapping not updated for user : " + userId); } xaBizUtil.createTrxLog(trxLogList); for (Long groupUserId : groupUsersToRemove) { xGroupUserService.deleteResource(groupUserId); } return vXUser; } public VXUserGroupInfo createXUserGroupFromMap( VXUserGroupInfo vXUserGroupInfo) { checkAdminAccess(); VXUserGroupInfo vxUGInfo = new VXUserGroupInfo(); VXUser vXUser = vXUserGroupInfo.getXuserInfo(); vXUser = xUserService.createXUserWithOutLogin(vXUser); vxUGInfo.setXuserInfo(vXUser); List<VXGroup> vxg = new ArrayList<VXGroup>(); for (VXGroup vXGroup : vXUserGroupInfo.getXgroupInfo()) { VXGroup VvXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); vxg.add(VvXGroup); VXGroupUser vXGroupUser = new VXGroupUser(); vXGroupUser.setUserId(vXUser.getId()); vXGroupUser.setName(VvXGroup.getName()); vXGroupUser = xGroupUserService .createXGroupUserWithOutLogin(vXGroupUser); } VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(vXUser .getName()); if(vXPortalUser!=null){ assignPermissionToUser(vXPortalUser, true); } vxUGInfo.setXgroupInfo(vxg); return vxUGInfo; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public VXGroupUserInfo createXGroupUserFromMap( VXGroupUserInfo vXGroupUserInfo) { checkAdminAccess(); VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); VXGroup vXGroup = vXGroupUserInfo.getXgroupInfo(); // Add the group user mappings for a given group to x_group_user table /*XXGroup xGroup = daoManager.getXXGroup().findByGroupName(vXGroup.getName()); if (xGroup == null) { return vxGUInfo; }*/ List<VXUser> vxu = new ArrayList<VXUser>(); for (VXUser vXUser : vXGroupUserInfo.getXuserInfo()) { XXUser xUser = daoManager.getXXUser().findByUserName(vXUser.getName()); if (xUser != null) { // Add or update group user mapping only if the user already exists in x_user table. vXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); vxGUInfo.setXgroupInfo(vXGroup); vxu.add(vXUser); VXGroupUser vXGroupUser = new VXGroupUser(); vXGroupUser.setUserId(xUser.getId()); vXGroupUser.setName(vXGroup.getName()); vXGroupUser = xGroupUserService .createXGroupUserWithOutLogin(vXGroupUser); } } vxGUInfo.setXuserInfo(vxu); return vxGUInfo; } public VXGroupUserInfo getXGroupUserFromMap( String groupName) { checkAdminAccess(); VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); XXGroup xGroup = daoManager.getXXGroup().findByGroupName(groupName); if (xGroup == null) { return vxGUInfo; } VXGroup xgroupInfo = xGroupService.populateViewBean(xGroup); vxGUInfo.setXgroupInfo(xgroupInfo); SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", xGroup.getId()); VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); List<VXUser> vxu = new ArrayList<VXUser>(); logger.debug("removing all the group user mapping for : " + xGroup.getName()); for (VXGroupUser groupUser : vxGroupUserList.getList()) { XXUser xUser = daoManager.getXXUser().getById(groupUser.getUserId()); if (xUser != null) { VXUser vxUser = new VXUser(); vxUser.setName(xUser.getName()); vxu.add(vxUser); } } vxGUInfo.setXuserInfo(vxu); return vxGUInfo; } public VXUser createXUserWithOutLogin(VXUser vXUser) { checkAdminAccess(); validatePassword(vXUser); return xUserService.createXUserWithOutLogin(vXUser); } public VXGroup createXGroup(VXGroup vXGroup) { checkAdminAccess(); if (vXGroup.getDescription() == null) { vXGroup.setDescription(vXGroup.getName()); } vXGroup = xGroupService.createResource(vXGroup); List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup, "create"); xaBizUtil.createTrxLog(trxLogList); return vXGroup; } public VXGroup createXGroupWithoutLogin(VXGroup vXGroup) { checkAdminAccess(); return xGroupService.createXGroupWithOutLogin(vXGroup); } public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) { checkAdminAccess(); vXGroupUser = xGroupUserService .createXGroupUserWithOutLogin(vXGroupUser); return vXGroupUser; } public VXUser getXUser(Long id) { VXUser vXUser=null; vXUser=xUserService.readResourceWithOutLogin(id); if(vXUser!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ vXUser=getMaskedVXUser(vXUser); } return vXUser; } public VXGroupUser getXGroupUser(Long id) { return xGroupUserService.readResourceWithOutLogin(id); } public VXGroup getXGroup(Long id) { VXGroup vXGroup=null; vXGroup=xGroupService.readResourceWithOutLogin(id); if(vXGroup!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ vXGroup=getMaskedVXGroup(vXGroup); } return vXGroup; } /** * // public void createXGroupAndXUser(String groupName, String userName) { * * // Long groupId; // Long userId; // XXGroup xxGroup = // * appDaoManager.getXXGroup().findByGroupName(groupName); // VXGroup * vxGroup; // if (xxGroup == null) { // vxGroup = new VXGroup(); // * vxGroup.setName(groupName); // vxGroup.setDescription(groupName); // * vxGroup.setGroupType(AppConstants.XA_GROUP_USER); // * vxGroup.setPriAcctId(1l); // vxGroup.setPriGrpId(1l); // vxGroup = * xGroupService.createResource(vxGroup); // groupId = vxGroup.getId(); // } * else { // groupId = xxGroup.getId(); // } // XXUser xxUser = * appDaoManager.getXXUser().findByUserName(userName); // VXUser vxUser; // * if (xxUser == null) { // vxUser = new VXUser(); // * vxUser.setName(userName); // vxUser.setDescription(userName); // * vxUser.setPriGrpId(1l); // vxUser.setPriAcctId(1l); // vxUser = * xUserService.createResource(vxUser); // userId = vxUser.getId(); // } * else { // userId = xxUser.getId(); // } // VXGroupUser vxGroupUser = new * VXGroupUser(); // vxGroupUser.setParentGroupId(groupId); // * vxGroupUser.setUserId(userId); // vxGroupUser.setName(groupName); // * vxGroupUser.setPriAcctId(1l); // vxGroupUser.setPriGrpId(1l); // * vxGroupUser = xGroupUserService.createResource(vxGroupUser); * * // } */ public void deleteXGroupAndXUser(String groupName, String userName) { checkAdminAccess(); VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); VXUser vxUser = xUserService.getXUserByUserName(userName); SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", vxGroup.getId()); searchCriteria.addParam("xUserId", vxUser.getId()); VXGroupUserList vxGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); for (VXGroupUser vxGroupUser : vxGroupUserList.getList()) { daoManager.getXXGroupUser().remove(vxGroupUser.getId()); } } public VXGroupList getXUserGroups(Long xUserId) { SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xUserId", xUserId); VXGroupUserList vXGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); VXGroupList vXGroupList = new VXGroupList(); List<VXGroup> vXGroups = new ArrayList<VXGroup>(); if (vXGroupUserList != null) { List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList(); Set<Long> groupIdList = new HashSet<Long>(); for (VXGroupUser vXGroupUser : vXGroupUsers) { groupIdList.add(vXGroupUser.getParentGroupId()); } for (Long groupId : groupIdList) { VXGroup vXGroup = xGroupService.readResource(groupId); vXGroups.add(vXGroup); } vXGroupList.setVXGroups(vXGroups); } else { logger.debug("No groups found for user id : " + xUserId); } return vXGroupList; } public Set<String> getGroupsForUser(String userName) { Set<String> ret = new HashSet<String>(); try { VXUser user = getXUserByUserName(userName); if (user != null) { VXGroupList groups = getXUserGroups(user.getId()); if (groups != null && !CollectionUtils.isEmpty(groups.getList())) { for (VXGroup group : groups.getList()) { ret.add(group.getName()); } } else { if (logger.isDebugEnabled()) { logger.debug("getGroupsForUser('" + userName + "'): no groups found for user"); } } } else { if (logger.isDebugEnabled()) { logger.debug("getGroupsForUser('" + userName + "'): user not found"); } } } catch (Exception excp) { logger.error("getGroupsForUser('" + userName + "') failed", excp); } return ret; } public VXUserList getXGroupUsers(Long xGroupId) { SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", xGroupId); VXGroupUserList vXGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); VXUserList vXUserList = new VXUserList(); List<VXUser> vXUsers = new ArrayList<VXUser>(); if (vXGroupUserList != null) { List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList(); Set<Long> userIdList = new HashSet<Long>(); for (VXGroupUser vXGroupUser : vXGroupUsers) { userIdList.add(vXGroupUser.getUserId()); } for (Long userId : userIdList) { VXUser vXUser = xUserService.readResource(userId); vXUsers.add(vXUser); } vXUserList.setVXUsers(vXUsers); } else { logger.debug("No users found for group id : " + xGroupId); } return vXUserList; } // FIXME Hack : Unnecessary, to be removed after discussion. private void setUserDesc(VXUser vXUser) { vXUser.setDescription(vXUser.getName()); } @Override public VXGroup updateXGroup(VXGroup vXGroup) { checkAdminAccess(); XXGroup xGroup = daoManager.getXXGroup().getById(vXGroup.getId()); List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup, xGroup, "update"); xaBizUtil.createTrxLog(trxLogList); vXGroup = (VXGroup) xGroupService.updateResource(vXGroup); return vXGroup; } public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) { checkAdminAccess(); return super.updateXGroupUser(vXGroupUser); } public void deleteXGroupUser(Long id, boolean force) { checkAdminAccess(); super.deleteXGroupUser(id, force); } public VXGroupGroup createXGroupGroup(VXGroupGroup vXGroupGroup){ checkAdminAccess(); return super.createXGroupGroup(vXGroupGroup); } public VXGroupGroup updateXGroupGroup(VXGroupGroup vXGroupGroup) { checkAdminAccess(); return super.updateXGroupGroup(vXGroupGroup); } public void deleteXGroupGroup(Long id, boolean force) { checkAdminAccess(); super.deleteXGroupGroup(id, force); } public void deleteXPermMap(Long id, boolean force) { if (force) { XXPermMap xPermMap = daoManager.getXXPermMap().getById(id); if (xPermMap != null) { if (xResourceService.readResource(xPermMap.getResourceId()) == null) { throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); } } xPermMapService.deleteResource(id); } else { throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } public VXLong getXPermMapSearchCount(SearchCriteria searchCriteria) { VXPermMapList permMapList = xPermMapService.searchXPermMaps(searchCriteria); VXLong vXLong = new VXLong(); vXLong.setValue(permMapList.getListSize()); return vXLong; } public void deleteXAuditMap(Long id, boolean force) { if (force) { XXAuditMap xAuditMap = daoManager.getXXAuditMap().getById(id); if (xAuditMap != null) { if (xResourceService.readResource(xAuditMap.getResourceId()) == null) { throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); } } xAuditMapService.deleteResource(id); } else { throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } public VXLong getXAuditMapSearchCount(SearchCriteria searchCriteria) { VXAuditMapList auditMapList = xAuditMapService.searchXAuditMaps(searchCriteria); VXLong vXLong = new VXLong(); vXLong.setValue(auditMapList.getListSize()); return vXLong; } public void modifyUserVisibility(HashMap<Long, Integer> visibilityMap) { checkAdminAccess(); Set<Map.Entry<Long, Integer>> entries = visibilityMap.entrySet(); for (Map.Entry<Long, Integer> entry : entries) { XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); VXUser vObj = xUserService.populateViewBean(xUser); vObj.setIsVisible(entry.getValue()); vObj = xUserService.updateResource(vObj); } } public void modifyGroupsVisibility(HashMap<Long, Integer> groupVisibilityMap) { checkAdminAccess(); Set<Map.Entry<Long, Integer>> entries = groupVisibilityMap.entrySet(); for (Map.Entry<Long, Integer> entry : entries) { XXGroup xGroup = daoManager.getXXGroup().getById(entry.getKey()); VXGroup vObj = xGroupService.populateViewBean(xGroup); vObj.setIsVisible(entry.getValue()); vObj = xGroupService.updateResource(vObj); } } // Module permissions public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) { XXModuleDef xModDef = daoManager.getXXModuleDef().findByModuleName(vXModuleDef.getModule()); if (xModDef != null) { throw restErrorUtil.createRESTException("Module Def with same name already exists.", MessageEnums.ERROR_DUPLICATE_OBJECT); } return xModuleDefService.createResource(vXModuleDef); } public VXModuleDef getXModuleDefPermission(Long id) { return xModuleDefService.readResource(id); } public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) { List<VXGroupPermission> groupPermListNew = vXModuleDef.getGroupPermList(); List<VXUserPermission> userPermListNew = vXModuleDef.getUserPermList(); List<VXGroupPermission> groupPermListOld = new ArrayList<VXGroupPermission>(); List<VXUserPermission> userPermListOld = new ArrayList<VXUserPermission>(); XXModuleDef xModuleDef = daoManager.getXXModuleDef().getById(vXModuleDef.getId()); VXModuleDef vModuleDefPopulateOld = xModuleDefService.populateViewBean(xModuleDef); List<XXGroupPermission> xgroupPermissionList = daoManager.getXXGroupPermission().findByModuleId(vXModuleDef.getId(), true); Map<Long, XXGroup> xXGroupMap=xGroupService.getXXGroupIdXXGroupMap(); if(xXGroupMap==null || xXGroupMap.isEmpty()){ for (XXGroupPermission xGrpPerm : xgroupPermissionList) { VXGroupPermission vXGrpPerm = xGroupPermissionService.populateViewBean(xGrpPerm); groupPermListOld.add(vXGrpPerm); } }else{ groupPermListOld=xGroupPermissionService.getPopulatedVXGroupPermissionList(xgroupPermissionList,xXGroupMap,vModuleDefPopulateOld); } vModuleDefPopulateOld.setGroupPermList(groupPermListOld); List<XXUserPermission> xuserPermissionList = daoManager.getXXUserPermission().findByModuleId(vXModuleDef.getId(), true); Map<Long, XXUser> xXPortalUserIdXXUserMap=xUserService.getXXPortalUserIdXXUserMap(); if(xXPortalUserIdXXUserMap==null || xXPortalUserIdXXUserMap.isEmpty()){ for (XXUserPermission xUserPerm : xuserPermissionList) { VXUserPermission vUserPerm = xUserPermissionService.populateViewBean(xUserPerm); userPermListOld.add(vUserPerm); } }else{ userPermListOld=xUserPermissionService.getPopulatedVXUserPermissionList(xuserPermissionList,xXPortalUserIdXXUserMap,vModuleDefPopulateOld); } vModuleDefPopulateOld.setUserPermList(userPermListOld); if (groupPermListOld != null && groupPermListNew != null) { for (VXGroupPermission newVXGroupPerm : groupPermListNew) { boolean isExist = false; for (VXGroupPermission oldVXGroupPerm : groupPermListOld) { if (newVXGroupPerm.getModuleId().equals(oldVXGroupPerm.getModuleId()) && newVXGroupPerm.getGroupId().equals(oldVXGroupPerm.getGroupId())) { if (!newVXGroupPerm.getIsAllowed().equals(oldVXGroupPerm.getIsAllowed())) { oldVXGroupPerm.setIsAllowed(newVXGroupPerm.getIsAllowed()); oldVXGroupPerm = this.updateXGroupPermission(oldVXGroupPerm); } isExist = true; } } if (!isExist) { newVXGroupPerm = this.createXGroupPermission(newVXGroupPerm); } } } if (userPermListOld != null && userPermListNew != null) { for (VXUserPermission newVXUserPerm : userPermListNew) { boolean isExist = false; for (VXUserPermission oldVXUserPerm : userPermListOld) { if (newVXUserPerm.getModuleId().equals(oldVXUserPerm.getModuleId()) && newVXUserPerm.getUserId().equals(oldVXUserPerm.getUserId())) { if (!newVXUserPerm.getIsAllowed().equals(oldVXUserPerm.getIsAllowed())) { oldVXUserPerm.setIsAllowed(newVXUserPerm.getIsAllowed()); oldVXUserPerm = this.updateXUserPermission(oldVXUserPerm); } isExist = true; } } if (!isExist) { newVXUserPerm = this.createXUserPermission(newVXUserPerm); } } } vXModuleDef = xModuleDefService.updateResource(vXModuleDef); return vXModuleDef; } public void deleteXModuleDefPermission(Long id, boolean force) { daoManager.getXXUserPermission().deleteByModuleId(id); daoManager.getXXGroupPermission().deleteByModuleId(id); xModuleDefService.deleteResource(id); } // User permission public VXUserPermission createXUserPermission(VXUserPermission vXUserPermission) { vXUserPermission = xUserPermissionService.createResource(vXUserPermission); Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Assigning permission to user who's found logged in into system, so updating permission in session of that user: [" + vXUserPermission.getUserName() + "]"); sessionMgr.resetUserModulePermission(userSession); } } return vXUserPermission; } public VXUserPermission getXUserPermission(Long id) { return xUserPermissionService.readResource(id); } public VXUserPermission updateXUserPermission(VXUserPermission vXUserPermission) { vXUserPermission = xUserPermissionService.updateResource(vXUserPermission); Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Updating permission of user who's found logged in into system, so updating permission in session of user: [" + vXUserPermission.getUserName() + "]"); sessionMgr.resetUserModulePermission(userSession); } } return vXUserPermission; } public void deleteXUserPermission(Long id, boolean force) { XXUserPermission xUserPermission = daoManager.getXXUserPermission().getById(id); if (xUserPermission == null) { throw restErrorUtil.createRESTException("No UserPermission found to delete, ID: " + id, MessageEnums.DATA_NOT_FOUND); } xUserPermissionService.deleteResource(id); Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(xUserPermission.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("deleting permission of user who's found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } // Group permission public VXGroupPermission createXGroupPermission(VXGroupPermission vXGroupPermission) { vXGroupPermission = xGroupPermissionService.createResource(vXGroupPermission); List<XXGroupUser> grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); for (XXGroupUser xGrpUser : grpUsers) { Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Assigning permission to group, one of the user belongs to that group found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } return vXGroupPermission; } public VXGroupPermission getXGroupPermission(Long id) { return xGroupPermissionService.readResource(id); } public VXGroupPermission updateXGroupPermission(VXGroupPermission vXGroupPermission) { vXGroupPermission = xGroupPermissionService.updateResource(vXGroupPermission); List<XXGroupUser> grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); for (XXGroupUser xGrpUser : grpUsers) { Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Assigning permission to group whose one of the user found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } return vXGroupPermission; } public void deleteXGroupPermission(Long id, boolean force) { XXGroupPermission xGrpPerm = daoManager.getXXGroupPermission().getById(id); if (xGrpPerm == null) { throw restErrorUtil.createRESTException("No GroupPermission object with ID: [" + id + "found.", MessageEnums.DATA_NOT_FOUND); } xGroupPermissionService.deleteResource(id); List<XXGroupUser> grpUsers = daoManager.getXXGroupUser().findByGroupId(xGrpPerm.getGroupId()); for (XXGroupUser xGrpUser : grpUsers) { Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("deleting permission of the group whose one of the user found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } } public void modifyUserActiveStatus(HashMap<Long, Integer> statusMap) { checkAdminAccess(); UserSessionBase session = ContextUtil.getCurrentUserSession(); String currentUser=null; if(session!=null){ currentUser=session.getLoginId(); if(currentUser==null || currentUser.trim().isEmpty()){ currentUser=null; } } if(currentUser==null){ return; } Set<Map.Entry<Long, Integer>> entries = statusMap.entrySet(); for (Map.Entry<Long, Integer> entry : entries) { if(entry!=null && entry.getKey()!=null && entry.getValue()!=null){ XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); if(xUser!=null){ VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(xUser.getName()); if(vXPortalUser!=null){ if(vXPortalUser.getLoginId()!=null && !vXPortalUser.getLoginId().equalsIgnoreCase(currentUser)){ vXPortalUser.setStatus(entry.getValue()); userMgr.updateUser(vXPortalUser); } } } } } } public void checkAdminAccess() { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if (!session.isUserAdmin()) { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); throw restErrorUtil.generateRESTException(vXResponse); } } else { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } public void checkAccess(String loginID) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if (!session.isUserAdmin() && !session.isKeyAdmin() && !session.getLoginId().equalsIgnoreCase(loginID)) { throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); } } else { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) { VXPermMapList returnList; UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); // If user is system admin if (currentUserSession != null && currentUserSession.isUserAdmin()) { returnList = super.searchXPermMaps(searchCriteria); } else { returnList = new VXPermMapList(); int startIndex = searchCriteria.getStartIndex(); int pageSize = searchCriteria.getMaxRows(); searchCriteria.setStartIndex(0); searchCriteria.setMaxRows(Integer.MAX_VALUE); List<VXPermMap> resultList = xPermMapService.searchXPermMaps(searchCriteria).getVXPermMaps(); List<VXPermMap> adminPermResourceList = new ArrayList<VXPermMap>(); for (VXPermMap xXPermMap : resultList) { XXResource xRes = daoManager.getXXResource().getById(xXPermMap.getResourceId()); VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN); if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { adminPermResourceList.add(xXPermMap); } } if (adminPermResourceList.size() > 0) { populatePageList(adminPermResourceList, startIndex, pageSize, returnList); } } return returnList; } private void populatePageList(List<VXPermMap> permMapList, int startIndex, int pageSize, VXPermMapList vxPermMapList) { List<VXPermMap> onePageList = new ArrayList<VXPermMap>(); for (int i = startIndex; i < pageSize + startIndex && i < permMapList.size(); i++) { VXPermMap vXPermMap = permMapList.get(i); onePageList.add(vXPermMap); } vxPermMapList.setVXPermMaps(onePageList); vxPermMapList.setStartIndex(startIndex); vxPermMapList.setPageSize(pageSize); vxPermMapList.setResultSize(onePageList.size()); vxPermMapList.setTotalCount(permMapList.size()); } public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) { VXAuditMapList returnList; UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); // If user is system admin if (currentUserSession != null && currentUserSession.isUserAdmin()) { returnList = super.searchXAuditMaps(searchCriteria); } else { returnList = new VXAuditMapList(); int startIndex = searchCriteria.getStartIndex(); int pageSize = searchCriteria.getMaxRows(); searchCriteria.setStartIndex(0); searchCriteria.setMaxRows(Integer.MAX_VALUE); List<VXAuditMap> resultList = xAuditMapService.searchXAuditMaps(searchCriteria).getVXAuditMaps(); List<VXAuditMap> adminAuditResourceList = new ArrayList<VXAuditMap>(); for (VXAuditMap xXAuditMap : resultList) { XXResource xRes = daoManager.getXXResource().getById(xXAuditMap.getResourceId()); VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN); if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { adminAuditResourceList.add(xXAuditMap); } } if (adminAuditResourceList.size() > 0) { populatePageList(adminAuditResourceList, startIndex, pageSize, returnList); } } return returnList; } private void populatePageList(List<VXAuditMap> auditMapList, int startIndex, int pageSize, VXAuditMapList vxAuditMapList) { List<VXAuditMap> onePageList = new ArrayList<VXAuditMap>(); for (int i = startIndex; i < pageSize + startIndex && i < auditMapList.size(); i++) { VXAuditMap vXAuditMap = auditMapList.get(i); onePageList.add(vXAuditMap); } vxAuditMapList.setVXAuditMaps(onePageList); vxAuditMapList.setStartIndex(startIndex); vxAuditMapList.setPageSize(pageSize); vxAuditMapList.setResultSize(onePageList.size()); vxAuditMapList.setTotalCount(auditMapList.size()); } public void checkAccessRoles(List<String> stringRolesList) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null && stringRolesList!=null) { if (!session.isUserAdmin() && !session.isKeyAdmin()) { throw restErrorUtil.create403RESTException("Permission" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); }else{ if (session.isUserAdmin() && stringRolesList.contains(RangerConstants.ROLE_KEY_ADMIN)) { throw restErrorUtil.create403RESTException("Permission" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "") + " isn't permitted to perform the action."); } if (session.isKeyAdmin() && stringRolesList.contains(RangerConstants.ROLE_SYS_ADMIN)) { throw restErrorUtil.create403RESTException("Permission" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "") + " isn't permitted to perform the action."); } } }else{ VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } public VXStringList setUserRolesByExternalID(Long userId, List<VXString> vStringRolesList) { List<String> roleListNewProfile = new ArrayList<String>(); if(vStringRolesList!=null){ for (VXString vXString : vStringRolesList) { roleListNewProfile.add(vXString.getValue()); } } checkAccessRoles(roleListNewProfile); VXUser vXUser=getXUser(userId); List<XXPortalUserRole> portalUserRoleList =null; if(vXUser!=null && roleListNewProfile.size()>0){ VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); if(oldUserProfile!=null){ updateUserRolesPermissions(oldUserProfile,roleListNewProfile); portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } }else{ throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } } public VXStringList setUserRolesByName(String userName, List<VXString> vStringRolesList) { List<String> roleListNewProfile = new ArrayList<String>(); if(vStringRolesList!=null){ for (VXString vXString : vStringRolesList) { roleListNewProfile.add(vXString.getValue()); } } checkAccessRoles(roleListNewProfile); if(userName!=null && roleListNewProfile.size()>0){ VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(userName); if(oldUserProfile!=null){ updateUserRolesPermissions(oldUserProfile,roleListNewProfile); List<XXPortalUserRole> portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } }else{ throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } } public VXStringList getUserRolesByExternalID(Long userId) { VXUser vXUser=getXUser(userId); if(vXUser==null){ throw restErrorUtil.createRESTException("Please provide a valid ID", MessageEnums.INVALID_INPUT_DATA); } checkAccess(vXUser.getName()); List<XXPortalUserRole> portalUserRoleList =null; VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); if(oldUserProfile!=null){ portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } } public VXStringList getUserRolesByName(String userName) { VXPortalUser vXPortalUser=null; if(userName!=null && !userName.trim().isEmpty()){ checkAccess(userName); vXPortalUser = userMgr.getUserProfileByLoginId(userName); if(vXPortalUser!=null && vXPortalUser.getUserRoleList()!=null){ List<XXPortalUserRole> portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(vXPortalUser.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); } }else{ throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); } } public void updateUserRolesPermissions(VXPortalUser oldUserProfile,List<String> roleListNewProfile){ //update permissions start Collection<String> roleListUpdatedProfile =new ArrayList<String>(); if (oldUserProfile != null && oldUserProfile.getId() != null) { Collection<String> roleListOldProfile = oldUserProfile.getUserRoleList(); if(roleListNewProfile!=null && roleListOldProfile!=null){ for (String role : roleListNewProfile) { if(role!=null && !roleListOldProfile.contains(role)){ roleListUpdatedProfile.add(role); } } } } if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ oldUserProfile.setUserRoleList(roleListUpdatedProfile); List<XXUserPermission> xuserPermissionList = daoManager .getXXUserPermission() .findByUserPermissionId(oldUserProfile.getId()); if (xuserPermissionList!=null && xuserPermissionList.size()>0){ for (XXUserPermission xXUserPermission : xuserPermissionList) { if (xXUserPermission != null) { xUserPermissionService.deleteResource(xXUserPermission.getId()); } } } assignPermissionToUser(oldUserProfile,true); if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ userMgr.updateRoles(oldUserProfile.getId(), oldUserProfile.getUserRoleList()); } } //update permissions end } public VXStringList getStringListFromUserRoleList( List<XXPortalUserRole> listXXPortalUserRole) { if(listXXPortalUserRole==null){ return null; } List<VXString> xStrList = new ArrayList<VXString>(); VXString vXStr=null; for (XXPortalUserRole userRole : listXXPortalUserRole) { if(userRole!=null){ vXStr = new VXString(); vXStr.setValue(userRole.getUserRole()); xStrList.add(vXStr); } } VXStringList vXStringList = new VXStringList(xStrList); return vXStringList; } public boolean hasAccess(String loginID) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if(session.isUserAdmin() || session.getLoginId().equalsIgnoreCase(loginID)){ return true; } } return false; } public VXUser getMaskedVXUser(VXUser vXUser) { if(vXUser!=null){ if(vXUser.getGroupIdList()!=null && vXUser.getGroupIdList().size()>0){ vXUser.setGroupIdList(new ArrayList<Long>()); } if(vXUser.getGroupNameList()!=null && vXUser.getGroupNameList().size()>0){ vXUser.setGroupNameList(getMaskedCollection(vXUser.getGroupNameList())); } if(vXUser.getUserRoleList()!=null && vXUser.getUserRoleList().size()>0){ vXUser.setUserRoleList(getMaskedCollection(vXUser.getUserRoleList())); } vXUser.setUpdatedBy(AppConstants.Masked_String); } return vXUser; } public VXGroup getMaskedVXGroup(VXGroup vXGroup) { if(vXGroup!=null){ vXGroup.setUpdatedBy(AppConstants.Masked_String); } return vXGroup; } @Override public VXUserList searchXUsers(SearchCriteria searchCriteria) { VXUserList vXUserList = new VXUserList(); VXUser vXUserExactMatch = null; try{ VXUserList vXUserListSort = new VXUserList(); if(searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null){ searchCriteria.setSortBy("name"); vXUserListSort = xUserService.searchXUsers(searchCriteria); vXUserExactMatch = getXUserByUserName((String)searchCriteria.getParamList().get("name")); } int vXUserExactMatchwithSearchCriteria = 0; if(vXUserExactMatch != null){ vXUserListSort = xUserService.searchXUsers(searchCriteria); HashMap<String, Object> searchCriteriaParamList = searchCriteria.getParamList(); vXUserExactMatchwithSearchCriteria = 1; for(Map.Entry<String, Object> entry:searchCriteriaParamList.entrySet()){ String caseKey=entry.getKey(); switch (caseKey.toLowerCase()) { case "isvisible": Integer isVisible = vXUserExactMatch.getIsVisible(); if(isVisible != null && !isVisible.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "status": Integer status = vXUserExactMatch.getStatus(); if(status != null && !status.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "usersource": Integer userSource = vXUserExactMatch.getUserSource(); if(userSource != null && !userSource.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "emailaddress": String email = vXUserExactMatch.getEmailAddress(); if(email != null && !email.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "userrole": if(vXUserExactMatch.getUserRoleList() != null && !vXUserExactMatch.getUserRoleList().contains(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "userrolelist": @SuppressWarnings("unchecked") Collection<String> userrolelist = (Collection<String>) entry.getValue(); if(!CollectionUtils.isEmpty(userrolelist)){ for(String role:userrolelist){ if(vXUserExactMatch.getUserRoleList() != null && vXUserExactMatch.getUserRoleList().contains(role)){ vXUserExactMatchwithSearchCriteria = 1; break; } else{ vXUserExactMatchwithSearchCriteria = -1; } } } break; default: logger.warn("XUserMgr.searchXUsers: unexpected searchCriteriaParam:" + caseKey); break; } if(vXUserExactMatchwithSearchCriteria == -1){ break; } } } if(vXUserExactMatchwithSearchCriteria == 1){ VXGroupList groups = getXUserGroups(vXUserExactMatch.getId()); if(groups.getListSize() > 0){ Collection<String> groupNameList = new ArrayList<String>(); Collection<Long> groupIdList = new ArrayList<Long>(); for(VXGroup group:groups.getList()){ groupIdList.add(group.getId()); groupNameList.add(group.getName()); } vXUserExactMatch.setGroupIdList(groupIdList); vXUserExactMatch.setGroupNameList(groupNameList); } List<VXUser> vXUsers = new ArrayList<VXUser>(); if(searchCriteria.getStartIndex() == 0){ vXUsers.add(0,vXUserExactMatch); } for(VXUser vxUser:vXUserListSort.getVXUsers()){ if(vXUserExactMatch.getId()!=null && vxUser!=null){ if(!vXUserExactMatch.getId().equals(vxUser.getId())){ vXUsers.add(vxUser); } } } vXUserList.setVXUsers(vXUsers); vXUserList.setStartIndex(searchCriteria.getStartIndex()); vXUserList.setResultSize(vXUserList.getVXUsers().size()); vXUserList.setTotalCount(vXUserListSort.getTotalCount()); vXUserList.setPageSize(searchCriteria.getMaxRows()); vXUserList.setSortBy(searchCriteria.getSortBy()); vXUserList.setSortType(searchCriteria.getSortType()); } } catch (Exception e){ logger.error("Error getting the exact match of user =>"+e); } if(vXUserList.getVXUsers().isEmpty()) { searchCriteria.setSortBy("id"); vXUserList = xUserService.searchXUsers(searchCriteria); } if(vXUserList!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ List<VXUser> vXUsers = new ArrayList<VXUser>(); if(vXUserList!=null && vXUserList.getListSize()>0){ for(VXUser vXUser:vXUserList.getList()){ vXUser=getMaskedVXUser(vXUser); vXUsers.add(vXUser); } vXUserList.setVXUsers(vXUsers); } } return vXUserList; } @Override public VXGroupList searchXGroups(SearchCriteria searchCriteria) { VXGroupList vXGroupList= new VXGroupList(); VXGroup vXGroupExactMatch = null; try{ VXGroupList vXGroupListSort= new VXGroupList(); if(searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null){ searchCriteria.setSortBy("name"); vXGroupListSort = xGroupService.searchXGroups(searchCriteria); vXGroupExactMatch = getGroupByGroupName((String)searchCriteria.getParamList().get("name")); } int vXGroupExactMatchwithSearchCriteria = 0; if(vXGroupExactMatch != null){ HashMap<String, Object> searchCriteriaParamList = searchCriteria.getParamList(); vXGroupExactMatchwithSearchCriteria = 1; for (Map.Entry<String, Object> entry: searchCriteriaParamList.entrySet()){ String caseKey=entry.getKey(); switch (caseKey.toLowerCase()) { case "isvisible": Integer isVisible = vXGroupExactMatch.getIsVisible(); if(isVisible != null && !isVisible.equals(entry.getValue())){ vXGroupExactMatchwithSearchCriteria = -1; } break; case "groupsource": Integer groupsource = vXGroupExactMatch.getGroupSource(); if(groupsource != null && !groupsource.equals(entry.getValue())){ vXGroupExactMatchwithSearchCriteria = -1; } break; default: logger.warn("XUserMgr.searchXGroups: unexpected searchCriteriaParam:" + caseKey); break; } if(vXGroupExactMatchwithSearchCriteria == -1){ break; } } } if(vXGroupExactMatchwithSearchCriteria == 1){ List<VXGroup> vXGroups = new ArrayList<VXGroup>(); if(searchCriteria.getStartIndex() == 0){ vXGroups.add(0,vXGroupExactMatch); } for(VXGroup vXGroup:vXGroupListSort.getList()){ if(vXGroupExactMatch.getId() != null && vXGroup != null){ if(!vXGroupExactMatch.getId().equals(vXGroup.getId())){ vXGroups.add(vXGroup); } } } vXGroupList.setVXGroups(vXGroups); vXGroupList.setStartIndex(searchCriteria.getStartIndex()); vXGroupList.setResultSize(vXGroupList.getList().size()); vXGroupList.setTotalCount(vXGroupListSort.getTotalCount()); vXGroupList.setPageSize(searchCriteria.getMaxRows()); vXGroupList.setSortBy(searchCriteria.getSortBy()); vXGroupList.setSortType(searchCriteria.getSortType()); } } catch (Exception e){ logger.error("Error getting the exact match of group =>"+e); } if(vXGroupList.getList().isEmpty()) { searchCriteria.setSortBy("id"); vXGroupList=xGroupService.searchXGroups(searchCriteria); } if(vXGroupList!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ if(vXGroupList!=null && vXGroupList.getListSize()>0){ List<VXGroup> listMasked=new ArrayList<VXGroup>(); for(VXGroup vXGroup:vXGroupList.getList()){ vXGroup=getMaskedVXGroup(vXGroup); listMasked.add(vXGroup); } vXGroupList.setVXGroups(listMasked); } } return vXGroupList; } public Collection<String> getMaskedCollection(Collection<String> listunMasked){ List<String> listMasked=new ArrayList<String>(); if(listunMasked!=null) { for(int i = 0; i < listunMasked.size(); i++) { listMasked.add(AppConstants.Masked_String); } } return listMasked; } public boolean hasAccessToModule(String moduleName){ UserSessionBase userSession = ContextUtil.getCurrentUserSession(); if (userSession != null && userSession.getLoginId()!=null){ VXUser vxUser = xUserService.getXUserByUserName(userSession.getLoginId()); if(vxUser!=null){ List<String> permissionList = daoManager.getXXModuleDef().findAccessibleModulesByUserId(userSession.getUserId(), vxUser.getId()); if(permissionList!=null && permissionList.contains(moduleName)){ return true; } } } return false; } public void deleteXGroup(Long id, boolean force) { checkAdminAccess(); XXGroupDao xXGroupDao = daoManager.getXXGroup(); XXGroup xXGroup = xXGroupDao.getById(id); VXGroup vXGroup = xGroupService.populateViewBean(xXGroup); if (vXGroup == null || StringUtil.isEmpty(vXGroup.getName())) { throw restErrorUtil.createRESTException("Group ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } if(logger.isDebugEnabled()){ logger.info("Force delete status="+force+" for group="+vXGroup.getName()); } SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", id); VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("groupId", id); VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("groupId", id); VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); XXGroupPermissionDao xXGroupPermissionDao=daoManager.getXXGroupPermission(); List<XXGroupPermission> xXGroupPermissions=xXGroupPermissionDao.findByGroupId(id); XXGroupGroupDao xXGroupGroupDao = daoManager.getXXGroupGroup(); List<XXGroupGroup> xXGroupGroups = xXGroupGroupDao.findByGroupId(id); XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); List<XXPolicy> xXPolicyList = xXPolicyDao.findByGroupId(id); logger.warn("Deleting GROUP : "+vXGroup.getName()); if (force) { //delete XXGroupUser records of matching group XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); XXUserDao xXUserDao = daoManager.getXXUser(); XXUser xXUser =null; for (VXGroupUser groupUser : vxGroupUserList.getList()) { if(groupUser!=null){ xXUser=xXUserDao.getById(groupUser.getUserId()); if(xXUser!=null){ logger.warn("Removing user '" + xXUser.getName() + "' from group '" + groupUser.getName() + "'"); } xGroupUserDao.remove(groupUser.getId()); } } //delete XXPermMap records of matching group XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); XXResourceDao xXResourceDao = daoManager.getXXResource(); XXResource xXResource =null; for (VXPermMap vXPermMap : vXPermMapList.getList()) { if(vXPermMap!=null){ xXResource=xXResourceDao.getById(vXPermMap.getResourceId()); if(xXResource!=null){ logger.warn("Deleting '" + AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()) + "' permission from policy ID='" + vXPermMap.getResourceId() + "' for group '" + vXPermMap.getGroupName() + "'"); } xXPermMapDao.remove(vXPermMap.getId()); } } //delete XXAuditMap records of matching group XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { if(vXAuditMap!=null){ xXResource=xXResourceDao.getById(vXAuditMap.getResourceId()); xXAuditMapDao.remove(vXAuditMap.getId()); } } //delete XXGroupGroupDao records of group-group mapping for (XXGroupGroup xXGroupGroup : xXGroupGroups) { if(xXGroupGroup!=null){ XXGroup xXGroupParent=xXGroupDao.getById(xXGroupGroup.getParentGroupId()); XXGroup xXGroupChild=xXGroupDao.getById(xXGroupGroup.getGroupId()); if(xXGroupParent!=null && xXGroupChild!=null){ logger.warn("Removing group '" + xXGroupChild.getName() + "' from group '" + xXGroupParent.getName() + "'"); } xXGroupGroupDao.remove(xXGroupGroup.getId()); } } //delete XXPolicyItemGroupPerm records of group for (XXPolicy xXPolicy : xXPolicyList) { RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); List<RangerPolicyItem> policyItems = rangerPolicy.getPolicyItems(); removeUserGroupReferences(policyItems,null,vXGroup.getName()); rangerPolicy.setPolicyItems(policyItems); List<RangerPolicyItem> denyPolicyItems = rangerPolicy.getDenyPolicyItems(); removeUserGroupReferences(denyPolicyItems,null,vXGroup.getName()); rangerPolicy.setDenyPolicyItems(denyPolicyItems); List<RangerPolicyItem> allowExceptions = rangerPolicy.getAllowExceptions(); removeUserGroupReferences(allowExceptions,null,vXGroup.getName()); rangerPolicy.setAllowExceptions(allowExceptions); List<RangerPolicyItem> denyExceptions = rangerPolicy.getDenyExceptions(); removeUserGroupReferences(denyExceptions,null,vXGroup.getName()); rangerPolicy.setDenyExceptions(denyExceptions); List<RangerDataMaskPolicyItem> dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); removeUserGroupReferences(dataMaskItems,null,vXGroup.getName()); rangerPolicy.setDataMaskPolicyItems(dataMaskItems); List<RangerRowFilterPolicyItem> rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); removeUserGroupReferences(rowFilterItems,null,vXGroup.getName()); rangerPolicy.setRowFilterPolicyItems(rowFilterItems); try { svcStore.updatePolicy(rangerPolicy); } catch (Throwable excp) { logger.error("updatePolicy(" + rangerPolicy + ") failed", excp); restErrorUtil.createRESTException(excp.getMessage()); } } if(CollectionUtils.isNotEmpty(xXGroupPermissions)){ for (XXGroupPermission xXGroupPermission : xXGroupPermissions) { if(xXGroupPermission!=null){ XXModuleDef xXModuleDef=daoManager.getXXModuleDef().findByModuleId(xXGroupPermission.getModuleId()); if(xXModuleDef!=null){ logger.warn("Deleting '" + xXModuleDef.getModule() + "' module permission for group '" + xXGroup.getName() + "'"); } xXGroupPermissionDao.remove(xXGroupPermission.getId()); } } } //delete XXGroup xXGroupDao.remove(id); //Create XXTrxLog List<XXTrxLog> xXTrxLogsXXGroup = xGroupService.getTransactionLog(xGroupService.populateViewBean(xXGroup), "delete"); xaBizUtil.createTrxLog(xXTrxLogsXXGroup); } else { boolean hasReferences=false; if(vxGroupUserList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && CollectionUtils.isNotEmpty(xXPolicyList)){ hasReferences=true; } if(hasReferences==false && vXPermMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && vXAuditMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && CollectionUtils.isNotEmpty(xXGroupGroups)){ hasReferences=true; } if(hasReferences==false && CollectionUtils.isNotEmpty(xXGroupPermissions)){ hasReferences=true; } if(hasReferences){ //change visibility to Hidden if(vXGroup.getIsVisible()==RangerCommonEnums.IS_VISIBLE){ vXGroup.setIsVisible(RangerCommonEnums.IS_HIDDEN); xGroupService.updateResource(vXGroup); } }else{ //delete XXGroup xXGroupDao.remove(id); //Create XXTrxLog List<XXTrxLog> xXTrxLogsXXGroup = xGroupService.getTransactionLog(xGroupService.populateViewBean(xXGroup), "delete"); xaBizUtil.createTrxLog(xXTrxLogsXXGroup); } } } public void deleteXUser(Long id, boolean force) { checkAdminAccess(); XXUserDao xXUserDao = daoManager.getXXUser(); XXUser xXUser = xXUserDao.getById(id); VXUser vXUser = xUserService.populateViewBean(xXUser); if(vXUser==null ||StringUtil.isEmpty(vXUser.getName())){ throw restErrorUtil.createRESTException("No user found with id=" + id); } XXPortalUserDao xXPortalUserDao=daoManager.getXXPortalUser(); XXPortalUser xXPortalUser=xXPortalUserDao.findByLoginId(vXUser.getName().trim()); VXPortalUser vXPortalUser=null; if(xXPortalUser!=null){ vXPortalUser=xPortalUserService.populateViewBean(xXPortalUser); } if(vXPortalUser==null ||StringUtil.isEmpty(vXPortalUser.getLoginId())){ throw restErrorUtil.createRESTException("No user found with id=" + id); } if (logger.isDebugEnabled()) { logger.debug("Force delete status="+force+" for user="+vXUser.getName()); } restrictSelfAccountDeletion(vXUser.getName().trim()); SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xUserId", id); VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("userId", id); VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("userId", id); VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); long xXPortalUserId=0; xXPortalUserId=vXPortalUser.getId(); XXAuthSessionDao xXAuthSessionDao=daoManager.getXXAuthSession(); XXUserPermissionDao xXUserPermissionDao=daoManager.getXXUserPermission(); XXPortalUserRoleDao xXPortalUserRoleDao=daoManager.getXXPortalUserRole(); List<XXAuthSession> xXAuthSessions=xXAuthSessionDao.getAuthSessionByUserId(xXPortalUserId); List<XXUserPermission> xXUserPermissions=xXUserPermissionDao.findByUserPermissionId(xXPortalUserId); List<XXPortalUserRole> xXPortalUserRoles=xXPortalUserRoleDao.findByUserId(xXPortalUserId); XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); List<XXPolicy> xXPolicyList=xXPolicyDao.findByUserId(id); logger.warn("Deleting User : "+vXUser.getName()); if (force) { //delete XXGroupUser mapping XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); for (VXGroupUser groupUser : vxGroupUserList.getList()) { if(groupUser!=null){ logger.warn("Removing user '" + vXUser.getName() + "' from group '" + groupUser.getName() + "'"); xGroupUserDao.remove(groupUser.getId()); } } //delete XXPermMap records of user XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); for (VXPermMap vXPermMap : vXPermMapList.getList()) { if(vXPermMap!=null){ logger.warn("Deleting '" + AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()) + "' permission from policy ID='" + vXPermMap.getResourceId() + "' for user '" + vXPermMap.getUserName() + "'"); xXPermMapDao.remove(vXPermMap.getId()); } } //delete XXAuditMap records of user XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { if(vXAuditMap!=null){ xXAuditMapDao.remove(vXAuditMap.getId()); } } //delete XXPortalUser references if(vXPortalUser!=null){ xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); if(xXAuthSessions!=null && xXAuthSessions.size()>0){ logger.warn("Deleting " + xXAuthSessions.size() + " login session records for user '" + vXPortalUser.getLoginId() + "'"); } for (XXAuthSession xXAuthSession : xXAuthSessions) { xXAuthSessionDao.remove(xXAuthSession.getId()); } for (XXUserPermission xXUserPermission : xXUserPermissions) { if(xXUserPermission!=null){ XXModuleDef xXModuleDef=daoManager.getXXModuleDef().findByModuleId(xXUserPermission.getModuleId()); if(xXModuleDef!=null){ logger.warn("Deleting '" + xXModuleDef.getModule() + "' module permission for user '" + vXPortalUser.getLoginId() + "'"); } xXUserPermissionDao.remove(xXUserPermission.getId()); } } for (XXPortalUserRole xXPortalUserRole : xXPortalUserRoles) { if(xXPortalUserRole!=null){ logger.warn("Deleting '" + xXPortalUserRole.getUserRole() + "' role for user '" + vXPortalUser.getLoginId() + "'"); xXPortalUserRoleDao.remove(xXPortalUserRole.getId()); } } } //delete XXPolicyItemUserPerm records of user for(XXPolicy xXPolicy:xXPolicyList){ RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); List<RangerPolicyItem> policyItems = rangerPolicy.getPolicyItems(); removeUserGroupReferences(policyItems,vXUser.getName(),null); rangerPolicy.setPolicyItems(policyItems); List<RangerPolicyItem> denyPolicyItems = rangerPolicy.getDenyPolicyItems(); removeUserGroupReferences(denyPolicyItems,vXUser.getName(),null); rangerPolicy.setDenyPolicyItems(denyPolicyItems); List<RangerPolicyItem> allowExceptions = rangerPolicy.getAllowExceptions(); removeUserGroupReferences(allowExceptions,vXUser.getName(),null); rangerPolicy.setAllowExceptions(allowExceptions); List<RangerPolicyItem> denyExceptions = rangerPolicy.getDenyExceptions(); removeUserGroupReferences(denyExceptions,vXUser.getName(),null); rangerPolicy.setDenyExceptions(denyExceptions); List<RangerDataMaskPolicyItem> dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); removeUserGroupReferences(dataMaskItems,vXUser.getName(),null); rangerPolicy.setDataMaskPolicyItems(dataMaskItems); List<RangerRowFilterPolicyItem> rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); removeUserGroupReferences(rowFilterItems,vXUser.getName(),null); rangerPolicy.setRowFilterPolicyItems(rowFilterItems); try{ svcStore.updatePolicy(rangerPolicy); }catch(Throwable excp) { logger.error("updatePolicy(" + rangerPolicy + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } } //delete XXUser entry of user xXUserDao.remove(id); //delete XXPortal entry of user logger.warn("Deleting Portal User : "+vXPortalUser.getLoginId()); xXPortalUserDao.remove(xXPortalUserId); List<XXTrxLog> trxLogList =xUserService.getTransactionLog(xUserService.populateViewBean(xXUser), "delete"); xaBizUtil.createTrxLog(trxLogList); if (xXPortalUser != null) { trxLogList=xPortalUserService .getTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), "delete"); xaBizUtil.createTrxLog(trxLogList); } } else { boolean hasReferences=false; if(vxGroupUserList!=null && vxGroupUserList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && xXPolicyList!=null && xXPolicyList.size()>0){ hasReferences=true; } if(hasReferences==false && vXPermMapList!=null && vXPermMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && vXAuditMapList!=null && vXAuditMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && xXAuthSessions!=null && xXAuthSessions.size()>0){ hasReferences=true; } if(hasReferences==false && xXUserPermissions!=null && xXUserPermissions.size()>0){ hasReferences=true; } if(hasReferences==false && xXPortalUserRoles!=null && xXPortalUserRoles.size()>0){ hasReferences=true; } if(hasReferences){ if(vXUser.getIsVisible()!=RangerCommonEnums.IS_HIDDEN){ logger.info("Updating visibility of user '"+vXUser.getName()+"' to Hidden!"); vXUser.setIsVisible(RangerCommonEnums.IS_HIDDEN); xUserService.updateResource(vXUser); } }else{ xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); //delete XXUser entry of user xXUserDao.remove(id); //delete XXPortal entry of user logger.warn("Deleting Portal User : "+vXPortalUser.getLoginId()); xXPortalUserDao.remove(xXPortalUserId); List<XXTrxLog> trxLogList =xUserService.getTransactionLog(xUserService.populateViewBean(xXUser), "delete"); xaBizUtil.createTrxLog(trxLogList); trxLogList=xPortalUserService.getTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), "delete"); xaBizUtil.createTrxLog(trxLogList); } } } private <T extends RangerPolicyItem> void removeUserGroupReferences(List<T> policyItems, String user, String group) { List<T> itemsToRemove = null; for(T policyItem : policyItems) { if(!StringUtil.isEmpty(user)) { policyItem.getUsers().remove(user); } if(!StringUtil.isEmpty(group)) { policyItem.getGroups().remove(group); } if(policyItem.getUsers().isEmpty() && policyItem.getGroups().isEmpty()) { if(itemsToRemove == null) { itemsToRemove = new ArrayList<T>(); } itemsToRemove.add(policyItem); } } if(CollectionUtils.isNotEmpty(itemsToRemove)) { policyItems.removeAll(itemsToRemove); } } public void restrictSelfAccountDeletion(String loginID) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if (!session.isUserAdmin()) { throw restErrorUtil.create403RESTException("Operation denied. LoggedInUser= "+session.getXXPortalUser().getLoginId() + " isn't permitted to perform the action."); }else{ if(!StringUtil.isEmpty(loginID) && loginID.equals(session.getLoginId())){ throw restErrorUtil.create403RESTException("Operation denied. LoggedInUser= "+session.getXXPortalUser().getLoginId() + " isn't permitted to delete his own profile."); } } } else { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public VXUser createServiceConfigUser(String userName){ if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { logger.error("User Name: "+userName); throw restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA); } VXUser vXUser = null; VXPortalUser vXPortalUser=null; XXUser xxUser = daoManager.getXXUser().findByUserName(userName); XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName); String actualPassword = ""; if(xxUser!=null){ vXUser = xUserService.populateViewBean(xxUser); return vXUser; } if(xxUser==null){ vXUser=new VXUser(); vXUser.setName(userName); vXUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); vXUser.setDescription(vXUser.getName()); actualPassword = vXUser.getPassword(); } if(xXPortalUser==null){ vXPortalUser=new VXPortalUser(); vXPortalUser.setLoginId(userName); vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); vXPortalUser.setFirstName(vXUser.getFirstName()); vXPortalUser.setLastName(vXUser.getLastName()); vXPortalUser.setPassword(vXUser.getPassword()); vXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); ArrayList<String> roleList = new ArrayList<String>(); roleList.add(RangerConstants.ROLE_USER); vXPortalUser.setUserRoleList(roleList); xXPortalUser = userMgr.mapVXPortalUserToXXPortalUser(vXPortalUser); xXPortalUser=userMgr.createUser(xXPortalUser, RangerCommonEnums.STATUS_ENABLED, roleList); } VXUser createdXUser=null; if(xxUser==null && vXUser!=null){ try{ createdXUser = xUserService.createResource(vXUser); }catch(Exception ex){ logger.error("Error creating user: "+createdXUser.getName(),ex); } } if(createdXUser!=null){ try{ logger.info("User created: "+createdXUser.getName()); createdXUser.setPassword(actualPassword); List<XXTrxLog> trxLogList = xUserService.getTransactionLog(createdXUser, "create"); String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); createdXUser.setPassword(hiddenPassword); xaBizUtil.createTrxLog(trxLogList); if(xXPortalUser!=null){ vXPortalUser=userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); assignPermissionToUser(vXPortalUser, true); } }catch(Exception ex){ logger.error("Error while assigning permissions to user: "+createdXUser.getName(),ex); } }else{ xxUser = daoManager.getXXUser().findByUserName(userName); if(xxUser!=null){ createdXUser = xUserService.populateViewBean(xxUser); } } return createdXUser; } private void validatePassword(VXUser vXUser) { if (vXUser.getPassword() != null && !vXUser.getPassword().isEmpty()) { boolean checkPassword = false; String pattern = "(?=.*[0-9])(?=.*[a-zA-Z]).{8,}"; checkPassword = vXUser.getPassword().trim().matches(pattern); if (!checkPassword) { logger.warn("validatePassword(). Password should be minimum 8 characters with min one alphabet and one numeric."); throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password should be minimum 8 characters with min one alphabet and one numeric", null); } } else { logger.warn("validatePassword(). Password cannot be blank/null."); throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password cannot be blank/null", null); } } }
security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.ranger.biz; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.collections.CollectionUtils; import org.apache.ranger.common.ContextUtil; import org.apache.ranger.common.GUIDUtil; import org.apache.ranger.common.RangerCommonEnums; import org.apache.ranger.entity.XXGroupPermission; import org.apache.ranger.entity.XXModuleDef; import org.apache.ranger.entity.XXUserPermission; import org.apache.ranger.plugin.model.RangerPolicy; import org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem; import org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem; import org.apache.ranger.service.RangerPolicyService; import org.apache.ranger.service.XGroupPermissionService; import org.apache.ranger.service.XModuleDefService; import org.apache.ranger.service.XPortalUserService; import org.apache.ranger.service.XResourceService; import org.apache.ranger.service.XUserPermissionService; import org.apache.ranger.view.VXGroupPermission; import org.apache.ranger.view.VXModuleDef; import org.apache.ranger.view.VXUserPermission; import org.apache.log4j.Logger; import org.apache.ranger.authorization.utils.StringUtil; import org.apache.ranger.common.AppConstants; import org.apache.ranger.common.MessageEnums; import org.apache.ranger.common.PropertiesUtil; import org.apache.ranger.common.RangerConstants; import org.apache.ranger.common.SearchCriteria; import org.apache.ranger.common.UserSessionBase; import org.apache.ranger.db.RangerDaoManager; import org.apache.ranger.db.XXAuditMapDao; import org.apache.ranger.db.XXAuthSessionDao; import org.apache.ranger.db.XXGroupDao; import org.apache.ranger.db.XXGroupGroupDao; import org.apache.ranger.db.XXGroupPermissionDao; import org.apache.ranger.db.XXGroupUserDao; import org.apache.ranger.db.XXPermMapDao; import org.apache.ranger.db.XXPolicyDao; import org.apache.ranger.db.XXPortalUserDao; import org.apache.ranger.db.XXPortalUserRoleDao; import org.apache.ranger.db.XXResourceDao; import org.apache.ranger.db.XXUserDao; import org.apache.ranger.db.XXUserPermissionDao; import org.apache.ranger.entity.XXAuditMap; import org.apache.ranger.entity.XXAuthSession; import org.apache.ranger.entity.XXGroup; import org.apache.ranger.entity.XXGroupGroup; import org.apache.ranger.entity.XXGroupUser; import org.apache.ranger.entity.XXPermMap; import org.apache.ranger.entity.XXPolicy; import org.apache.ranger.entity.XXPortalUser; import org.apache.ranger.entity.XXResource; import org.apache.ranger.entity.XXTrxLog; import org.apache.ranger.entity.XXUser; import org.apache.ranger.service.XGroupService; import org.apache.ranger.service.XUserService; import org.apache.ranger.view.VXAuditMap; import org.apache.ranger.view.VXAuditMapList; import org.apache.ranger.view.VXGroup; import org.apache.ranger.view.VXGroupGroup; import org.apache.ranger.view.VXGroupList; import org.apache.ranger.view.VXGroupUser; import org.apache.ranger.view.VXGroupUserInfo; import org.apache.ranger.view.VXGroupUserList; import org.apache.ranger.view.VXLong; import org.apache.ranger.view.VXPermMap; import org.apache.ranger.view.VXPermMapList; import org.apache.ranger.view.VXPortalUser; import org.apache.ranger.view.VXUser; import org.apache.ranger.view.VXUserGroupInfo; import org.apache.ranger.view.VXUserList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import org.apache.ranger.view.VXResponse; import org.apache.ranger.entity.XXPortalUserRole; import org.apache.ranger.view.VXString; import org.apache.ranger.view.VXStringList; @Component public class XUserMgr extends XUserMgrBase { @Autowired XUserService xUserService; @Autowired XGroupService xGroupService; @Autowired RangerBizUtil msBizUtil; @Autowired UserMgr userMgr; @Autowired RangerDaoManager daoManager; @Autowired RangerBizUtil xaBizUtil; @Autowired XModuleDefService xModuleDefService; @Autowired XUserPermissionService xUserPermissionService; @Autowired XGroupPermissionService xGroupPermissionService; @Autowired XPortalUserService xPortalUserService; @Autowired XResourceService xResourceService; @Autowired SessionMgr sessionMgr; @Autowired RangerPolicyService policyService; @Autowired ServiceDBStore svcStore; @Autowired GUIDUtil guidUtil; static final Logger logger = Logger.getLogger(XUserMgr.class); public VXUser getXUserByUserName(String userName) { VXUser vXUser=null; vXUser=xUserService.getXUserByUserName(userName); if(vXUser!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ vXUser=getMaskedVXUser(vXUser); } return vXUser; } public VXGroup getGroupByGroupName(String groupName) { VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); if (vxGroup == null) { throw restErrorUtil.createRESTException( groupName + " is Not Found", MessageEnums.DATA_NOT_FOUND); } return vxGroup; } public VXUser createXUser(VXUser vXUser) { checkAdminAccess(); validatePassword(vXUser); String userName = vXUser.getName(); if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { throw restErrorUtil.createRESTException( "Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA); } if (vXUser.getDescription() == null) { setUserDesc(vXUser); } String actualPassword = vXUser.getPassword(); VXPortalUser vXPortalUser = new VXPortalUser(); vXPortalUser.setLoginId(userName); vXPortalUser.setFirstName(vXUser.getFirstName()); if("null".equalsIgnoreCase(vXPortalUser.getFirstName())){ vXPortalUser.setFirstName(""); } vXPortalUser.setLastName(vXUser.getLastName()); if("null".equalsIgnoreCase(vXPortalUser.getLastName())){ vXPortalUser.setLastName(""); } vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); } else { vXPortalUser.setPublicScreenName(vXUser.getName()); } vXPortalUser.setPassword(actualPassword); vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); vXPortalUser = userMgr.createDefaultAccountUser(vXPortalUser); VXUser createdXUser = xUserService.createResource(vXUser); createdXUser.setPassword(actualPassword); List<XXTrxLog> trxLogList = xUserService.getTransactionLog( createdXUser, "create"); String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); createdXUser.setPassword(hiddenPassword); Collection<Long> groupIdList = vXUser.getGroupIdList(); List<VXGroupUser> vXGroupUsers = new ArrayList<VXGroupUser>(); if (groupIdList != null) { for (Long groupId : groupIdList) { VXGroupUser vXGroupUser = createXGroupUser( createdXUser.getId(), groupId); // trxLogList.addAll(xGroupUserService.getTransactionLog( // vXGroupUser, "create")); vXGroupUsers.add(vXGroupUser); } } for (VXGroupUser vXGroupUser : vXGroupUsers) { trxLogList.addAll(xGroupUserService.getTransactionLog(vXGroupUser, "create")); } // xaBizUtil.createTrxLog(trxLogList); if(vXPortalUser!=null){ assignPermissionToUser(vXPortalUser, true); } return createdXUser; } public void assignPermissionToUser(VXPortalUser vXPortalUser, boolean isCreate) { HashMap<String, Long> moduleNameId = getAllModuleNameAndIdMap(); if(moduleNameId!=null && vXPortalUser!=null){ if(CollectionUtils.isNotEmpty(vXPortalUser.getUserRoleList())){ for (String role : vXPortalUser.getUserRoleList()) { if (role.equals(RangerConstants.ROLE_USER)) { createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); } else if (role.equals(RangerConstants.ROLE_SYS_ADMIN)) { createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_AUDIT), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_USER_GROUPS), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_TAG_BASED_POLICIES), isCreate); } else if (role.equals(RangerConstants.ROLE_KEY_ADMIN)) { createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_KEY_MANAGER), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_REPORTS), isCreate); createOrUpdateUserPermisson(vXPortalUser, moduleNameId.get(RangerConstants.MODULE_RESOURCE_BASED_POLICIES), isCreate); } } } } } // Insert or Updating Mapping permissions depending upon roles public void createOrUpdateUserPermisson(VXPortalUser portalUser, Long moduleId, boolean isCreate) { VXUserPermission vXUserPermission; XXUserPermission xUserPermission = daoManager.getXXUserPermission().findByModuleIdAndPortalUserId(portalUser.getId(), moduleId); if (xUserPermission == null) { vXUserPermission = new VXUserPermission(); // When Creating XXUserPermission UI sends xUserId, to keep it consistent here xUserId should be used XXUser xUser = daoManager.getXXUser().findByPortalUserId(portalUser.getId()); if (xUser == null) { logger.warn("Could not found corresponding xUser for username: [" + portalUser.getLoginId() + "], So not assigning permission to this user"); return; } else { vXUserPermission.setUserId(xUser.getId()); } vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); vXUserPermission.setModuleId(moduleId); try { vXUserPermission = this.createXUserPermission(vXUserPermission); logger.info("Permission assigned to user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); } catch (Exception e) { logger.error("Error while assigning permission to user: [" + portalUser.getLoginId() + "] for module: [" + moduleId + "]", e); } } else if (isCreate) { vXUserPermission = xUserPermissionService.populateViewBean(xUserPermission); vXUserPermission.setIsAllowed(RangerCommonEnums.IS_ALLOWED); vXUserPermission = this.updateXUserPermission(vXUserPermission); logger.info("Permission Updated for user: [" + vXUserPermission.getUserName() + "] For Module: [" + vXUserPermission.getModuleName() + "]"); } } public HashMap<String, Long> getAllModuleNameAndIdMap() { List<XXModuleDef> xXModuleDefs = daoManager.getXXModuleDef().getAll(); if (!CollectionUtils.isEmpty(xXModuleDefs)) { HashMap<String, Long> moduleNameAndIdMap = new HashMap<String, Long>(); for (XXModuleDef xXModuleDef : xXModuleDefs) { moduleNameAndIdMap.put(xXModuleDef.getModule(), xXModuleDef.getId()); } return moduleNameAndIdMap; } return null; } private VXGroupUser createXGroupUser(Long userId, Long groupId) { VXGroupUser vXGroupUser = new VXGroupUser(); vXGroupUser.setParentGroupId(groupId); vXGroupUser.setUserId(userId); VXGroup vXGroup = xGroupService.readResource(groupId); vXGroupUser.setName(vXGroup.getName()); vXGroupUser = xGroupUserService.createResource(vXGroupUser); return vXGroupUser; } public VXUser updateXUser(VXUser vXUser) { if (vXUser == null || vXUser.getName() == null || "null".equalsIgnoreCase(vXUser.getName()) || vXUser.getName().trim().isEmpty()) { throw restErrorUtil.createRESTException("Please provide a valid " + "username.", MessageEnums.INVALID_INPUT_DATA); } checkAccess(vXUser.getName()); VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser .getName()); VXPortalUser vXPortalUser = new VXPortalUser(); if (oldUserProfile != null && oldUserProfile.getId() != null) { vXPortalUser.setId(oldUserProfile.getId()); } // TODO : There is a possibility that old user may not exist. vXPortalUser.setFirstName(vXUser.getFirstName()); if("null".equalsIgnoreCase(vXPortalUser.getFirstName())){ vXPortalUser.setFirstName(""); } vXPortalUser.setLastName(vXUser.getLastName()); if("null".equalsIgnoreCase(vXPortalUser.getLastName())){ vXPortalUser.setLastName(""); } vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); vXPortalUser.setLoginId(vXUser.getName()); vXPortalUser.setStatus(vXUser.getStatus()); vXPortalUser.setUserRoleList(vXUser.getUserRoleList()); if (vXPortalUser.getFirstName() != null && vXPortalUser.getLastName() != null && !vXPortalUser.getFirstName().trim().isEmpty() && !vXPortalUser.getLastName().trim().isEmpty()) { vXPortalUser.setPublicScreenName(vXPortalUser.getFirstName() + " " + vXPortalUser.getLastName()); } else { vXPortalUser.setPublicScreenName(vXUser.getName()); } vXPortalUser.setUserSource(vXUser.getUserSource()); String hiddenPasswordString = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); String password = vXUser.getPassword(); if (oldUserProfile != null && password != null && password.equals(hiddenPasswordString)) { vXPortalUser.setPassword(oldUserProfile.getPassword()); } else if(password != null){ validatePassword(vXUser); vXPortalUser.setPassword(password); } Collection<Long> groupIdList = vXUser.getGroupIdList(); XXPortalUser xXPortalUser = new XXPortalUser(); xXPortalUser = userMgr.updateUserWithPass(vXPortalUser); //update permissions start Collection<String> roleListUpdatedProfile =new ArrayList<String>(); if (oldUserProfile != null && oldUserProfile.getId() != null) { if(vXUser!=null && vXUser.getUserRoleList()!=null){ Collection<String> roleListOldProfile = oldUserProfile.getUserRoleList(); Collection<String> roleListNewProfile = vXUser.getUserRoleList(); if(roleListNewProfile!=null && roleListOldProfile!=null){ for (String role : roleListNewProfile) { if(role!=null && !roleListOldProfile.contains(role)){ roleListUpdatedProfile.add(role); } } } } } if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ vXPortalUser.setUserRoleList(roleListUpdatedProfile); List<XXUserPermission> xuserPermissionList = daoManager .getXXUserPermission() .findByUserPermissionId(vXPortalUser.getId()); if (xuserPermissionList!=null && xuserPermissionList.size()>0){ for (XXUserPermission xXUserPermission : xuserPermissionList) { if (xXUserPermission != null) { try { xUserPermissionService.deleteResource(xXUserPermission.getId()); } catch (Exception e) { logger.error(e.getMessage()); } } } } assignPermissionToUser(vXPortalUser,true); } //update permissions end Collection<String> roleList = new ArrayList<String>(); if (xXPortalUser != null) { roleList = userMgr.getRolesForUser(xXPortalUser); } if (roleList == null || roleList.size() == 0) { roleList = new ArrayList<String>(); roleList.add(RangerConstants.ROLE_USER); } // TODO I've to get the transaction log from here. // There is nothing to log anything in XXUser so far. vXUser = xUserService.updateResource(vXUser); vXUser.setUserRoleList(roleList); vXUser.setPassword(password); List<XXTrxLog> trxLogList = xUserService.getTransactionLog(vXUser, oldUserProfile, "update"); vXUser.setPassword(hiddenPasswordString); Long userId = vXUser.getId(); List<Long> groupUsersToRemove = new ArrayList<Long>(); if (groupIdList != null) { SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xUserId", userId); VXGroupUserList vXGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList(); if (vXGroupUsers != null) { // Create for (Long groupId : groupIdList) { boolean found = false; for (VXGroupUser vXGroupUser : vXGroupUsers) { if (groupId.equals(vXGroupUser.getParentGroupId())) { found = true; break; } } if (!found) { VXGroupUser vXGroupUser = createXGroupUser(userId, groupId); trxLogList.addAll(xGroupUserService.getTransactionLog( vXGroupUser, "create")); } } // Delete for (VXGroupUser vXGroupUser : vXGroupUsers) { boolean found = false; for (Long groupId : groupIdList) { if (groupId.equals(vXGroupUser.getParentGroupId())) { trxLogList.addAll(xGroupUserService .getTransactionLog(vXGroupUser, "update")); found = true; break; } } if (!found) { // TODO I've to get the transaction log from here. trxLogList.addAll(xGroupUserService.getTransactionLog( vXGroupUser, "delete")); groupUsersToRemove.add(vXGroupUser.getId()); // xGroupUserService.deleteResource(vXGroupUser.getId()); } } } else { for (Long groupId : groupIdList) { VXGroupUser vXGroupUser = createXGroupUser(userId, groupId); trxLogList.addAll(xGroupUserService.getTransactionLog( vXGroupUser, "create")); } } vXUser.setGroupIdList(groupIdList); } else { logger.debug("Group id list can't be null for user. Group user " + "mapping not updated for user : " + userId); } xaBizUtil.createTrxLog(trxLogList); for (Long groupUserId : groupUsersToRemove) { xGroupUserService.deleteResource(groupUserId); } return vXUser; } public VXUserGroupInfo createXUserGroupFromMap( VXUserGroupInfo vXUserGroupInfo) { checkAdminAccess(); if(vXUserGroupInfo.getXuserInfo() != null) { validatePassword(vXUserGroupInfo.getXuserInfo()); } VXUserGroupInfo vxUGInfo = new VXUserGroupInfo(); VXUser vXUser = vXUserGroupInfo.getXuserInfo(); vXUser = xUserService.createXUserWithOutLogin(vXUser); vxUGInfo.setXuserInfo(vXUser); List<VXGroup> vxg = new ArrayList<VXGroup>(); for (VXGroup vXGroup : vXUserGroupInfo.getXgroupInfo()) { VXGroup VvXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); vxg.add(VvXGroup); VXGroupUser vXGroupUser = new VXGroupUser(); vXGroupUser.setUserId(vXUser.getId()); vXGroupUser.setName(VvXGroup.getName()); vXGroupUser = xGroupUserService .createXGroupUserWithOutLogin(vXGroupUser); } VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(vXUser .getName()); if(vXPortalUser!=null){ assignPermissionToUser(vXPortalUser, true); } vxUGInfo.setXgroupInfo(vxg); return vxUGInfo; } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public VXGroupUserInfo createXGroupUserFromMap( VXGroupUserInfo vXGroupUserInfo) { checkAdminAccess(); VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); VXGroup vXGroup = vXGroupUserInfo.getXgroupInfo(); // Add the group user mappings for a given group to x_group_user table /*XXGroup xGroup = daoManager.getXXGroup().findByGroupName(vXGroup.getName()); if (xGroup == null) { return vxGUInfo; }*/ List<VXUser> vxu = new ArrayList<VXUser>(); for (VXUser vXUser : vXGroupUserInfo.getXuserInfo()) { XXUser xUser = daoManager.getXXUser().findByUserName(vXUser.getName()); if (xUser != null) { // Add or update group user mapping only if the user already exists in x_user table. vXGroup = xGroupService.createXGroupWithOutLogin(vXGroup); vxGUInfo.setXgroupInfo(vXGroup); vxu.add(vXUser); VXGroupUser vXGroupUser = new VXGroupUser(); vXGroupUser.setUserId(xUser.getId()); vXGroupUser.setName(vXGroup.getName()); vXGroupUser = xGroupUserService .createXGroupUserWithOutLogin(vXGroupUser); } } vxGUInfo.setXuserInfo(vxu); return vxGUInfo; } public VXGroupUserInfo getXGroupUserFromMap( String groupName) { checkAdminAccess(); VXGroupUserInfo vxGUInfo = new VXGroupUserInfo(); XXGroup xGroup = daoManager.getXXGroup().findByGroupName(groupName); if (xGroup == null) { return vxGUInfo; } VXGroup xgroupInfo = xGroupService.populateViewBean(xGroup); vxGUInfo.setXgroupInfo(xgroupInfo); SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", xGroup.getId()); VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); List<VXUser> vxu = new ArrayList<VXUser>(); logger.debug("removing all the group user mapping for : " + xGroup.getName()); for (VXGroupUser groupUser : vxGroupUserList.getList()) { XXUser xUser = daoManager.getXXUser().getById(groupUser.getUserId()); if (xUser != null) { VXUser vxUser = new VXUser(); vxUser.setName(xUser.getName()); vxu.add(vxUser); } } vxGUInfo.setXuserInfo(vxu); return vxGUInfo; } public VXUser createXUserWithOutLogin(VXUser vXUser) { checkAdminAccess(); validatePassword(vXUser); return xUserService.createXUserWithOutLogin(vXUser); } public VXGroup createXGroup(VXGroup vXGroup) { checkAdminAccess(); if (vXGroup.getDescription() == null) { vXGroup.setDescription(vXGroup.getName()); } vXGroup = xGroupService.createResource(vXGroup); List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup, "create"); xaBizUtil.createTrxLog(trxLogList); return vXGroup; } public VXGroup createXGroupWithoutLogin(VXGroup vXGroup) { checkAdminAccess(); return xGroupService.createXGroupWithOutLogin(vXGroup); } public VXGroupUser createXGroupUser(VXGroupUser vXGroupUser) { checkAdminAccess(); vXGroupUser = xGroupUserService .createXGroupUserWithOutLogin(vXGroupUser); return vXGroupUser; } public VXUser getXUser(Long id) { VXUser vXUser=null; vXUser=xUserService.readResourceWithOutLogin(id); if(vXUser!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ vXUser=getMaskedVXUser(vXUser); } return vXUser; } public VXGroupUser getXGroupUser(Long id) { return xGroupUserService.readResourceWithOutLogin(id); } public VXGroup getXGroup(Long id) { VXGroup vXGroup=null; vXGroup=xGroupService.readResourceWithOutLogin(id); if(vXGroup!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ vXGroup=getMaskedVXGroup(vXGroup); } return vXGroup; } /** * // public void createXGroupAndXUser(String groupName, String userName) { * * // Long groupId; // Long userId; // XXGroup xxGroup = // * appDaoManager.getXXGroup().findByGroupName(groupName); // VXGroup * vxGroup; // if (xxGroup == null) { // vxGroup = new VXGroup(); // * vxGroup.setName(groupName); // vxGroup.setDescription(groupName); // * vxGroup.setGroupType(AppConstants.XA_GROUP_USER); // * vxGroup.setPriAcctId(1l); // vxGroup.setPriGrpId(1l); // vxGroup = * xGroupService.createResource(vxGroup); // groupId = vxGroup.getId(); // } * else { // groupId = xxGroup.getId(); // } // XXUser xxUser = * appDaoManager.getXXUser().findByUserName(userName); // VXUser vxUser; // * if (xxUser == null) { // vxUser = new VXUser(); // * vxUser.setName(userName); // vxUser.setDescription(userName); // * vxUser.setPriGrpId(1l); // vxUser.setPriAcctId(1l); // vxUser = * xUserService.createResource(vxUser); // userId = vxUser.getId(); // } * else { // userId = xxUser.getId(); // } // VXGroupUser vxGroupUser = new * VXGroupUser(); // vxGroupUser.setParentGroupId(groupId); // * vxGroupUser.setUserId(userId); // vxGroupUser.setName(groupName); // * vxGroupUser.setPriAcctId(1l); // vxGroupUser.setPriGrpId(1l); // * vxGroupUser = xGroupUserService.createResource(vxGroupUser); * * // } */ public void deleteXGroupAndXUser(String groupName, String userName) { checkAdminAccess(); VXGroup vxGroup = xGroupService.getGroupByGroupName(groupName); VXUser vxUser = xUserService.getXUserByUserName(userName); SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", vxGroup.getId()); searchCriteria.addParam("xUserId", vxUser.getId()); VXGroupUserList vxGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); for (VXGroupUser vxGroupUser : vxGroupUserList.getList()) { daoManager.getXXGroupUser().remove(vxGroupUser.getId()); } } public VXGroupList getXUserGroups(Long xUserId) { SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xUserId", xUserId); VXGroupUserList vXGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); VXGroupList vXGroupList = new VXGroupList(); List<VXGroup> vXGroups = new ArrayList<VXGroup>(); if (vXGroupUserList != null) { List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList(); Set<Long> groupIdList = new HashSet<Long>(); for (VXGroupUser vXGroupUser : vXGroupUsers) { groupIdList.add(vXGroupUser.getParentGroupId()); } for (Long groupId : groupIdList) { VXGroup vXGroup = xGroupService.readResource(groupId); vXGroups.add(vXGroup); } vXGroupList.setVXGroups(vXGroups); } else { logger.debug("No groups found for user id : " + xUserId); } return vXGroupList; } public Set<String> getGroupsForUser(String userName) { Set<String> ret = new HashSet<String>(); try { VXUser user = getXUserByUserName(userName); if (user != null) { VXGroupList groups = getXUserGroups(user.getId()); if (groups != null && !CollectionUtils.isEmpty(groups.getList())) { for (VXGroup group : groups.getList()) { ret.add(group.getName()); } } else { if (logger.isDebugEnabled()) { logger.debug("getGroupsForUser('" + userName + "'): no groups found for user"); } } } else { if (logger.isDebugEnabled()) { logger.debug("getGroupsForUser('" + userName + "'): user not found"); } } } catch (Exception excp) { logger.error("getGroupsForUser('" + userName + "') failed", excp); } return ret; } public VXUserList getXGroupUsers(Long xGroupId) { SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", xGroupId); VXGroupUserList vXGroupUserList = xGroupUserService .searchXGroupUsers(searchCriteria); VXUserList vXUserList = new VXUserList(); List<VXUser> vXUsers = new ArrayList<VXUser>(); if (vXGroupUserList != null) { List<VXGroupUser> vXGroupUsers = vXGroupUserList.getList(); Set<Long> userIdList = new HashSet<Long>(); for (VXGroupUser vXGroupUser : vXGroupUsers) { userIdList.add(vXGroupUser.getUserId()); } for (Long userId : userIdList) { VXUser vXUser = xUserService.readResource(userId); vXUsers.add(vXUser); } vXUserList.setVXUsers(vXUsers); } else { logger.debug("No users found for group id : " + xGroupId); } return vXUserList; } // FIXME Hack : Unnecessary, to be removed after discussion. private void setUserDesc(VXUser vXUser) { vXUser.setDescription(vXUser.getName()); } @Override public VXGroup updateXGroup(VXGroup vXGroup) { checkAdminAccess(); XXGroup xGroup = daoManager.getXXGroup().getById(vXGroup.getId()); List<XXTrxLog> trxLogList = xGroupService.getTransactionLog(vXGroup, xGroup, "update"); xaBizUtil.createTrxLog(trxLogList); vXGroup = (VXGroup) xGroupService.updateResource(vXGroup); return vXGroup; } public VXGroupUser updateXGroupUser(VXGroupUser vXGroupUser) { checkAdminAccess(); return super.updateXGroupUser(vXGroupUser); } public void deleteXGroupUser(Long id, boolean force) { checkAdminAccess(); super.deleteXGroupUser(id, force); } public VXGroupGroup createXGroupGroup(VXGroupGroup vXGroupGroup){ checkAdminAccess(); return super.createXGroupGroup(vXGroupGroup); } public VXGroupGroup updateXGroupGroup(VXGroupGroup vXGroupGroup) { checkAdminAccess(); return super.updateXGroupGroup(vXGroupGroup); } public void deleteXGroupGroup(Long id, boolean force) { checkAdminAccess(); super.deleteXGroupGroup(id, force); } public void deleteXPermMap(Long id, boolean force) { if (force) { XXPermMap xPermMap = daoManager.getXXPermMap().getById(id); if (xPermMap != null) { if (xResourceService.readResource(xPermMap.getResourceId()) == null) { throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xPermMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); } } xPermMapService.deleteResource(id); } else { throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } public VXLong getXPermMapSearchCount(SearchCriteria searchCriteria) { VXPermMapList permMapList = xPermMapService.searchXPermMaps(searchCriteria); VXLong vXLong = new VXLong(); vXLong.setValue(permMapList.getListSize()); return vXLong; } public void deleteXAuditMap(Long id, boolean force) { if (force) { XXAuditMap xAuditMap = daoManager.getXXAuditMap().getById(id); if (xAuditMap != null) { if (xResourceService.readResource(xAuditMap.getResourceId()) == null) { throw restErrorUtil.createRESTException("Invalid Input Data - No resource found with Id: " + xAuditMap.getResourceId(), MessageEnums.INVALID_INPUT_DATA); } } xAuditMapService.deleteResource(id); } else { throw restErrorUtil.createRESTException("serverMsg.modelMgrBaseDeleteModel", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY); } } public VXLong getXAuditMapSearchCount(SearchCriteria searchCriteria) { VXAuditMapList auditMapList = xAuditMapService.searchXAuditMaps(searchCriteria); VXLong vXLong = new VXLong(); vXLong.setValue(auditMapList.getListSize()); return vXLong; } public void modifyUserVisibility(HashMap<Long, Integer> visibilityMap) { checkAdminAccess(); Set<Map.Entry<Long, Integer>> entries = visibilityMap.entrySet(); for (Map.Entry<Long, Integer> entry : entries) { XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); VXUser vObj = xUserService.populateViewBean(xUser); vObj.setIsVisible(entry.getValue()); vObj = xUserService.updateResource(vObj); } } public void modifyGroupsVisibility(HashMap<Long, Integer> groupVisibilityMap) { checkAdminAccess(); Set<Map.Entry<Long, Integer>> entries = groupVisibilityMap.entrySet(); for (Map.Entry<Long, Integer> entry : entries) { XXGroup xGroup = daoManager.getXXGroup().getById(entry.getKey()); VXGroup vObj = xGroupService.populateViewBean(xGroup); vObj.setIsVisible(entry.getValue()); vObj = xGroupService.updateResource(vObj); } } // Module permissions public VXModuleDef createXModuleDefPermission(VXModuleDef vXModuleDef) { XXModuleDef xModDef = daoManager.getXXModuleDef().findByModuleName(vXModuleDef.getModule()); if (xModDef != null) { throw restErrorUtil.createRESTException("Module Def with same name already exists.", MessageEnums.ERROR_DUPLICATE_OBJECT); } return xModuleDefService.createResource(vXModuleDef); } public VXModuleDef getXModuleDefPermission(Long id) { return xModuleDefService.readResource(id); } public VXModuleDef updateXModuleDefPermission(VXModuleDef vXModuleDef) { List<VXGroupPermission> groupPermListNew = vXModuleDef.getGroupPermList(); List<VXUserPermission> userPermListNew = vXModuleDef.getUserPermList(); List<VXGroupPermission> groupPermListOld = new ArrayList<VXGroupPermission>(); List<VXUserPermission> userPermListOld = new ArrayList<VXUserPermission>(); XXModuleDef xModuleDef = daoManager.getXXModuleDef().getById(vXModuleDef.getId()); VXModuleDef vModuleDefPopulateOld = xModuleDefService.populateViewBean(xModuleDef); List<XXGroupPermission> xgroupPermissionList = daoManager.getXXGroupPermission().findByModuleId(vXModuleDef.getId(), true); Map<Long, XXGroup> xXGroupMap=xGroupService.getXXGroupIdXXGroupMap(); if(xXGroupMap==null || xXGroupMap.isEmpty()){ for (XXGroupPermission xGrpPerm : xgroupPermissionList) { VXGroupPermission vXGrpPerm = xGroupPermissionService.populateViewBean(xGrpPerm); groupPermListOld.add(vXGrpPerm); } }else{ groupPermListOld=xGroupPermissionService.getPopulatedVXGroupPermissionList(xgroupPermissionList,xXGroupMap,vModuleDefPopulateOld); } vModuleDefPopulateOld.setGroupPermList(groupPermListOld); List<XXUserPermission> xuserPermissionList = daoManager.getXXUserPermission().findByModuleId(vXModuleDef.getId(), true); Map<Long, XXUser> xXPortalUserIdXXUserMap=xUserService.getXXPortalUserIdXXUserMap(); if(xXPortalUserIdXXUserMap==null || xXPortalUserIdXXUserMap.isEmpty()){ for (XXUserPermission xUserPerm : xuserPermissionList) { VXUserPermission vUserPerm = xUserPermissionService.populateViewBean(xUserPerm); userPermListOld.add(vUserPerm); } }else{ userPermListOld=xUserPermissionService.getPopulatedVXUserPermissionList(xuserPermissionList,xXPortalUserIdXXUserMap,vModuleDefPopulateOld); } vModuleDefPopulateOld.setUserPermList(userPermListOld); if (groupPermListOld != null && groupPermListNew != null) { for (VXGroupPermission newVXGroupPerm : groupPermListNew) { boolean isExist = false; for (VXGroupPermission oldVXGroupPerm : groupPermListOld) { if (newVXGroupPerm.getModuleId().equals(oldVXGroupPerm.getModuleId()) && newVXGroupPerm.getGroupId().equals(oldVXGroupPerm.getGroupId())) { if (!newVXGroupPerm.getIsAllowed().equals(oldVXGroupPerm.getIsAllowed())) { oldVXGroupPerm.setIsAllowed(newVXGroupPerm.getIsAllowed()); oldVXGroupPerm = this.updateXGroupPermission(oldVXGroupPerm); } isExist = true; } } if (!isExist) { newVXGroupPerm = this.createXGroupPermission(newVXGroupPerm); } } } if (userPermListOld != null && userPermListNew != null) { for (VXUserPermission newVXUserPerm : userPermListNew) { boolean isExist = false; for (VXUserPermission oldVXUserPerm : userPermListOld) { if (newVXUserPerm.getModuleId().equals(oldVXUserPerm.getModuleId()) && newVXUserPerm.getUserId().equals(oldVXUserPerm.getUserId())) { if (!newVXUserPerm.getIsAllowed().equals(oldVXUserPerm.getIsAllowed())) { oldVXUserPerm.setIsAllowed(newVXUserPerm.getIsAllowed()); oldVXUserPerm = this.updateXUserPermission(oldVXUserPerm); } isExist = true; } } if (!isExist) { newVXUserPerm = this.createXUserPermission(newVXUserPerm); } } } vXModuleDef = xModuleDefService.updateResource(vXModuleDef); return vXModuleDef; } public void deleteXModuleDefPermission(Long id, boolean force) { daoManager.getXXUserPermission().deleteByModuleId(id); daoManager.getXXGroupPermission().deleteByModuleId(id); xModuleDefService.deleteResource(id); } // User permission public VXUserPermission createXUserPermission(VXUserPermission vXUserPermission) { vXUserPermission = xUserPermissionService.createResource(vXUserPermission); Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Assigning permission to user who's found logged in into system, so updating permission in session of that user: [" + vXUserPermission.getUserName() + "]"); sessionMgr.resetUserModulePermission(userSession); } } return vXUserPermission; } public VXUserPermission getXUserPermission(Long id) { return xUserPermissionService.readResource(id); } public VXUserPermission updateXUserPermission(VXUserPermission vXUserPermission) { vXUserPermission = xUserPermissionService.updateResource(vXUserPermission); Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(vXUserPermission.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Updating permission of user who's found logged in into system, so updating permission in session of user: [" + vXUserPermission.getUserName() + "]"); sessionMgr.resetUserModulePermission(userSession); } } return vXUserPermission; } public void deleteXUserPermission(Long id, boolean force) { XXUserPermission xUserPermission = daoManager.getXXUserPermission().getById(id); if (xUserPermission == null) { throw restErrorUtil.createRESTException("No UserPermission found to delete, ID: " + id, MessageEnums.DATA_NOT_FOUND); } xUserPermissionService.deleteResource(id); Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForPortalUserId(xUserPermission.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("deleting permission of user who's found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } // Group permission public VXGroupPermission createXGroupPermission(VXGroupPermission vXGroupPermission) { vXGroupPermission = xGroupPermissionService.createResource(vXGroupPermission); List<XXGroupUser> grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); for (XXGroupUser xGrpUser : grpUsers) { Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Assigning permission to group, one of the user belongs to that group found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } return vXGroupPermission; } public VXGroupPermission getXGroupPermission(Long id) { return xGroupPermissionService.readResource(id); } public VXGroupPermission updateXGroupPermission(VXGroupPermission vXGroupPermission) { vXGroupPermission = xGroupPermissionService.updateResource(vXGroupPermission); List<XXGroupUser> grpUsers = daoManager.getXXGroupUser().findByGroupId(vXGroupPermission.getGroupId()); for (XXGroupUser xGrpUser : grpUsers) { Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("Assigning permission to group whose one of the user found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } return vXGroupPermission; } public void deleteXGroupPermission(Long id, boolean force) { XXGroupPermission xGrpPerm = daoManager.getXXGroupPermission().getById(id); if (xGrpPerm == null) { throw restErrorUtil.createRESTException("No GroupPermission object with ID: [" + id + "found.", MessageEnums.DATA_NOT_FOUND); } xGroupPermissionService.deleteResource(id); List<XXGroupUser> grpUsers = daoManager.getXXGroupUser().findByGroupId(xGrpPerm.getGroupId()); for (XXGroupUser xGrpUser : grpUsers) { Set<UserSessionBase> userSessions = sessionMgr.getActiveUserSessionsForXUserId(xGrpUser.getUserId()); if (!CollectionUtils.isEmpty(userSessions)) { for (UserSessionBase userSession : userSessions) { logger.info("deleting permission of the group whose one of the user found logged in into system, so updating permission in session of that user"); sessionMgr.resetUserModulePermission(userSession); } } } } public void modifyUserActiveStatus(HashMap<Long, Integer> statusMap) { checkAdminAccess(); UserSessionBase session = ContextUtil.getCurrentUserSession(); String currentUser=null; if(session!=null){ currentUser=session.getLoginId(); if(currentUser==null || currentUser.trim().isEmpty()){ currentUser=null; } } if(currentUser==null){ return; } Set<Map.Entry<Long, Integer>> entries = statusMap.entrySet(); for (Map.Entry<Long, Integer> entry : entries) { if(entry!=null && entry.getKey()!=null && entry.getValue()!=null){ XXUser xUser = daoManager.getXXUser().getById(entry.getKey()); if(xUser!=null){ VXPortalUser vXPortalUser = userMgr.getUserProfileByLoginId(xUser.getName()); if(vXPortalUser!=null){ if(vXPortalUser.getLoginId()!=null && !vXPortalUser.getLoginId().equalsIgnoreCase(currentUser)){ vXPortalUser.setStatus(entry.getValue()); userMgr.updateUser(vXPortalUser); } } } } } } public void checkAdminAccess() { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if (!session.isUserAdmin()) { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); throw restErrorUtil.generateRESTException(vXResponse); } } else { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } public void checkAccess(String loginID) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if (!session.isUserAdmin() && !session.isKeyAdmin() && !session.getLoginId().equalsIgnoreCase(loginID)) { throw restErrorUtil.create403RESTException("Operation" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); } } else { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } public VXPermMapList searchXPermMaps(SearchCriteria searchCriteria) { VXPermMapList returnList; UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); // If user is system admin if (currentUserSession != null && currentUserSession.isUserAdmin()) { returnList = super.searchXPermMaps(searchCriteria); } else { returnList = new VXPermMapList(); int startIndex = searchCriteria.getStartIndex(); int pageSize = searchCriteria.getMaxRows(); searchCriteria.setStartIndex(0); searchCriteria.setMaxRows(Integer.MAX_VALUE); List<VXPermMap> resultList = xPermMapService.searchXPermMaps(searchCriteria).getVXPermMaps(); List<VXPermMap> adminPermResourceList = new ArrayList<VXPermMap>(); for (VXPermMap xXPermMap : resultList) { XXResource xRes = daoManager.getXXResource().getById(xXPermMap.getResourceId()); VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN); if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { adminPermResourceList.add(xXPermMap); } } if (adminPermResourceList.size() > 0) { populatePageList(adminPermResourceList, startIndex, pageSize, returnList); } } return returnList; } private void populatePageList(List<VXPermMap> permMapList, int startIndex, int pageSize, VXPermMapList vxPermMapList) { List<VXPermMap> onePageList = new ArrayList<VXPermMap>(); for (int i = startIndex; i < pageSize + startIndex && i < permMapList.size(); i++) { VXPermMap vXPermMap = permMapList.get(i); onePageList.add(vXPermMap); } vxPermMapList.setVXPermMaps(onePageList); vxPermMapList.setStartIndex(startIndex); vxPermMapList.setPageSize(pageSize); vxPermMapList.setResultSize(onePageList.size()); vxPermMapList.setTotalCount(permMapList.size()); } public VXAuditMapList searchXAuditMaps(SearchCriteria searchCriteria) { VXAuditMapList returnList; UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession(); // If user is system admin if (currentUserSession != null && currentUserSession.isUserAdmin()) { returnList = super.searchXAuditMaps(searchCriteria); } else { returnList = new VXAuditMapList(); int startIndex = searchCriteria.getStartIndex(); int pageSize = searchCriteria.getMaxRows(); searchCriteria.setStartIndex(0); searchCriteria.setMaxRows(Integer.MAX_VALUE); List<VXAuditMap> resultList = xAuditMapService.searchXAuditMaps(searchCriteria).getVXAuditMaps(); List<VXAuditMap> adminAuditResourceList = new ArrayList<VXAuditMap>(); for (VXAuditMap xXAuditMap : resultList) { XXResource xRes = daoManager.getXXResource().getById(xXAuditMap.getResourceId()); VXResponse vXResponse = msBizUtil.hasPermission(xResourceService.populateViewBean(xRes), AppConstants.XA_PERM_TYPE_ADMIN); if (vXResponse.getStatusCode() == VXResponse.STATUS_SUCCESS) { adminAuditResourceList.add(xXAuditMap); } } if (adminAuditResourceList.size() > 0) { populatePageList(adminAuditResourceList, startIndex, pageSize, returnList); } } return returnList; } private void populatePageList(List<VXAuditMap> auditMapList, int startIndex, int pageSize, VXAuditMapList vxAuditMapList) { List<VXAuditMap> onePageList = new ArrayList<VXAuditMap>(); for (int i = startIndex; i < pageSize + startIndex && i < auditMapList.size(); i++) { VXAuditMap vXAuditMap = auditMapList.get(i); onePageList.add(vXAuditMap); } vxAuditMapList.setVXAuditMaps(onePageList); vxAuditMapList.setStartIndex(startIndex); vxAuditMapList.setPageSize(pageSize); vxAuditMapList.setResultSize(onePageList.size()); vxAuditMapList.setTotalCount(auditMapList.size()); } public void checkAccessRoles(List<String> stringRolesList) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null && stringRolesList!=null) { if (!session.isUserAdmin() && !session.isKeyAdmin()) { throw restErrorUtil.create403RESTException("Permission" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "Not Logged In") + " ,isn't permitted to perform the action."); }else{ if (session.isUserAdmin() && stringRolesList.contains(RangerConstants.ROLE_KEY_ADMIN)) { throw restErrorUtil.create403RESTException("Permission" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "") + " isn't permitted to perform the action."); } if (session.isKeyAdmin() && stringRolesList.contains(RangerConstants.ROLE_SYS_ADMIN)) { throw restErrorUtil.create403RESTException("Permission" + " denied. LoggedInUser=" + (session != null ? session.getXXPortalUser().getId() : "") + " isn't permitted to perform the action."); } } }else{ VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } public VXStringList setUserRolesByExternalID(Long userId, List<VXString> vStringRolesList) { List<String> roleListNewProfile = new ArrayList<String>(); if(vStringRolesList!=null){ for (VXString vXString : vStringRolesList) { roleListNewProfile.add(vXString.getValue()); } } checkAccessRoles(roleListNewProfile); VXUser vXUser=getXUser(userId); List<XXPortalUserRole> portalUserRoleList =null; if(vXUser!=null && roleListNewProfile.size()>0){ VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); if(oldUserProfile!=null){ updateUserRolesPermissions(oldUserProfile,roleListNewProfile); portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } }else{ throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } } public VXStringList setUserRolesByName(String userName, List<VXString> vStringRolesList) { List<String> roleListNewProfile = new ArrayList<String>(); if(vStringRolesList!=null){ for (VXString vXString : vStringRolesList) { roleListNewProfile.add(vXString.getValue()); } } checkAccessRoles(roleListNewProfile); if(userName!=null && roleListNewProfile.size()>0){ VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(userName); if(oldUserProfile!=null){ updateUserRolesPermissions(oldUserProfile,roleListNewProfile); List<XXPortalUserRole> portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } }else{ throw restErrorUtil.createRESTException("Login ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } } public VXStringList getUserRolesByExternalID(Long userId) { VXUser vXUser=getXUser(userId); if(vXUser==null){ throw restErrorUtil.createRESTException("Please provide a valid ID", MessageEnums.INVALID_INPUT_DATA); } checkAccess(vXUser.getName()); List<XXPortalUserRole> portalUserRoleList =null; VXPortalUser oldUserProfile = userMgr.getUserProfileByLoginId(vXUser.getName()); if(oldUserProfile!=null){ portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(oldUserProfile.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("User ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } } public VXStringList getUserRolesByName(String userName) { VXPortalUser vXPortalUser=null; if(userName!=null && !userName.trim().isEmpty()){ checkAccess(userName); vXPortalUser = userMgr.getUserProfileByLoginId(userName); if(vXPortalUser!=null && vXPortalUser.getUserRoleList()!=null){ List<XXPortalUserRole> portalUserRoleList = daoManager.getXXPortalUserRole().findByUserId(vXPortalUser.getId()); return getStringListFromUserRoleList(portalUserRoleList); }else{ throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); } }else{ throw restErrorUtil.createRESTException("Please provide a valid userName", MessageEnums.INVALID_INPUT_DATA); } } public void updateUserRolesPermissions(VXPortalUser oldUserProfile,List<String> roleListNewProfile){ //update permissions start Collection<String> roleListUpdatedProfile =new ArrayList<String>(); if (oldUserProfile != null && oldUserProfile.getId() != null) { Collection<String> roleListOldProfile = oldUserProfile.getUserRoleList(); if(roleListNewProfile!=null && roleListOldProfile!=null){ for (String role : roleListNewProfile) { if(role!=null && !roleListOldProfile.contains(role)){ roleListUpdatedProfile.add(role); } } } } if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ oldUserProfile.setUserRoleList(roleListUpdatedProfile); List<XXUserPermission> xuserPermissionList = daoManager .getXXUserPermission() .findByUserPermissionId(oldUserProfile.getId()); if (xuserPermissionList!=null && xuserPermissionList.size()>0){ for (XXUserPermission xXUserPermission : xuserPermissionList) { if (xXUserPermission != null) { xUserPermissionService.deleteResource(xXUserPermission.getId()); } } } assignPermissionToUser(oldUserProfile,true); if(roleListUpdatedProfile!=null && roleListUpdatedProfile.size()>0){ userMgr.updateRoles(oldUserProfile.getId(), oldUserProfile.getUserRoleList()); } } //update permissions end } public VXStringList getStringListFromUserRoleList( List<XXPortalUserRole> listXXPortalUserRole) { if(listXXPortalUserRole==null){ return null; } List<VXString> xStrList = new ArrayList<VXString>(); VXString vXStr=null; for (XXPortalUserRole userRole : listXXPortalUserRole) { if(userRole!=null){ vXStr = new VXString(); vXStr.setValue(userRole.getUserRole()); xStrList.add(vXStr); } } VXStringList vXStringList = new VXStringList(xStrList); return vXStringList; } public boolean hasAccess(String loginID) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if(session.isUserAdmin() || session.getLoginId().equalsIgnoreCase(loginID)){ return true; } } return false; } public VXUser getMaskedVXUser(VXUser vXUser) { if(vXUser!=null){ if(vXUser.getGroupIdList()!=null && vXUser.getGroupIdList().size()>0){ vXUser.setGroupIdList(new ArrayList<Long>()); } if(vXUser.getGroupNameList()!=null && vXUser.getGroupNameList().size()>0){ vXUser.setGroupNameList(getMaskedCollection(vXUser.getGroupNameList())); } if(vXUser.getUserRoleList()!=null && vXUser.getUserRoleList().size()>0){ vXUser.setUserRoleList(getMaskedCollection(vXUser.getUserRoleList())); } vXUser.setUpdatedBy(AppConstants.Masked_String); } return vXUser; } public VXGroup getMaskedVXGroup(VXGroup vXGroup) { if(vXGroup!=null){ vXGroup.setUpdatedBy(AppConstants.Masked_String); } return vXGroup; } @Override public VXUserList searchXUsers(SearchCriteria searchCriteria) { VXUserList vXUserList = new VXUserList(); VXUser vXUserExactMatch = null; try{ VXUserList vXUserListSort = new VXUserList(); if(searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null){ searchCriteria.setSortBy("name"); vXUserListSort = xUserService.searchXUsers(searchCriteria); vXUserExactMatch = getXUserByUserName((String)searchCriteria.getParamList().get("name")); } int vXUserExactMatchwithSearchCriteria = 0; if(vXUserExactMatch != null){ vXUserListSort = xUserService.searchXUsers(searchCriteria); HashMap<String, Object> searchCriteriaParamList = searchCriteria.getParamList(); vXUserExactMatchwithSearchCriteria = 1; for(Map.Entry<String, Object> entry:searchCriteriaParamList.entrySet()){ String caseKey=entry.getKey(); switch (caseKey.toLowerCase()) { case "isvisible": Integer isVisible = vXUserExactMatch.getIsVisible(); if(isVisible != null && !isVisible.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "status": Integer status = vXUserExactMatch.getStatus(); if(status != null && !status.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "usersource": Integer userSource = vXUserExactMatch.getUserSource(); if(userSource != null && !userSource.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "emailaddress": String email = vXUserExactMatch.getEmailAddress(); if(email != null && !email.equals(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "userrole": if(vXUserExactMatch.getUserRoleList() != null && !vXUserExactMatch.getUserRoleList().contains(entry.getValue())){ vXUserExactMatchwithSearchCriteria = -1; } break; case "userrolelist": @SuppressWarnings("unchecked") Collection<String> userrolelist = (Collection<String>) entry.getValue(); if(!CollectionUtils.isEmpty(userrolelist)){ for(String role:userrolelist){ if(vXUserExactMatch.getUserRoleList() != null && vXUserExactMatch.getUserRoleList().contains(role)){ vXUserExactMatchwithSearchCriteria = 1; break; } else{ vXUserExactMatchwithSearchCriteria = -1; } } } break; default: logger.warn("XUserMgr.searchXUsers: unexpected searchCriteriaParam:" + caseKey); break; } if(vXUserExactMatchwithSearchCriteria == -1){ break; } } } if(vXUserExactMatchwithSearchCriteria == 1){ VXGroupList groups = getXUserGroups(vXUserExactMatch.getId()); if(groups.getListSize() > 0){ Collection<String> groupNameList = new ArrayList<String>(); Collection<Long> groupIdList = new ArrayList<Long>(); for(VXGroup group:groups.getList()){ groupIdList.add(group.getId()); groupNameList.add(group.getName()); } vXUserExactMatch.setGroupIdList(groupIdList); vXUserExactMatch.setGroupNameList(groupNameList); } List<VXUser> vXUsers = new ArrayList<VXUser>(); if(searchCriteria.getStartIndex() == 0){ vXUsers.add(0,vXUserExactMatch); } for(VXUser vxUser:vXUserListSort.getVXUsers()){ if(vXUserExactMatch.getId()!=null && vxUser!=null){ if(!vXUserExactMatch.getId().equals(vxUser.getId())){ vXUsers.add(vxUser); } } } vXUserList.setVXUsers(vXUsers); vXUserList.setStartIndex(searchCriteria.getStartIndex()); vXUserList.setResultSize(vXUserList.getVXUsers().size()); vXUserList.setTotalCount(vXUserListSort.getTotalCount()); vXUserList.setPageSize(searchCriteria.getMaxRows()); vXUserList.setSortBy(searchCriteria.getSortBy()); vXUserList.setSortType(searchCriteria.getSortType()); } } catch (Exception e){ logger.error("Error getting the exact match of user =>"+e); } if(vXUserList.getVXUsers().isEmpty()) { searchCriteria.setSortBy("id"); vXUserList = xUserService.searchXUsers(searchCriteria); } if(vXUserList!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ List<VXUser> vXUsers = new ArrayList<VXUser>(); if(vXUserList!=null && vXUserList.getListSize()>0){ for(VXUser vXUser:vXUserList.getList()){ vXUser=getMaskedVXUser(vXUser); vXUsers.add(vXUser); } vXUserList.setVXUsers(vXUsers); } } return vXUserList; } @Override public VXGroupList searchXGroups(SearchCriteria searchCriteria) { VXGroupList vXGroupList= new VXGroupList(); VXGroup vXGroupExactMatch = null; try{ VXGroupList vXGroupListSort= new VXGroupList(); if(searchCriteria.getParamList() != null && searchCriteria.getParamList().get("name") != null){ searchCriteria.setSortBy("name"); vXGroupListSort = xGroupService.searchXGroups(searchCriteria); vXGroupExactMatch = getGroupByGroupName((String)searchCriteria.getParamList().get("name")); } int vXGroupExactMatchwithSearchCriteria = 0; if(vXGroupExactMatch != null){ HashMap<String, Object> searchCriteriaParamList = searchCriteria.getParamList(); vXGroupExactMatchwithSearchCriteria = 1; for (Map.Entry<String, Object> entry: searchCriteriaParamList.entrySet()){ String caseKey=entry.getKey(); switch (caseKey.toLowerCase()) { case "isvisible": Integer isVisible = vXGroupExactMatch.getIsVisible(); if(isVisible != null && !isVisible.equals(entry.getValue())){ vXGroupExactMatchwithSearchCriteria = -1; } break; case "groupsource": Integer groupsource = vXGroupExactMatch.getGroupSource(); if(groupsource != null && !groupsource.equals(entry.getValue())){ vXGroupExactMatchwithSearchCriteria = -1; } break; default: logger.warn("XUserMgr.searchXGroups: unexpected searchCriteriaParam:" + caseKey); break; } if(vXGroupExactMatchwithSearchCriteria == -1){ break; } } } if(vXGroupExactMatchwithSearchCriteria == 1){ List<VXGroup> vXGroups = new ArrayList<VXGroup>(); if(searchCriteria.getStartIndex() == 0){ vXGroups.add(0,vXGroupExactMatch); } for(VXGroup vXGroup:vXGroupListSort.getList()){ if(vXGroupExactMatch.getId() != null && vXGroup != null){ if(!vXGroupExactMatch.getId().equals(vXGroup.getId())){ vXGroups.add(vXGroup); } } } vXGroupList.setVXGroups(vXGroups); vXGroupList.setStartIndex(searchCriteria.getStartIndex()); vXGroupList.setResultSize(vXGroupList.getList().size()); vXGroupList.setTotalCount(vXGroupListSort.getTotalCount()); vXGroupList.setPageSize(searchCriteria.getMaxRows()); vXGroupList.setSortBy(searchCriteria.getSortBy()); vXGroupList.setSortType(searchCriteria.getSortType()); } } catch (Exception e){ logger.error("Error getting the exact match of group =>"+e); } if(vXGroupList.getList().isEmpty()) { searchCriteria.setSortBy("id"); vXGroupList=xGroupService.searchXGroups(searchCriteria); } if(vXGroupList!=null && !hasAccessToModule(RangerConstants.MODULE_USER_GROUPS)){ if(vXGroupList!=null && vXGroupList.getListSize()>0){ List<VXGroup> listMasked=new ArrayList<VXGroup>(); for(VXGroup vXGroup:vXGroupList.getList()){ vXGroup=getMaskedVXGroup(vXGroup); listMasked.add(vXGroup); } vXGroupList.setVXGroups(listMasked); } } return vXGroupList; } public Collection<String> getMaskedCollection(Collection<String> listunMasked){ List<String> listMasked=new ArrayList<String>(); if(listunMasked!=null) { for(int i = 0; i < listunMasked.size(); i++) { listMasked.add(AppConstants.Masked_String); } } return listMasked; } public boolean hasAccessToModule(String moduleName){ UserSessionBase userSession = ContextUtil.getCurrentUserSession(); if (userSession != null && userSession.getLoginId()!=null){ VXUser vxUser = xUserService.getXUserByUserName(userSession.getLoginId()); if(vxUser!=null){ List<String> permissionList = daoManager.getXXModuleDef().findAccessibleModulesByUserId(userSession.getUserId(), vxUser.getId()); if(permissionList!=null && permissionList.contains(moduleName)){ return true; } } } return false; } public void deleteXGroup(Long id, boolean force) { checkAdminAccess(); XXGroupDao xXGroupDao = daoManager.getXXGroup(); XXGroup xXGroup = xXGroupDao.getById(id); VXGroup vXGroup = xGroupService.populateViewBean(xXGroup); if (vXGroup == null || StringUtil.isEmpty(vXGroup.getName())) { throw restErrorUtil.createRESTException("Group ID doesn't exist.", MessageEnums.INVALID_INPUT_DATA); } if(logger.isDebugEnabled()){ logger.info("Force delete status="+force+" for group="+vXGroup.getName()); } SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xGroupId", id); VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("groupId", id); VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("groupId", id); VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); XXGroupPermissionDao xXGroupPermissionDao=daoManager.getXXGroupPermission(); List<XXGroupPermission> xXGroupPermissions=xXGroupPermissionDao.findByGroupId(id); XXGroupGroupDao xXGroupGroupDao = daoManager.getXXGroupGroup(); List<XXGroupGroup> xXGroupGroups = xXGroupGroupDao.findByGroupId(id); XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); List<XXPolicy> xXPolicyList = xXPolicyDao.findByGroupId(id); logger.warn("Deleting GROUP : "+vXGroup.getName()); if (force) { //delete XXGroupUser records of matching group XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); XXUserDao xXUserDao = daoManager.getXXUser(); XXUser xXUser =null; for (VXGroupUser groupUser : vxGroupUserList.getList()) { if(groupUser!=null){ xXUser=xXUserDao.getById(groupUser.getUserId()); if(xXUser!=null){ logger.warn("Removing user '" + xXUser.getName() + "' from group '" + groupUser.getName() + "'"); } xGroupUserDao.remove(groupUser.getId()); } } //delete XXPermMap records of matching group XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); XXResourceDao xXResourceDao = daoManager.getXXResource(); XXResource xXResource =null; for (VXPermMap vXPermMap : vXPermMapList.getList()) { if(vXPermMap!=null){ xXResource=xXResourceDao.getById(vXPermMap.getResourceId()); if(xXResource!=null){ logger.warn("Deleting '" + AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()) + "' permission from policy ID='" + vXPermMap.getResourceId() + "' for group '" + vXPermMap.getGroupName() + "'"); } xXPermMapDao.remove(vXPermMap.getId()); } } //delete XXAuditMap records of matching group XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { if(vXAuditMap!=null){ xXResource=xXResourceDao.getById(vXAuditMap.getResourceId()); xXAuditMapDao.remove(vXAuditMap.getId()); } } //delete XXGroupGroupDao records of group-group mapping for (XXGroupGroup xXGroupGroup : xXGroupGroups) { if(xXGroupGroup!=null){ XXGroup xXGroupParent=xXGroupDao.getById(xXGroupGroup.getParentGroupId()); XXGroup xXGroupChild=xXGroupDao.getById(xXGroupGroup.getGroupId()); if(xXGroupParent!=null && xXGroupChild!=null){ logger.warn("Removing group '" + xXGroupChild.getName() + "' from group '" + xXGroupParent.getName() + "'"); } xXGroupGroupDao.remove(xXGroupGroup.getId()); } } //delete XXPolicyItemGroupPerm records of group for (XXPolicy xXPolicy : xXPolicyList) { RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); List<RangerPolicyItem> policyItems = rangerPolicy.getPolicyItems(); removeUserGroupReferences(policyItems,null,vXGroup.getName()); rangerPolicy.setPolicyItems(policyItems); List<RangerPolicyItem> denyPolicyItems = rangerPolicy.getDenyPolicyItems(); removeUserGroupReferences(denyPolicyItems,null,vXGroup.getName()); rangerPolicy.setDenyPolicyItems(denyPolicyItems); List<RangerPolicyItem> allowExceptions = rangerPolicy.getAllowExceptions(); removeUserGroupReferences(allowExceptions,null,vXGroup.getName()); rangerPolicy.setAllowExceptions(allowExceptions); List<RangerPolicyItem> denyExceptions = rangerPolicy.getDenyExceptions(); removeUserGroupReferences(denyExceptions,null,vXGroup.getName()); rangerPolicy.setDenyExceptions(denyExceptions); List<RangerDataMaskPolicyItem> dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); removeUserGroupReferences(dataMaskItems,null,vXGroup.getName()); rangerPolicy.setDataMaskPolicyItems(dataMaskItems); List<RangerRowFilterPolicyItem> rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); removeUserGroupReferences(rowFilterItems,null,vXGroup.getName()); rangerPolicy.setRowFilterPolicyItems(rowFilterItems); try { svcStore.updatePolicy(rangerPolicy); } catch (Throwable excp) { logger.error("updatePolicy(" + rangerPolicy + ") failed", excp); restErrorUtil.createRESTException(excp.getMessage()); } } if(CollectionUtils.isNotEmpty(xXGroupPermissions)){ for (XXGroupPermission xXGroupPermission : xXGroupPermissions) { if(xXGroupPermission!=null){ XXModuleDef xXModuleDef=daoManager.getXXModuleDef().findByModuleId(xXGroupPermission.getModuleId()); if(xXModuleDef!=null){ logger.warn("Deleting '" + xXModuleDef.getModule() + "' module permission for group '" + xXGroup.getName() + "'"); } xXGroupPermissionDao.remove(xXGroupPermission.getId()); } } } //delete XXGroup xXGroupDao.remove(id); //Create XXTrxLog List<XXTrxLog> xXTrxLogsXXGroup = xGroupService.getTransactionLog(xGroupService.populateViewBean(xXGroup), "delete"); xaBizUtil.createTrxLog(xXTrxLogsXXGroup); } else { boolean hasReferences=false; if(vxGroupUserList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && CollectionUtils.isNotEmpty(xXPolicyList)){ hasReferences=true; } if(hasReferences==false && vXPermMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && vXAuditMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && CollectionUtils.isNotEmpty(xXGroupGroups)){ hasReferences=true; } if(hasReferences==false && CollectionUtils.isNotEmpty(xXGroupPermissions)){ hasReferences=true; } if(hasReferences){ //change visibility to Hidden if(vXGroup.getIsVisible()==RangerCommonEnums.IS_VISIBLE){ vXGroup.setIsVisible(RangerCommonEnums.IS_HIDDEN); xGroupService.updateResource(vXGroup); } }else{ //delete XXGroup xXGroupDao.remove(id); //Create XXTrxLog List<XXTrxLog> xXTrxLogsXXGroup = xGroupService.getTransactionLog(xGroupService.populateViewBean(xXGroup), "delete"); xaBizUtil.createTrxLog(xXTrxLogsXXGroup); } } } public void deleteXUser(Long id, boolean force) { checkAdminAccess(); XXUserDao xXUserDao = daoManager.getXXUser(); XXUser xXUser = xXUserDao.getById(id); VXUser vXUser = xUserService.populateViewBean(xXUser); if(vXUser==null ||StringUtil.isEmpty(vXUser.getName())){ throw restErrorUtil.createRESTException("No user found with id=" + id); } XXPortalUserDao xXPortalUserDao=daoManager.getXXPortalUser(); XXPortalUser xXPortalUser=xXPortalUserDao.findByLoginId(vXUser.getName().trim()); VXPortalUser vXPortalUser=null; if(xXPortalUser!=null){ vXPortalUser=xPortalUserService.populateViewBean(xXPortalUser); } if(vXPortalUser==null ||StringUtil.isEmpty(vXPortalUser.getLoginId())){ throw restErrorUtil.createRESTException("No user found with id=" + id); } if (logger.isDebugEnabled()) { logger.debug("Force delete status="+force+" for user="+vXUser.getName()); } restrictSelfAccountDeletion(vXUser.getName().trim()); SearchCriteria searchCriteria = new SearchCriteria(); searchCriteria.addParam("xUserId", id); VXGroupUserList vxGroupUserList = searchXGroupUsers(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("userId", id); VXPermMapList vXPermMapList = searchXPermMaps(searchCriteria); searchCriteria = new SearchCriteria(); searchCriteria.addParam("userId", id); VXAuditMapList vXAuditMapList = searchXAuditMaps(searchCriteria); long xXPortalUserId=0; xXPortalUserId=vXPortalUser.getId(); XXAuthSessionDao xXAuthSessionDao=daoManager.getXXAuthSession(); XXUserPermissionDao xXUserPermissionDao=daoManager.getXXUserPermission(); XXPortalUserRoleDao xXPortalUserRoleDao=daoManager.getXXPortalUserRole(); List<XXAuthSession> xXAuthSessions=xXAuthSessionDao.getAuthSessionByUserId(xXPortalUserId); List<XXUserPermission> xXUserPermissions=xXUserPermissionDao.findByUserPermissionId(xXPortalUserId); List<XXPortalUserRole> xXPortalUserRoles=xXPortalUserRoleDao.findByUserId(xXPortalUserId); XXPolicyDao xXPolicyDao = daoManager.getXXPolicy(); List<XXPolicy> xXPolicyList=xXPolicyDao.findByUserId(id); logger.warn("Deleting User : "+vXUser.getName()); if (force) { //delete XXGroupUser mapping XXGroupUserDao xGroupUserDao = daoManager.getXXGroupUser(); for (VXGroupUser groupUser : vxGroupUserList.getList()) { if(groupUser!=null){ logger.warn("Removing user '" + vXUser.getName() + "' from group '" + groupUser.getName() + "'"); xGroupUserDao.remove(groupUser.getId()); } } //delete XXPermMap records of user XXPermMapDao xXPermMapDao = daoManager.getXXPermMap(); for (VXPermMap vXPermMap : vXPermMapList.getList()) { if(vXPermMap!=null){ logger.warn("Deleting '" + AppConstants.getLabelFor_XAPermType(vXPermMap.getPermType()) + "' permission from policy ID='" + vXPermMap.getResourceId() + "' for user '" + vXPermMap.getUserName() + "'"); xXPermMapDao.remove(vXPermMap.getId()); } } //delete XXAuditMap records of user XXAuditMapDao xXAuditMapDao = daoManager.getXXAuditMap(); for (VXAuditMap vXAuditMap : vXAuditMapList.getList()) { if(vXAuditMap!=null){ xXAuditMapDao.remove(vXAuditMap.getId()); } } //delete XXPortalUser references if(vXPortalUser!=null){ xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); if(xXAuthSessions!=null && xXAuthSessions.size()>0){ logger.warn("Deleting " + xXAuthSessions.size() + " login session records for user '" + vXPortalUser.getLoginId() + "'"); } for (XXAuthSession xXAuthSession : xXAuthSessions) { xXAuthSessionDao.remove(xXAuthSession.getId()); } for (XXUserPermission xXUserPermission : xXUserPermissions) { if(xXUserPermission!=null){ XXModuleDef xXModuleDef=daoManager.getXXModuleDef().findByModuleId(xXUserPermission.getModuleId()); if(xXModuleDef!=null){ logger.warn("Deleting '" + xXModuleDef.getModule() + "' module permission for user '" + vXPortalUser.getLoginId() + "'"); } xXUserPermissionDao.remove(xXUserPermission.getId()); } } for (XXPortalUserRole xXPortalUserRole : xXPortalUserRoles) { if(xXPortalUserRole!=null){ logger.warn("Deleting '" + xXPortalUserRole.getUserRole() + "' role for user '" + vXPortalUser.getLoginId() + "'"); xXPortalUserRoleDao.remove(xXPortalUserRole.getId()); } } } //delete XXPolicyItemUserPerm records of user for(XXPolicy xXPolicy:xXPolicyList){ RangerPolicy rangerPolicy = policyService.getPopulatedViewObject(xXPolicy); List<RangerPolicyItem> policyItems = rangerPolicy.getPolicyItems(); removeUserGroupReferences(policyItems,vXUser.getName(),null); rangerPolicy.setPolicyItems(policyItems); List<RangerPolicyItem> denyPolicyItems = rangerPolicy.getDenyPolicyItems(); removeUserGroupReferences(denyPolicyItems,vXUser.getName(),null); rangerPolicy.setDenyPolicyItems(denyPolicyItems); List<RangerPolicyItem> allowExceptions = rangerPolicy.getAllowExceptions(); removeUserGroupReferences(allowExceptions,vXUser.getName(),null); rangerPolicy.setAllowExceptions(allowExceptions); List<RangerPolicyItem> denyExceptions = rangerPolicy.getDenyExceptions(); removeUserGroupReferences(denyExceptions,vXUser.getName(),null); rangerPolicy.setDenyExceptions(denyExceptions); List<RangerDataMaskPolicyItem> dataMaskItems = rangerPolicy.getDataMaskPolicyItems(); removeUserGroupReferences(dataMaskItems,vXUser.getName(),null); rangerPolicy.setDataMaskPolicyItems(dataMaskItems); List<RangerRowFilterPolicyItem> rowFilterItems = rangerPolicy.getRowFilterPolicyItems(); removeUserGroupReferences(rowFilterItems,vXUser.getName(),null); rangerPolicy.setRowFilterPolicyItems(rowFilterItems); try{ svcStore.updatePolicy(rangerPolicy); }catch(Throwable excp) { logger.error("updatePolicy(" + rangerPolicy + ") failed", excp); throw restErrorUtil.createRESTException(excp.getMessage()); } } //delete XXUser entry of user xXUserDao.remove(id); //delete XXPortal entry of user logger.warn("Deleting Portal User : "+vXPortalUser.getLoginId()); xXPortalUserDao.remove(xXPortalUserId); List<XXTrxLog> trxLogList =xUserService.getTransactionLog(xUserService.populateViewBean(xXUser), "delete"); xaBizUtil.createTrxLog(trxLogList); if (xXPortalUser != null) { trxLogList=xPortalUserService .getTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), "delete"); xaBizUtil.createTrxLog(trxLogList); } } else { boolean hasReferences=false; if(vxGroupUserList!=null && vxGroupUserList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && xXPolicyList!=null && xXPolicyList.size()>0){ hasReferences=true; } if(hasReferences==false && vXPermMapList!=null && vXPermMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && vXAuditMapList!=null && vXAuditMapList.getListSize()>0){ hasReferences=true; } if(hasReferences==false && xXAuthSessions!=null && xXAuthSessions.size()>0){ hasReferences=true; } if(hasReferences==false && xXUserPermissions!=null && xXUserPermissions.size()>0){ hasReferences=true; } if(hasReferences==false && xXPortalUserRoles!=null && xXPortalUserRoles.size()>0){ hasReferences=true; } if(hasReferences){ if(vXUser.getIsVisible()!=RangerCommonEnums.IS_HIDDEN){ logger.info("Updating visibility of user '"+vXUser.getName()+"' to Hidden!"); vXUser.setIsVisible(RangerCommonEnums.IS_HIDDEN); xUserService.updateResource(vXUser); } }else{ xPortalUserService.updateXXPortalUserReferences(xXPortalUserId); //delete XXUser entry of user xXUserDao.remove(id); //delete XXPortal entry of user logger.warn("Deleting Portal User : "+vXPortalUser.getLoginId()); xXPortalUserDao.remove(xXPortalUserId); List<XXTrxLog> trxLogList =xUserService.getTransactionLog(xUserService.populateViewBean(xXUser), "delete"); xaBizUtil.createTrxLog(trxLogList); trxLogList=xPortalUserService.getTransactionLog(xPortalUserService.populateViewBean(xXPortalUser), "delete"); xaBizUtil.createTrxLog(trxLogList); } } } private <T extends RangerPolicyItem> void removeUserGroupReferences(List<T> policyItems, String user, String group) { List<T> itemsToRemove = null; for(T policyItem : policyItems) { if(!StringUtil.isEmpty(user)) { policyItem.getUsers().remove(user); } if(!StringUtil.isEmpty(group)) { policyItem.getGroups().remove(group); } if(policyItem.getUsers().isEmpty() && policyItem.getGroups().isEmpty()) { if(itemsToRemove == null) { itemsToRemove = new ArrayList<T>(); } itemsToRemove.add(policyItem); } } if(CollectionUtils.isNotEmpty(itemsToRemove)) { policyItems.removeAll(itemsToRemove); } } public void restrictSelfAccountDeletion(String loginID) { UserSessionBase session = ContextUtil.getCurrentUserSession(); if (session != null) { if (!session.isUserAdmin()) { throw restErrorUtil.create403RESTException("Operation denied. LoggedInUser= "+session.getXXPortalUser().getLoginId() + " isn't permitted to perform the action."); }else{ if(!StringUtil.isEmpty(loginID) && loginID.equals(session.getLoginId())){ throw restErrorUtil.create403RESTException("Operation denied. LoggedInUser= "+session.getXXPortalUser().getLoginId() + " isn't permitted to delete his own profile."); } } } else { VXResponse vXResponse = new VXResponse(); vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); vXResponse.setMsgDesc("Bad Credentials"); throw restErrorUtil.generateRESTException(vXResponse); } } @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public VXUser createServiceConfigUser(String userName){ if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) { logger.error("User Name: "+userName); throw restErrorUtil.createRESTException("Please provide a valid username.",MessageEnums.INVALID_INPUT_DATA); } VXUser vXUser = null; VXPortalUser vXPortalUser=null; XXUser xxUser = daoManager.getXXUser().findByUserName(userName); XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName); String actualPassword = ""; if(xxUser!=null){ vXUser = xUserService.populateViewBean(xxUser); return vXUser; } if(xxUser==null){ vXUser=new VXUser(); vXUser.setName(userName); vXUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); vXUser.setDescription(vXUser.getName()); actualPassword = vXUser.getPassword(); } if(xXPortalUser==null){ vXPortalUser=new VXPortalUser(); vXPortalUser.setLoginId(userName); vXPortalUser.setEmailAddress(vXUser.getEmailAddress()); vXPortalUser.setFirstName(vXUser.getFirstName()); vXPortalUser.setLastName(vXUser.getLastName()); vXPortalUser.setPassword(vXUser.getPassword()); vXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL); ArrayList<String> roleList = new ArrayList<String>(); roleList.add(RangerConstants.ROLE_USER); vXPortalUser.setUserRoleList(roleList); xXPortalUser = userMgr.mapVXPortalUserToXXPortalUser(vXPortalUser); xXPortalUser=userMgr.createUser(xXPortalUser, RangerCommonEnums.STATUS_ENABLED, roleList); } VXUser createdXUser=null; if(xxUser==null && vXUser!=null){ try{ createdXUser = xUserService.createResource(vXUser); }catch(Exception ex){ logger.error("Error creating user: "+createdXUser.getName(),ex); } } if(createdXUser!=null){ try{ logger.info("User created: "+createdXUser.getName()); createdXUser.setPassword(actualPassword); List<XXTrxLog> trxLogList = xUserService.getTransactionLog(createdXUser, "create"); String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****"); createdXUser.setPassword(hiddenPassword); xaBizUtil.createTrxLog(trxLogList); if(xXPortalUser!=null){ vXPortalUser=userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser); assignPermissionToUser(vXPortalUser, true); } }catch(Exception ex){ logger.error("Error while assigning permissions to user: "+createdXUser.getName(),ex); } }else{ xxUser = daoManager.getXXUser().findByUserName(userName); if(xxUser!=null){ createdXUser = xUserService.populateViewBean(xxUser); } } return createdXUser; } private void validatePassword(VXUser vXUser) { if (vXUser.getPassword() != null && !vXUser.getPassword().isEmpty()) { boolean checkPassword = false; String pattern = "(?=.*[0-9])(?=.*[a-zA-Z]).{8,}"; checkPassword = vXUser.getPassword().trim().matches(pattern); if (!checkPassword) { logger.warn("validatePassword(). Password should be minimum 8 characters with min one alphabet and one numeric."); throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password should be minimum 8 characters with min one alphabet and one numeric", null); } } else { logger.warn("validatePassword(). Password cannot be blank/null."); throw restErrorUtil.createRESTException("serverMsg.xuserMgrValidatePassword", MessageEnums.INVALID_PASSWORD, null, "Password cannot be blank/null", null); } } }
RANGER-1638 : Improve the password validation from Ranger API
security-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java
RANGER-1638 : Improve the password validation from Ranger API
<ide><path>ecurity-admin/src/main/java/org/apache/ranger/biz/XUserMgr.java <ide> public VXUserGroupInfo createXUserGroupFromMap( <ide> VXUserGroupInfo vXUserGroupInfo) { <ide> checkAdminAccess(); <del> if(vXUserGroupInfo.getXuserInfo() != null) { <del> validatePassword(vXUserGroupInfo.getXuserInfo()); <del> } <ide> VXUserGroupInfo vxUGInfo = new VXUserGroupInfo(); <ide> <ide> VXUser vXUser = vXUserGroupInfo.getXuserInfo();
Java
apache-2.0
40e245f1852788ddea557b9e0e92d0bf0708fecb
0
rsahlin/graphics-engine,rsahlin/graphics-engine
package com.graphicsengine.scene; import com.nucleus.common.Key; /** * The different type of nodes that are defined and handled by the Graphics Engine * * @author Richard Sahlin * */ public enum GraphicsEngineNodeType implements Key { playfieldNode(), spriteMeshNode(), sharedMeshNode(), quadNode(), /** * UI base node */ element(); @Override public String getKey() { return name(); } }
src/main/java/com/graphicsengine/scene/GraphicsEngineNodeType.java
package com.graphicsengine.scene; import com.nucleus.common.Key; /** * The different type of nodes that are defined and handled by the Graphics Engine * * @author Richard Sahlin * */ public enum GraphicsEngineNodeType implements Key { playfieldNode(), spriteMeshNode(), sharedMeshNode(), quadNode(); @Override public String getKey() { return name(); } }
Add ui Element
src/main/java/com/graphicsengine/scene/GraphicsEngineNodeType.java
Add ui Element
<ide><path>rc/main/java/com/graphicsengine/scene/GraphicsEngineNodeType.java <ide> playfieldNode(), <ide> spriteMeshNode(), <ide> sharedMeshNode(), <del> quadNode(); <add> quadNode(), <add> /** <add> * UI base node <add> */ <add> element(); <ide> <ide> @Override <ide> public String getKey() {
Java
apache-2.0
error: pathspec 'server/src/test/java/org/uiautomation/ios/e2e/uicatalogapp/UIAKeyboardTests.java' did not match any file(s) known to git
b631658553f711f71605cf1ffee4e50eda5bd4cf
1
ios-driver/ios-driver,masbog/ios-driver,ios-driver/ios-driver,seem-sky/ios-driver,shutkou/ios-driver,crashlytics/ios-driver,masbog/ios-driver,darraghgrace/ios-driver,crashlytics/ios-driver,seem-sky/ios-driver,ios-driver/ios-driver,azaytsev/ios-driver,azaytsev/ios-driver,darraghgrace/ios-driver,shutkou/ios-driver,seem-sky/ios-driver,shutkou/ios-driver,azaytsev/ios-driver,darraghgrace/ios-driver,crashlytics/ios-driver,ios-driver/ios-driver,masbog/ios-driver,adataylor/ios-driver,adataylor/ios-driver,adataylor/ios-driver,crashlytics/ios-driver,crashlytics/ios-driver,azaytsev/ios-driver,darraghgrace/ios-driver,adataylor/ios-driver,masbog/ios-driver,shutkou/ios-driver,azaytsev/ios-driver,shutkou/ios-driver,seem-sky/ios-driver,ios-driver/ios-driver,darraghgrace/ios-driver,shutkou/ios-driver,masbog/ios-driver,adataylor/ios-driver
package org.uiautomation.ios.e2e.uicatalogapp; import org.testng.Assert; import org.testng.annotations.Test; import org.uiautomation.ios.UIAModels.UIAElement; import org.uiautomation.ios.UIAModels.UIAElementArray; import org.uiautomation.ios.UIAModels.UIAKey; import org.uiautomation.ios.UIAModels.UIAKeyboard; import org.uiautomation.ios.UIAModels.UIATableCell; import org.uiautomation.ios.UIAModels.UIATextField; import org.uiautomation.ios.UIAModels.predicate.AndCriteria; import org.uiautomation.ios.UIAModels.predicate.Criteria; import org.uiautomation.ios.UIAModels.predicate.NameCriteria; import org.uiautomation.ios.UIAModels.predicate.TypeCriteria; import org.uiautomation.ios.client.uiamodels.impl.RemoteUIAApplication; import org.uiautomation.ios.client.uiamodels.impl.RemoteUIADriver; import org.uiautomation.ios.client.uiamodels.impl.RemoteUIATarget; import org.uiautomation.ios.client.uiamodels.impl.RemoteUIAWindow; import org.uiautomation.ios.exceptions.NoSuchElementException; public class UIAKeyboardTests extends UICatalogTestsBase { @Test(expectedExceptions = NoSuchElementException.class) public void throwsIfKeyboardNotPresent() { RemoteUIADriver driver = null; try { driver = getDriver(); RemoteUIATarget target = driver.getLocalTarget(); RemoteUIAApplication app = target.getFrontMostApp(); app.getKeyboard(); } finally { if (driver != null) { driver.quit(); } } } private UIATextField getTextField(RemoteUIAWindow win) { String name = "TextFields, Uses of UITextField"; Criteria c1 = new TypeCriteria(UIATableCell.class); Criteria c2 = new NameCriteria(name); Criteria c = new AndCriteria(c1, c2); UIAElement element = win.findElement(c); element.tap(); Criteria fieldC = new AndCriteria(new TypeCriteria(UIATextField.class), new NameCriteria("Normal")); UIATextField textfield = (UIATextField) win.findElement(fieldC); return textfield; } @Test public void canFindKeyboard() { RemoteUIADriver driver = null; try { driver = getDriver(); RemoteUIATarget target = driver.getLocalTarget(); RemoteUIAApplication app = target.getFrontMostApp(); RemoteUIAWindow win = app.getMainWindow(); UIATextField textfield = getTextField(win); textfield.tap(); UIAKeyboard keyboard = app.getKeyboard(); UIAElementArray<UIAKey> keys = app.getKeyboard().getKeys(); Assert.assertEquals(keys.size(), 28); // GB, should be a qwerty Assert.assertEquals(keys.get(0).getName(), "Q"); } finally { if (driver != null) { driver.quit(); } } } }
server/src/test/java/org/uiautomation/ios/e2e/uicatalogapp/UIAKeyboardTests.java
adding some tests for keyboard
server/src/test/java/org/uiautomation/ios/e2e/uicatalogapp/UIAKeyboardTests.java
adding some tests for keyboard
<ide><path>erver/src/test/java/org/uiautomation/ios/e2e/uicatalogapp/UIAKeyboardTests.java <add>package org.uiautomation.ios.e2e.uicatalogapp; <add> <add>import org.testng.Assert; <add>import org.testng.annotations.Test; <add>import org.uiautomation.ios.UIAModels.UIAElement; <add>import org.uiautomation.ios.UIAModels.UIAElementArray; <add>import org.uiautomation.ios.UIAModels.UIAKey; <add>import org.uiautomation.ios.UIAModels.UIAKeyboard; <add>import org.uiautomation.ios.UIAModels.UIATableCell; <add>import org.uiautomation.ios.UIAModels.UIATextField; <add>import org.uiautomation.ios.UIAModels.predicate.AndCriteria; <add>import org.uiautomation.ios.UIAModels.predicate.Criteria; <add>import org.uiautomation.ios.UIAModels.predicate.NameCriteria; <add>import org.uiautomation.ios.UIAModels.predicate.TypeCriteria; <add>import org.uiautomation.ios.client.uiamodels.impl.RemoteUIAApplication; <add>import org.uiautomation.ios.client.uiamodels.impl.RemoteUIADriver; <add>import org.uiautomation.ios.client.uiamodels.impl.RemoteUIATarget; <add>import org.uiautomation.ios.client.uiamodels.impl.RemoteUIAWindow; <add>import org.uiautomation.ios.exceptions.NoSuchElementException; <add> <add>public class UIAKeyboardTests extends UICatalogTestsBase { <add> <add> @Test(expectedExceptions = NoSuchElementException.class) <add> public void throwsIfKeyboardNotPresent() { <add> RemoteUIADriver driver = null; <add> try { <add> driver = getDriver(); <add> RemoteUIATarget target = driver.getLocalTarget(); <add> RemoteUIAApplication app = target.getFrontMostApp(); <add> app.getKeyboard(); <add> <add> } finally { <add> if (driver != null) { <add> driver.quit(); <add> } <add> } <add> } <add> <add> private UIATextField getTextField(RemoteUIAWindow win) { <add> String name = "TextFields, Uses of UITextField"; <add> Criteria c1 = new TypeCriteria(UIATableCell.class); <add> Criteria c2 = new NameCriteria(name); <add> Criteria c = new AndCriteria(c1, c2); <add> UIAElement element = win.findElement(c); <add> element.tap(); <add> Criteria fieldC = new AndCriteria(new TypeCriteria(UIATextField.class), <add> new NameCriteria("Normal")); <add> UIATextField textfield = (UIATextField) win.findElement(fieldC); <add> return textfield; <add> } <add> <add> @Test <add> public void canFindKeyboard() { <add> RemoteUIADriver driver = null; <add> try { <add> <add> driver = getDriver(); <add> RemoteUIATarget target = driver.getLocalTarget(); <add> RemoteUIAApplication app = target.getFrontMostApp(); <add> RemoteUIAWindow win = app.getMainWindow(); <add> <add> UIATextField textfield = getTextField(win); <add> textfield.tap(); <add> <add> UIAKeyboard keyboard = app.getKeyboard(); <add> <add> UIAElementArray<UIAKey> keys = app.getKeyboard().getKeys(); <add> Assert.assertEquals(keys.size(), 28); <add> // GB, should be a qwerty <add> Assert.assertEquals(keys.get(0).getName(), "Q"); <add> <add> } finally { <add> if (driver != null) { <add> driver.quit(); <add> } <add> } <add> } <add> <add>}
JavaScript
mit
8d0e2b8f0beae66719cedef0a1283354f0fca4fb
0
tommy-carlier/etc.tcx.be,tommy-carlier/etc.tcx.be
(function(){ function toYMD(y,m,d) { return y*10000 + m*100 + d; } function div(a,b) { return a/b>>0; } var doc = document, today = new Date(), year = today.getFullYear(), todayYMD = toYMD(year,today.getMonth()+1,today.getDate()), monthNames = ['','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'], shortMonthNames = ['','jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'], shortDayNames = ['zo','ma','di','wo','do','vr','za'], monthDays = [0,31,28,31,30,31,30,31,31,30,31,30,31], monthDaysLeap = [0,31,29,31,30,31,30,31,31,30,31,30,31], cssDayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; function firstWeekDay(y) { var py = y-1; return (1 + 5*(py%4) + 4*(py%100) + 6*(py%400)) % 7; } function firstWeekNum(wday) { return wday >= 1 && wday <= 4 ? 1 : 53; } function isLeapYear(y) { return (y%4 === 0 && y%100 !== 0) || y%400 === 0; } function daysInMonth(m,leap) { return (leap?monthDaysLeap:monthDays)[m]; } function easterYMD(y) { var c = div(y,100), a = (19*(y%19) + c - div(c,4) - div((c - div((c+8),25)+1),3)+15)%30, b = (32 + 2*(c%4 + div(y%100,4)) - a - y%4) % 7, md = a + b - 7*div((y%19 + 11*a + 22*b),451) + 114; return toYMD(y,div(md,31),md%31+1); } function addCls(e,cls) { e.classList.add(cls); } function appendTxt(p,txt) { p.appendChild(doc.createTextNode(txt)); } function append(p,tag,cls,txt) { var e = doc.createElement(tag); if(cls.length) addCls(e, cls); if(txt.length) appendTxt(e, txt); return p.appendChild(e); } function appendBtn(p,cls,txt,action) { append(p, 'button', cls, txt).setAttribute('data-action', action); } function appendYear(p,y,days) { var e = append(p, 'div', 'Year', y + ' '); append(e, 'span', 'DayCount', days + ' dagen'); } function appendMonth(p,m,days) { var e = append(p, 'div', 'Month', monthNames[m] + ' '); append(e, 'span', 'DayCount', days + ' dagen'); } function appendWeek(p,wnum) { append(p, 'div', 'Week', 'Week ' + wnum); } function appendEvent(p,txt) { var es = p.getElementsByClassName('DayEvents'), e = es.length ? es[0] : append(p, 'ul', 'DayEvents', ''); append(e, 'li', '', txt); } function appendDay(p,y,m,mday,wday,elems) { var ymd = toYMD(y,m,mday), e = append(p, 'div', 'Day', ''); e.setAttribute('data-ymd', ymd); addCls(e, cssDayNames[wday]); if(ymd == todayYMD) addCls(e, 'Today'); append(e, 'span', 'WeekDay', shortDayNames[wday]); appendTxt(e, ' '); append(e, 'span', 'MonthDay', mday.toString()); appendTxt(e, ' '); append(e, 'span', 'DayMonth', shortMonthNames[m]); elems[ymd] = e; if(wday === 4 && mday === 13) appendEvent(e, 'Vrijdag de dertiende'); return e; } function disable(e){ addCls(e, 'Disabled'); } function render(view) { var nodes = view.childNodes; for(var i = 0, n = nodes.length; i < n; i++) { view.removeChild(view.firstChild); } var f = doc.createDocumentFragment(), month = 1, mday = 1, ymd = toYMD(year,month,mday), wday = firstWeekDay(year), wnum = firstWeekNum(wday), isLeap = isLeapYear(year), mdays = daysInMonth(month, isLeap), dayElems = { }; appendYear(f, year, isLeap ? 366 : 365); if(year > 1900) { appendBtn(f, 'NavToPrevYear', 'ga naar ' + (year-1), 'navToPrevYear'); } if(wday != 1) { appendWeek(f, wnum); for(var i = 1, n = wday > 1 ? wday : 7; i < n; i++) { disable(appendDay(f, year-1, 12, 32-n+i, i, dayElems)); } appendMonth(f, 1, 31); } else { appendMonth(f, 1, 31); appendWeek(f, wnum); } while(true) { appendDay(f, year, month, mday, wday, dayElems); if(mday < mdays) { mday += 1; } else { mday = 1; month += 1; if(month < 13) { mdays = daysInMonth(month, isLeap); appendMonth(f, month, mdays); } else { break; } } wday = (wday+1)%7; if(wday == 1) { wnum = (wnum%53)+1; if(wnum == 53 && mday >= 29) { wnum = 1; } appendWeek(f, wnum); } } if(wday > 0) { for(var i = wday; i < 7; i++) { disable(appendDay(f, year+1, 1, i-wday+1, (i+1)%7, dayElems)); } } appendEvent(dayElems[toYMD(year,1,1)], 'Nieuwjaar'); appendEvent(dayElems[toYMD(year,1,6)], 'Driekoningen'); appendEvent(dayElems[toYMD(year,2,14)], 'Valentijnsdag'); appendEvent(dayElems[toYMD(year,5,1)], 'Dag van de Arbeid'); appendEvent(dayElems[toYMD(year,7,11)], 'Feestdag van de Vlaamse Gemeenschap'); appendEvent(dayElems[toYMD(year,7,21)], 'Nationale feestdag'); appendEvent(dayElems[toYMD(year,8,15)], 'O.L.V. Hemelvaart'); appendEvent(dayElems[toYMD(year,9,27)], 'Dag van de Franse Gemeenschap'); appendEvent(dayElems[toYMD(year,10,31)], 'Halloween'); appendEvent(dayElems[toYMD(year,11,1)], 'Allerheiligen'); appendEvent(dayElems[toYMD(year,11,2)], 'Allerzielen'); appendEvent(dayElems[toYMD(year,11,11)], 'Wapenstilstand'); appendEvent(dayElems[toYMD(year,11,11)], 'Sint-Maarten'); appendEvent(dayElems[toYMD(year,11,15)], 'Koningsdag'); appendEvent(dayElems[toYMD(year,11,15)], 'Dag van de Duitstalige Gemeenschap'); appendEvent(dayElems[toYMD(year,12,6)], 'Sinterklaas'); appendEvent(dayElems[toYMD(year,12,25)], 'Kerstmis'); appendEvent(dayElems[toYMD(year,12,31)], 'Oudejaarsavond'); appendEvent(dayElems[toYMD(year,3,1)], 'Begin van de meteorologische lente'); appendEvent(dayElems[toYMD(year,6,1)], 'Begin van de meteorologische zomer'); appendEvent(dayElems[toYMD(year,9,1)], 'Begin van de meteorologische herfst'); appendEvent(dayElems[toYMD(year,12,1)], 'Begin van de meteorologische winter'); appendEvent(dayElems[easterYMD(year)], 'Pasen'); if(year < 9999) { appendBtn(f, 'NavToNextYear', 'ga naar ' + (year+1), 'navToNextYear'); } view.appendChild(f); } function scrollToToday() { var es = doc.getElementsByClassName('Today'); if(es.length) { var e = es[0]; e.scrollIntoView(); scrollBy(0, -e.scrollHeight * 5); } } function init(view) { view.addEventListener('click', function(e) { switch(e.target.getAttribute('data-action')) { case 'navToPrevYear': year -= 1; render(view); scrollTo(0, doc.body.scrollHeight); break; case 'navToNextYear': year += 1; render(view); scrollTo(0,0); break; } }); render(view); setTimeout(scrollToToday,10); } init(doc.getElementById('yearView')); }())
kalender/kalender.js
(function(){ var doc = document, today = new Date(), year = today.getFullYear(), todayYMD = year*10000 + (today.getMonth()+1)*100 + today.getDate(), monthNames = ['','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'], shortMonthNames = ['','jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'], shortDayNames = ['zo','ma','di','wo','do','vr','za'], monthDays = [0,31,28,31,30,31,30,31,31,30,31,30,31], monthDaysLeap = [0,31,29,31,30,31,30,31,31,30,31,30,31], cssDayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']; function firstWeekDay(y) { var py = y-1; return (1 + 5*(py%4) + 4*(py%100) + 6*(py%400)) % 7; } function firstWeekNum(wday) { return wday >= 1 && wday <= 4 ? 1 : 53; } function isLeapYear(y) { return (y%4 === 0 && y%100 !== 0) || y%400 === 0; } function daysInMonth(m,leap) { return (leap?monthDaysLeap:monthDays)[m]; } function div(a,b) { return a/b>>0; } function easterYMD(y) { var c = div(y,100), a = (19*(y%19) + c - div(c,4) - div((c - div((c+8),25)+1),3)+15)%30, b = (32 + 2*(c%4 + div(y%100,4)) - a - y%4) % 7, md = a + b - 7*div((y%19 + 11*a + 22*b),451) + 114; return y*10000 + div(md,31)*100 + md%31+1; } function addCls(e,cls) { e.classList.add(cls); } function appendTxt(p,txt) { p.appendChild(doc.createTextNode(txt)); } function append(p,tag,cls,txt) { var e = doc.createElement(tag); if(cls.length) addCls(e, cls); if(txt.length) appendTxt(e, txt); return p.appendChild(e); } function appendBtn(p,cls,txt,action) { append(p, 'button', cls, txt).setAttribute('data-action', action); } function appendYear(p,y,days) { var e = append(p, 'div', 'Year', y + ' '); append(e, 'span', 'DayCount', days + ' dagen'); } function appendMonth(p,m,days) { var e = append(p, 'div', 'Month', monthNames[m] + ' '); append(e, 'span', 'DayCount', days + ' dagen'); } function appendWeek(p,wnum) { append(p, 'div', 'Week', 'Week ' + wnum); } function appendEvent(p,txt) { var es = p.getElementsByClassName('DayEvents'), e = es.length ? es[0] : append(p, 'ul', 'DayEvents', ''); append(e, 'li', '', txt); } function appendDay(p,y,m,mday,wday,elems) { var ymd = y*10000 + m*100 + mday, e = append(p, 'div', 'Day', ''); e.setAttribute('data-ymd', ymd); addCls(e, cssDayNames[wday]); if(ymd == todayYMD) addCls(e, 'Today'); append(e, 'span', 'WeekDay', shortDayNames[wday]); appendTxt(e, ' '); append(e, 'span', 'MonthDay', mday.toString()); appendTxt(e, ' '); append(e, 'span', 'DayMonth', shortMonthNames[m]); elems[ymd] = e; if(wday === 4 && mday === 13) appendEvent(e, 'Vrijdag de dertiende'); return e; } function disable(e){ addCls(e, 'Disabled'); } function render(view) { var nodes = view.childNodes; for(var i = 0, n = nodes.length; i < n; i++) { view.removeChild(view.firstChild); } var f = doc.createDocumentFragment(), month = 1, mday = 1, ymd = year*10000 + month*100 + mday, wday = firstWeekDay(year), wnum = firstWeekNum(wday), isLeap = isLeapYear(year), mdays = daysInMonth(month, isLeap), dayElems = { }; appendYear(f, year, isLeap ? 366 : 365); if(year > 1900) { appendBtn(f, 'NavToPrevYear', 'ga naar ' + (year-1), 'navToPrevYear'); } if(wday != 1) { appendWeek(f, wnum); for(var i = 1, n = wday > 1 ? wday : 7; i < n; i++) { disable(appendDay(f, year-1, 12, 32-n+i, i, dayElems)); } appendMonth(f, 1, 31); } else { appendMonth(f, 1, 31); appendWeek(f, wnum); } while(true) { appendDay(f, year, month, mday, wday, dayElems); if(mday < mdays) { mday += 1; } else { mday = 1; month += 1; if(month < 13) { mdays = daysInMonth(month, isLeap); appendMonth(f, month, mdays); } else { break; } } wday = (wday+1)%7; if(wday == 1) { wnum = (wnum%53)+1; if(wnum == 53 && mday >= 29) { wnum = 1; } appendWeek(f, wnum); } } if(wday > 0) { for(var i = wday; i < 7; i++) { disable(appendDay(f, year+1, 1, i-wday+1, (i+1)%7, dayElems)); } } appendEvent(dayElems[year*10000+ 101], 'Nieuwjaar'); appendEvent(dayElems[year*10000+ 106], 'Driekoningen'); appendEvent(dayElems[year*10000+ 214], 'Valentijnsdag'); appendEvent(dayElems[year*10000+ 501], 'Dag van de Arbeid'); appendEvent(dayElems[year*10000+ 711], 'Feestdag van de Vlaamse Gemeenschap'); appendEvent(dayElems[year*10000+ 721], 'Nationale feestdag'); appendEvent(dayElems[year*10000+ 815], 'O.L.V. Hemelvaart'); appendEvent(dayElems[year*10000+ 927], 'Dag van de Franse Gemeenschap'); appendEvent(dayElems[year*10000+1031], 'Halloween'); appendEvent(dayElems[year*10000+1101], 'Allerheiligen'); appendEvent(dayElems[year*10000+1102], 'Allerzielen'); appendEvent(dayElems[year*10000+1111], 'Wapenstilstand'); appendEvent(dayElems[year*10000+1111], 'Sint-Maarten'); appendEvent(dayElems[year*10000+1115], 'Koningsdag'); appendEvent(dayElems[year*10000+1115], 'Dag van de Duitstalige Gemeenschap'); appendEvent(dayElems[year*10000+1206], 'Sinterklaas'); appendEvent(dayElems[year*10000+1225], 'Kerstmis'); appendEvent(dayElems[year*10000+1231], 'Oudejaarsavond'); appendEvent(dayElems[year*10000+ 301], 'Begin van de meteorologische lente'); appendEvent(dayElems[year*10000+ 601], 'Begin van de meteorologische zomer'); appendEvent(dayElems[year*10000+ 901], 'Begin van de meteorologische herfst'); appendEvent(dayElems[year*10000+1201], 'Begin van de meteorologische winter'); appendEvent(dayElems[easterYMD(year)], 'Pasen'); if(year < 9999) { appendBtn(f, 'NavToNextYear', 'ga naar ' + (year+1), 'navToNextYear'); } view.appendChild(f); } function scrollToToday() { var es = doc.getElementsByClassName('Today'); if(es.length) { var e = es[0]; e.scrollIntoView(); scrollBy(0, -e.scrollHeight * 5); } } function init(view) { view.addEventListener('click', function(e) { switch(e.target.getAttribute('data-action')) { case 'navToPrevYear': year -= 1; render(view); scrollTo(0, doc.body.scrollHeight); break; case 'navToNextYear': year += 1; render(view); scrollTo(0, 0); break; } }); render(view); setTimeout(scrollToToday, 10); } init(doc.getElementById('yearView')); }())
Clean up: extract function toYMD
kalender/kalender.js
Clean up: extract function toYMD
<ide><path>alender/kalender.js <ide> (function(){ <add> function toYMD(y,m,d) { return y*10000 + m*100 + d; } <add> function div(a,b) { return a/b>>0; } <add> <ide> var doc = document, <ide> today = new Date(), <ide> year = today.getFullYear(), <del> todayYMD = year*10000 + (today.getMonth()+1)*100 + today.getDate(), <add> todayYMD = toYMD(year,today.getMonth()+1,today.getDate()), <ide> monthNames = ['','januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'], <ide> shortMonthNames = ['','jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'], <ide> shortDayNames = ['zo','ma','di','wo','do','vr','za'], <ide> return (leap?monthDaysLeap:monthDays)[m]; <ide> } <ide> <del> function div(a,b) { return a/b>>0; } <del> <ide> function easterYMD(y) { <ide> var c = div(y,100), <ide> a = (19*(y%19) + c - div(c,4) - div((c - div((c+8),25)+1),3)+15)%30, <ide> b = (32 + 2*(c%4 + div(y%100,4)) - a - y%4) % 7, <ide> md = a + b - 7*div((y%19 + 11*a + 22*b),451) + 114; <del> return y*10000 + div(md,31)*100 + md%31+1; <add> return toYMD(y,div(md,31),md%31+1); <ide> } <ide> <ide> function addCls(e,cls) { <ide> } <ide> <ide> function appendDay(p,y,m,mday,wday,elems) { <del> var ymd = y*10000 + m*100 + mday, <add> var ymd = toYMD(y,m,mday), <ide> e = append(p, 'div', 'Day', ''); <ide> e.setAttribute('data-ymd', ymd); <ide> addCls(e, cssDayNames[wday]); <ide> var f = doc.createDocumentFragment(), <ide> month = 1, <ide> mday = 1, <del> ymd = year*10000 + month*100 + mday, <add> ymd = toYMD(year,month,mday), <ide> wday = firstWeekDay(year), <ide> wnum = firstWeekNum(wday), <ide> isLeap = isLeapYear(year), <ide> } <ide> } <ide> <del> appendEvent(dayElems[year*10000+ 101], 'Nieuwjaar'); <del> appendEvent(dayElems[year*10000+ 106], 'Driekoningen'); <del> appendEvent(dayElems[year*10000+ 214], 'Valentijnsdag'); <del> appendEvent(dayElems[year*10000+ 501], 'Dag van de Arbeid'); <del> appendEvent(dayElems[year*10000+ 711], 'Feestdag van de Vlaamse Gemeenschap'); <del> appendEvent(dayElems[year*10000+ 721], 'Nationale feestdag'); <del> appendEvent(dayElems[year*10000+ 815], 'O.L.V. Hemelvaart'); <del> appendEvent(dayElems[year*10000+ 927], 'Dag van de Franse Gemeenschap'); <del> appendEvent(dayElems[year*10000+1031], 'Halloween'); <del> appendEvent(dayElems[year*10000+1101], 'Allerheiligen'); <del> appendEvent(dayElems[year*10000+1102], 'Allerzielen'); <del> appendEvent(dayElems[year*10000+1111], 'Wapenstilstand'); <del> appendEvent(dayElems[year*10000+1111], 'Sint-Maarten'); <del> appendEvent(dayElems[year*10000+1115], 'Koningsdag'); <del> appendEvent(dayElems[year*10000+1115], 'Dag van de Duitstalige Gemeenschap'); <del> appendEvent(dayElems[year*10000+1206], 'Sinterklaas'); <del> appendEvent(dayElems[year*10000+1225], 'Kerstmis'); <del> appendEvent(dayElems[year*10000+1231], 'Oudejaarsavond'); <del> <del> appendEvent(dayElems[year*10000+ 301], 'Begin van de meteorologische lente'); <del> appendEvent(dayElems[year*10000+ 601], 'Begin van de meteorologische zomer'); <del> appendEvent(dayElems[year*10000+ 901], 'Begin van de meteorologische herfst'); <del> appendEvent(dayElems[year*10000+1201], 'Begin van de meteorologische winter'); <add> appendEvent(dayElems[toYMD(year,1,1)], 'Nieuwjaar'); <add> appendEvent(dayElems[toYMD(year,1,6)], 'Driekoningen'); <add> appendEvent(dayElems[toYMD(year,2,14)], 'Valentijnsdag'); <add> appendEvent(dayElems[toYMD(year,5,1)], 'Dag van de Arbeid'); <add> appendEvent(dayElems[toYMD(year,7,11)], 'Feestdag van de Vlaamse Gemeenschap'); <add> appendEvent(dayElems[toYMD(year,7,21)], 'Nationale feestdag'); <add> appendEvent(dayElems[toYMD(year,8,15)], 'O.L.V. Hemelvaart'); <add> appendEvent(dayElems[toYMD(year,9,27)], 'Dag van de Franse Gemeenschap'); <add> appendEvent(dayElems[toYMD(year,10,31)], 'Halloween'); <add> appendEvent(dayElems[toYMD(year,11,1)], 'Allerheiligen'); <add> appendEvent(dayElems[toYMD(year,11,2)], 'Allerzielen'); <add> appendEvent(dayElems[toYMD(year,11,11)], 'Wapenstilstand'); <add> appendEvent(dayElems[toYMD(year,11,11)], 'Sint-Maarten'); <add> appendEvent(dayElems[toYMD(year,11,15)], 'Koningsdag'); <add> appendEvent(dayElems[toYMD(year,11,15)], 'Dag van de Duitstalige Gemeenschap'); <add> appendEvent(dayElems[toYMD(year,12,6)], 'Sinterklaas'); <add> appendEvent(dayElems[toYMD(year,12,25)], 'Kerstmis'); <add> appendEvent(dayElems[toYMD(year,12,31)], 'Oudejaarsavond'); <add> <add> appendEvent(dayElems[toYMD(year,3,1)], 'Begin van de meteorologische lente'); <add> appendEvent(dayElems[toYMD(year,6,1)], 'Begin van de meteorologische zomer'); <add> appendEvent(dayElems[toYMD(year,9,1)], 'Begin van de meteorologische herfst'); <add> appendEvent(dayElems[toYMD(year,12,1)], 'Begin van de meteorologische winter'); <ide> <ide> appendEvent(dayElems[easterYMD(year)], 'Pasen'); <ide> <ide> case 'navToNextYear': <ide> year += 1; <ide> render(view); <del> scrollTo(0, 0); <add> scrollTo(0,0); <ide> break; <ide> } <ide> }); <ide> render(view); <del> setTimeout(scrollToToday, 10); <add> setTimeout(scrollToToday,10); <ide> } <ide> <ide> init(doc.getElementById('yearView'));
Java
apache-2.0
4ac7e5ca36630320f1323b1571e46267cee9fa01
0
stumoodie/MetabolicNotationSubsystem,stumoodie/MetabolicNotationSubsystem
package uk.ac.ed.inf.Metabolic.sbmlexport; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.pathwayeditor.businessobjectsAPI.IMap; import org.pathwayeditor.contextadapter.publicapi.ExportServiceException; import org.pathwayeditor.contextadapter.publicapi.IContext; import org.pathwayeditor.contextadapter.publicapi.IContextAdapterExportService; import uk.ac.ed.inf.Metabolic.ExportAdapterCreationException; import uk.ac.ed.inf.Metabolic.IExportAdapter; import uk.ac.ed.inf.Metabolic.ndomAPI.IModel; public class SBMLExportService implements IContextAdapterExportService { String DISPLAY_NAME = "SBML exportL2v3"; String RECOMMENDED_SUFFIX = "sbml"; final String TYPECODE= "MetSBML_1.0.0"; private IContext context; private IExportAdapter<IModel>generator; public SBMLExportService(IContext context) { super(); this.context = context; } /** * @throws IllegalArgumentException if either argument is null * @throws ExportServiceException if exportFile: <ul> * <li> Doesn't exist * <li> Is not writable. * <li> Cannot produce valid SBML * </ul> */ public void exportMap(IMap map, File exportFile) throws ExportServiceException { FileOutputStream fos = null; try{ checkArgs(map, exportFile); generator = new MetabolicSBMLExportAdapter<IModel>(); // replace this with real model from validation step generator.createTarget(new DummyModel ()); fos = new FileOutputStream(exportFile); generator.writeTarget(fos); } catch (ExportAdapterCreationException e) { throw new ExportServiceException(e); } catch (IOException e) { throw new ExportServiceException(e); }finally{ try { if(fos!=null) fos.close(); }catch(Exception e){} } } private void checkArgs(IMap map, File exportFile) throws ExportServiceException, IOException { if (map == null || exportFile ==null || map.getTheSingleRootMapObject() == null) { throw new IllegalArgumentException("Arguments must not be null"); } exportFile.createNewFile(); if(!exportFile.canWrite()) { throw new ExportServiceException ("File " + exportFile + " is not writable"); } } public String getCode() { return TYPECODE; } public IContext getContext() { return context; } public String getDisplayName() { return DISPLAY_NAME; } public String getRecommendedSuffix() { return RECOMMENDED_SUFFIX; } public String toString () { return new StringBuffer().append("Export service for context :") .append(context.toString()) .append("\n Display name :").append(DISPLAY_NAME) .append("\n Code: ").append(TYPECODE) .toString(); } }
src/uk/ac/ed/inf/Metabolic/sbmlexport/SBMLExportService.java
package uk.ac.ed.inf.Metabolic.sbmlexport; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.pathwayeditor.businessobjectsAPI.IMap; import org.pathwayeditor.contextadapter.publicapi.ExportServiceException; import org.pathwayeditor.contextadapter.publicapi.IContext; import org.pathwayeditor.contextadapter.publicapi.IContextAdapterExportService; import uk.ac.ed.inf.Metabolic.ExportAdapterCreationException; import uk.ac.ed.inf.Metabolic.IExportAdapter; import uk.ac.ed.inf.Metabolic.ndomAPI.IModel; public class SBMLExportService implements IContextAdapterExportService { String DISPLAY_NAME = "SBML exportL2v3"; String RECOMMENDED_SUFFIX = "sbml"; final String TYPECODE= "MetSBML_1.0.0"; private IContext context; private IExportAdapter<IModel>generator; public SBMLExportService(IContext context) { super(); this.context = context; } /** * @throws IllegalArgumentException if either argument is null * @throws ExportServiceException if exportFile: <ul> * <li> Doesn't exist * <li> Is not writable. * </ul> */ public void exportMap(IMap map, File exportFile) throws ExportServiceException { FileOutputStream fos = null; try{ checkArgs(map, exportFile); generator = new MetabolicSBMLExportAdapter<IModel>(); // replace this with real model from validation step generator.createTarget(new DummyModel ()); fos = new FileOutputStream(exportFile); generator.writeTarget(fos); } catch (ExportAdapterCreationException e) { throw new ExportServiceException(e); } catch (IOException e) { throw new ExportServiceException(e); }finally{ try { if(fos!=null) fos.close(); }catch(Exception e){} } } private void checkArgs(IMap map, File exportFile) throws ExportServiceException, IOException { if (map == null || exportFile ==null || map.getTheSingleRootMapObject() == null) { throw new IllegalArgumentException("Arguments must not be null"); } exportFile.createNewFile(); if(!exportFile.canWrite()) { throw new ExportServiceException ("File " + exportFile + " is not writable"); } } public String getCode() { return TYPECODE; } public IContext getContext() { return context; } public String getDisplayName() { return DISPLAY_NAME; } public String getRecommendedSuffix() { return RECOMMENDED_SUFFIX; } public String toString () { return new StringBuffer().append("Export service for context :") .append(context.toString()) .append("\n Display name :").append(DISPLAY_NAME) .append("\n Code: ").append(TYPECODE) .toString(); } }
docs
src/uk/ac/ed/inf/Metabolic/sbmlexport/SBMLExportService.java
docs
<ide><path>rc/uk/ac/ed/inf/Metabolic/sbmlexport/SBMLExportService.java <ide> * @throws ExportServiceException if exportFile: <ul> <ide> * <li> Doesn't exist <ide> * <li> Is not writable. <add> * <li> Cannot produce valid SBML <ide> * </ul> <ide> */ <ide> public void exportMap(IMap map, File exportFile) throws ExportServiceException {
Java
apache-2.0
22eb3050f0b4199d3f5c3415f1336640afa77287
0
InfoSec812/vertx-web,InfoSec812/vertx-web,InfoSec812/vertx-web,aesteve/vertx-web,aesteve/vertx-web,vert-x3/vertx-web,vert-x3/vertx-web,vert-x3/vertx-web,aesteve/vertx-web,aesteve/vertx-web,InfoSec812/vertx-web,vert-x3/vertx-web,vert-x3/vertx-web,aesteve/vertx-web,InfoSec812/vertx-web,InfoSec812/vertx-web
/* * Copyright 2014 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.web.handler.impl; import io.netty.handler.codec.http.HttpHeaderValues; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.file.FileSystem; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.FileUpload; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.impl.FileUploadImpl; import java.io.File; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * * @author <a href="http://tfox.org">Tim Fox</a> */ public class BodyHandlerImpl implements BodyHandler { private static final Logger log = LoggerFactory.getLogger(BodyHandlerImpl.class); private static final String BODY_HANDLED = "__body-handled"; private long bodyLimit = DEFAULT_BODY_LIMIT; private String uploadsDir; private boolean mergeFormAttributes = DEFAULT_MERGE_FORM_ATTRIBUTES; private boolean deleteUploadedFilesOnEnd = DEFAULT_DELETE_UPLOADED_FILES_ON_END; private static final int DEFAULT_INITIAL_BODY_BUFFER_SIZE = 1024; //bytes public BodyHandlerImpl() { setUploadsDirectory(DEFAULT_UPLOADS_DIRECTORY); } public BodyHandlerImpl(String uploadDirectory) { setUploadsDirectory(uploadDirectory); } @Override public void handle(RoutingContext context) { HttpServerRequest request = context.request(); if (request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) { context.next(); return; } // we need to keep state since we can be called again on reroute Boolean handled = context.get(BODY_HANDLED); if (handled == null || !handled) { Long contentLength = parseContentLengthHeader(request); BHandler handler = new BHandler(context, contentLength); request.handler(handler); request.endHandler(v -> handler.end()); context.put(BODY_HANDLED, true); } else { // on reroute we need to re-merge the form params if that was desired if (mergeFormAttributes && request.isExpectMultipart()) { request.params().addAll(request.formAttributes()); } context.next(); } } @Override public BodyHandler setBodyLimit(long bodyLimit) { this.bodyLimit = bodyLimit; return this; } @Override public BodyHandler setUploadsDirectory(String uploadsDirectory) { this.uploadsDir = uploadsDirectory; return this; } @Override public BodyHandler setMergeFormAttributes(boolean mergeFormAttributes) { this.mergeFormAttributes = mergeFormAttributes; return this; } @Override public BodyHandler setDeleteUploadedFilesOnEnd(boolean deleteUploadedFilesOnEnd) { this.deleteUploadedFilesOnEnd = deleteUploadedFilesOnEnd; return this; } private Long parseContentLengthHeader(HttpServerRequest request) { String contentLength = request.getHeader(HttpHeaders.CONTENT_LENGTH); if(contentLength == null || contentLength == "") { return null; } try{ long parsedContentLength = Long.parseLong(contentLength); return parsedContentLength < 0 ? null : parsedContentLength; } catch (NumberFormatException ex) { return null; } } private class BHandler implements Handler<Buffer> { RoutingContext context; Buffer body; boolean failed; AtomicInteger uploadCount = new AtomicInteger(); AtomicBoolean cleanup = new AtomicBoolean(false); boolean ended; long uploadSize = 0L; final boolean isMultipart; final boolean isUrlEncoded; public BHandler(RoutingContext context, Long contentLength) { this.context = context; Set<FileUpload> fileUploads = context.fileUploads(); final String contentType = context.request().getHeader(HttpHeaders.CONTENT_TYPE); if (contentType == null) { isMultipart = false; isUrlEncoded = false; } else { final String lowerCaseContentType = contentType.toLowerCase(); isMultipart = lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()); isUrlEncoded = lowerCaseContentType.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString()); } initBodyBuffer(contentLength); if (isMultipart || isUrlEncoded) { makeUploadDir(context.vertx().fileSystem()); context.request().setExpectMultipart(true); context.request().uploadHandler(upload -> { if (bodyLimit != -1 && upload.isSizeAvailable()) { // we can try to abort even before the upload starts long size = uploadSize + upload.size(); if (size > bodyLimit) { failed = true; context.fail(413); return; } } // we actually upload to a file with a generated filename uploadCount.incrementAndGet(); String uploadedFileName = new File(uploadsDir, UUID.randomUUID().toString()).getPath(); upload.streamToFileSystem(uploadedFileName); FileUploadImpl fileUpload = new FileUploadImpl(uploadedFileName, upload); fileUploads.add(fileUpload); upload.exceptionHandler(t -> { deleteFileUploads(); context.fail(t); }); upload.endHandler(v -> uploadEnded()); }); } context.request().exceptionHandler(t -> { deleteFileUploads(); context.fail(t); }); } private void initBodyBuffer(Long contentLength) { int initialBodyBufferSize; if(contentLength == null || contentLength < 0) { initialBodyBufferSize = DEFAULT_INITIAL_BODY_BUFFER_SIZE; } else if(contentLength > Integer.MAX_VALUE) { initialBodyBufferSize = Integer.MAX_VALUE; } else { initialBodyBufferSize = contentLength.intValue(); } if(bodyLimit != -1) { initialBodyBufferSize = (int)Math.min(initialBodyBufferSize, bodyLimit); } this.body = Buffer.buffer(initialBodyBufferSize); } private void makeUploadDir(FileSystem fileSystem) { if (!fileSystem.existsBlocking(uploadsDir)) { fileSystem.mkdirsBlocking(uploadsDir); } } @Override public void handle(Buffer buff) { if (failed) { return; } uploadSize += buff.length(); if (bodyLimit != -1 && uploadSize > bodyLimit) { failed = true; context.fail(413); // enqueue a delete for the error uploads context.vertx().runOnContext(v -> deleteFileUploads()); } else { // multipart requests will not end up in the request body // url encoded should also not, however jQuery by default // post in urlencoded even if the payload is something else if (!isMultipart /* && !isUrlEncoded */) { body.appendBuffer(buff); } } } void uploadEnded() { int count = uploadCount.decrementAndGet(); // only if parsing is done and count is 0 then all files have been processed if (ended && count == 0) { doEnd(); } } void end() { // this marks the end of body parsing, calling doEnd should // only be possible from this moment onwards ended = true; // only if parsing is done and count is 0 then all files have been processed if (uploadCount.get() == 0) { doEnd(); } } void doEnd() { if (failed) { deleteFileUploads(); return; } if (deleteUploadedFilesOnEnd) { context.addBodyEndHandler(x -> deleteFileUploads()); } HttpServerRequest req = context.request(); if (mergeFormAttributes && req.isExpectMultipart()) { req.params().addAll(req.formAttributes()); } context.setBody(body); context.next(); } private void deleteFileUploads() { if (cleanup.compareAndSet(false, true)) { for (FileUpload fileUpload : context.fileUploads()) { FileSystem fileSystem = context.vertx().fileSystem(); String uploadedFileName = fileUpload.uploadedFileName(); fileSystem.exists(uploadedFileName, existResult -> { if (existResult.failed()) { log.warn("Could not detect if uploaded file exists, not deleting: " + uploadedFileName, existResult.cause()); } else if (existResult.result()) { fileSystem.delete(uploadedFileName, deleteResult -> { if (deleteResult.failed()) { log.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause()); } }); } }); } } } } }
vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java
/* * Copyright 2014 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.web.handler.impl; import io.netty.handler.codec.http.HttpHeaderValues; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.file.FileSystem; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.vertx.ext.web.FileUpload; import io.vertx.ext.web.RoutingContext; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.ext.web.impl.FileUploadImpl; import java.io.File; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * * @author <a href="http://tfox.org">Tim Fox</a> */ public class BodyHandlerImpl implements BodyHandler { private static final Logger log = LoggerFactory.getLogger(BodyHandlerImpl.class); private static final String BODY_HANDLED = "__body-handled"; private long bodyLimit = DEFAULT_BODY_LIMIT; private String uploadsDir; private boolean mergeFormAttributes = DEFAULT_MERGE_FORM_ATTRIBUTES; private boolean deleteUploadedFilesOnEnd = DEFAULT_DELETE_UPLOADED_FILES_ON_END; private static final int DEFAULT_INITIAL_BODY_BUFFER_SIZE = 1024; //bytes public BodyHandlerImpl() { setUploadsDirectory(DEFAULT_UPLOADS_DIRECTORY); } public BodyHandlerImpl(String uploadDirectory) { setUploadsDirectory(uploadDirectory); } @Override public void handle(RoutingContext context) { HttpServerRequest request = context.request(); if (request.headers().contains(HttpHeaders.UPGRADE, HttpHeaders.WEBSOCKET, true)) { context.next(); return; } // we need to keep state since we can be called again on reroute Boolean handled = context.get(BODY_HANDLED); if (handled == null || !handled) { int bodyBufferInitialSize = getInitialBodyBufferSize(context.request()); BHandler handler = new BHandler(context, bodyBufferInitialSize); request.handler(handler); request.endHandler(v -> handler.end()); context.put(BODY_HANDLED, true); } else { // on reroute we need to re-merge the form params if that was desired if (mergeFormAttributes && request.isExpectMultipart()) { request.params().addAll(request.formAttributes()); } context.next(); } } @Override public BodyHandler setBodyLimit(long bodyLimit) { this.bodyLimit = bodyLimit; return this; } @Override public BodyHandler setUploadsDirectory(String uploadsDirectory) { this.uploadsDir = uploadsDirectory; return this; } @Override public BodyHandler setMergeFormAttributes(boolean mergeFormAttributes) { this.mergeFormAttributes = mergeFormAttributes; return this; } @Override public BodyHandler setDeleteUploadedFilesOnEnd(boolean deleteUploadedFilesOnEnd) { this.deleteUploadedFilesOnEnd = deleteUploadedFilesOnEnd; return this; } private int getInitialBodyBufferSize(HttpServerRequest request) { String contentLength = request.getHeader(HttpHeaders.CONTENT_LENGTH); if(contentLength == null || contentLength == "") { return DEFAULT_INITIAL_BODY_BUFFER_SIZE; } try{ long parsedContentLength = Long.parseLong(contentLength); if(parsedContentLength < 0) { return DEFAULT_INITIAL_BODY_BUFFER_SIZE; } return (int)Math.min(parsedContentLength, Integer.MAX_VALUE); } catch (NumberFormatException ex) { return DEFAULT_INITIAL_BODY_BUFFER_SIZE; } } private class BHandler implements Handler<Buffer> { RoutingContext context; Buffer body; boolean failed; AtomicInteger uploadCount = new AtomicInteger(); AtomicBoolean cleanup = new AtomicBoolean(false); boolean ended; long uploadSize = 0L; final boolean isMultipart; final boolean isUrlEncoded; public BHandler(RoutingContext context, int bodyBufferInitialSize) { this.context = context; Set<FileUpload> fileUploads = context.fileUploads(); final String contentType = context.request().getHeader(HttpHeaders.CONTENT_TYPE); if (contentType == null) { isMultipart = false; isUrlEncoded = false; } else { final String lowerCaseContentType = contentType.toLowerCase(); isMultipart = lowerCaseContentType.startsWith(HttpHeaderValues.MULTIPART_FORM_DATA.toString()); isUrlEncoded = lowerCaseContentType.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString()); } initBodyBuffer(bodyBufferInitialSize); if (isMultipart || isUrlEncoded) { makeUploadDir(context.vertx().fileSystem()); context.request().setExpectMultipart(true); context.request().uploadHandler(upload -> { if (bodyLimit != -1 && upload.isSizeAvailable()) { // we can try to abort even before the upload starts long size = uploadSize + upload.size(); if (size > bodyLimit) { failed = true; context.fail(413); return; } } // we actually upload to a file with a generated filename uploadCount.incrementAndGet(); String uploadedFileName = new File(uploadsDir, UUID.randomUUID().toString()).getPath(); upload.streamToFileSystem(uploadedFileName); FileUploadImpl fileUpload = new FileUploadImpl(uploadedFileName, upload); fileUploads.add(fileUpload); upload.exceptionHandler(t -> { deleteFileUploads(); context.fail(t); }); upload.endHandler(v -> uploadEnded()); }); } context.request().exceptionHandler(t -> { deleteFileUploads(); context.fail(t); }); } private void initBodyBuffer(int initialBodyBufferSize) { if(bodyLimit < 0) { this.body = Buffer.buffer(initialBodyBufferSize); } else { int bufferSize = (int) Math.min(bodyLimit, initialBodyBufferSize); this.body = Buffer.buffer(bufferSize); } } private void makeUploadDir(FileSystem fileSystem) { if (!fileSystem.existsBlocking(uploadsDir)) { fileSystem.mkdirsBlocking(uploadsDir); } } @Override public void handle(Buffer buff) { if (failed) { return; } uploadSize += buff.length(); if (bodyLimit != -1 && uploadSize > bodyLimit) { failed = true; context.fail(413); // enqueue a delete for the error uploads context.vertx().runOnContext(v -> deleteFileUploads()); } else { // multipart requests will not end up in the request body // url encoded should also not, however jQuery by default // post in urlencoded even if the payload is something else if (!isMultipart /* && !isUrlEncoded */) { body.appendBuffer(buff); } } } void uploadEnded() { int count = uploadCount.decrementAndGet(); // only if parsing is done and count is 0 then all files have been processed if (ended && count == 0) { doEnd(); } } void end() { // this marks the end of body parsing, calling doEnd should // only be possible from this moment onwards ended = true; // only if parsing is done and count is 0 then all files have been processed if (uploadCount.get() == 0) { doEnd(); } } void doEnd() { if (failed) { deleteFileUploads(); return; } if (deleteUploadedFilesOnEnd) { context.addBodyEndHandler(x -> deleteFileUploads()); } HttpServerRequest req = context.request(); if (mergeFormAttributes && req.isExpectMultipart()) { req.params().addAll(req.formAttributes()); } context.setBody(body); context.next(); } private void deleteFileUploads() { if (cleanup.compareAndSet(false, true)) { for (FileUpload fileUpload : context.fileUploads()) { FileSystem fileSystem = context.vertx().fileSystem(); String uploadedFileName = fileUpload.uploadedFileName(); fileSystem.exists(uploadedFileName, existResult -> { if (existResult.failed()) { log.warn("Could not detect if uploaded file exists, not deleting: " + uploadedFileName, existResult.cause()); } else if (existResult.result()) { fileSystem.delete(uploadedFileName, deleteResult -> { if (deleteResult.failed()) { log.warn("Delete of uploaded file failed: " + uploadedFileName, deleteResult.cause()); } }); } }); } } } } }
Separate the parsing of content length and body buffer initialization Signed-off-by: Michael Pogrebinsky <[email protected]>
vertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java
Separate the parsing of content length and body buffer initialization
<ide><path>ertx-web/src/main/java/io/vertx/ext/web/handler/impl/BodyHandlerImpl.java <ide> // we need to keep state since we can be called again on reroute <ide> Boolean handled = context.get(BODY_HANDLED); <ide> if (handled == null || !handled) { <del> int bodyBufferInitialSize = getInitialBodyBufferSize(context.request()); <del> BHandler handler = new BHandler(context, bodyBufferInitialSize); <add> Long contentLength = parseContentLengthHeader(request); <add> BHandler handler = new BHandler(context, contentLength); <ide> request.handler(handler); <ide> request.endHandler(v -> handler.end()); <ide> context.put(BODY_HANDLED, true); <ide> return this; <ide> } <ide> <del> private int getInitialBodyBufferSize(HttpServerRequest request) { <add> private Long parseContentLengthHeader(HttpServerRequest request) { <ide> String contentLength = request.getHeader(HttpHeaders.CONTENT_LENGTH); <ide> if(contentLength == null || contentLength == "") { <del> return DEFAULT_INITIAL_BODY_BUFFER_SIZE; <del> } <del> <add> return null; <add> } <ide> try{ <ide> long parsedContentLength = Long.parseLong(contentLength); <del> if(parsedContentLength < 0) { <del> return DEFAULT_INITIAL_BODY_BUFFER_SIZE; <del> } <del> return (int)Math.min(parsedContentLength, Integer.MAX_VALUE); <add> <add> return parsedContentLength < 0 ? null : parsedContentLength; <ide> } <ide> catch (NumberFormatException ex) { <del> return DEFAULT_INITIAL_BODY_BUFFER_SIZE; <add> return null; <ide> } <ide> } <ide> <ide> final boolean isMultipart; <ide> final boolean isUrlEncoded; <ide> <del> public BHandler(RoutingContext context, int bodyBufferInitialSize) { <add> public BHandler(RoutingContext context, Long contentLength) { <ide> this.context = context; <ide> Set<FileUpload> fileUploads = context.fileUploads(); <ide> <ide> isUrlEncoded = lowerCaseContentType.startsWith(HttpHeaderValues.APPLICATION_X_WWW_FORM_URLENCODED.toString()); <ide> } <ide> <del> initBodyBuffer(bodyBufferInitialSize); <add> initBodyBuffer(contentLength); <ide> <ide> if (isMultipart || isUrlEncoded) { <ide> makeUploadDir(context.vertx().fileSystem()); <ide> }); <ide> } <ide> <del> private void initBodyBuffer(int initialBodyBufferSize) { <del> if(bodyLimit < 0) { <del> this.body = Buffer.buffer(initialBodyBufferSize); <add> private void initBodyBuffer(Long contentLength) { <add> int initialBodyBufferSize; <add> if(contentLength == null || contentLength < 0) { <add> initialBodyBufferSize = DEFAULT_INITIAL_BODY_BUFFER_SIZE; <add> } <add> else if(contentLength > Integer.MAX_VALUE) { <add> initialBodyBufferSize = Integer.MAX_VALUE; <ide> } <ide> else { <del> int bufferSize = (int) Math.min(bodyLimit, initialBodyBufferSize); <del> this.body = Buffer.buffer(bufferSize); <del> } <add> initialBodyBufferSize = contentLength.intValue(); <add> } <add> <add> if(bodyLimit != -1) { <add> initialBodyBufferSize = (int)Math.min(initialBodyBufferSize, bodyLimit); <add> } <add> <add> this.body = Buffer.buffer(initialBodyBufferSize); <ide> } <ide> <ide> private void makeUploadDir(FileSystem fileSystem) {
Java
mit
413318d45cac348b07cc04008f3ac32dbfcc8fab
0
Nunnery/MythicDrops
package net.nunnerycode.bukkit.mythicdrops.socketting; import net.nunnerycode.bukkit.libraries.ivory.utils.ProjectileWrapperUtils; import net.nunnerycode.bukkit.libraries.ivory.utils.StringListUtils; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.settings.SockettingSettings; import net.nunnerycode.bukkit.mythicdrops.api.socketting.GemType; import net.nunnerycode.bukkit.mythicdrops.api.socketting.SocketCommandRunner; import net.nunnerycode.bukkit.mythicdrops.api.socketting.SocketEffect; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.utils.ItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.SocketGemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class SockettingListener implements Listener { private final Map<String, HeldItem> heldSocket = new HashMap<>(); private MythicDropsPlugin mythicDrops; public SockettingListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.NORMAL) public void onRightClick(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } if (event.getItem() == null) { return; } Player player = event.getPlayer(); if (!player.hasPermission("mythicdrops.socket")) { return; } ItemStack itemInHand = event.getItem(); String itemType = ItemUtil.getItemTypeFromMaterial(itemInHand.getType()); if (mythicDrops.getSockettingSettings().getSocketGemMaterials() .contains(itemInHand.getType())) { event.setUseItemInHand(Event.Result.DENY); player.updateInventory(); } if (itemType != null && ItemUtil.isArmor(itemType) && itemInHand.hasItemMeta()) { event.setUseItemInHand(Event.Result.DENY); player.updateInventory(); } if (heldSocket.containsKey(player.getName())) { socketItem(event, player, itemInHand, itemType); heldSocket.remove(player.getName()); } else { addHeldSocket(event, player, itemInHand); } } public List<SocketGem> getSocketGems(ItemStack itemStack) { List<SocketGem> socketGemList = new ArrayList<SocketGem>(); ItemMeta im; if (itemStack.hasItemMeta()) { im = itemStack.getItemMeta(); } else { return socketGemList; } List<String> lore = im.getLore(); if (lore == null) { return socketGemList; } for (String s : lore) { SocketGem sg = SocketGemUtil.getSocketGemFromName(ChatColor.stripColor(s)); if (sg == null) { continue; } socketGemList.add(sg); } return socketGemList; } @EventHandler(priority = EventPriority.MONITOR) public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { if (event.isCancelled()) { return; } Entity e = event.getEntity(); Entity d = event.getDamager(); if (!(e instanceof LivingEntity)) { return; } LivingEntity lee = (LivingEntity) e; LivingEntity led; if (d instanceof LivingEntity) { led = (LivingEntity) d; } else if (d instanceof Projectile) { Projectile p = (Projectile) d; led = ProjectileWrapperUtils.getShooter(p); if (led == null) { return; } } else { return; } applyEffects(led, lee); runCommands(led, lee); } public void runCommands(LivingEntity attacker, LivingEntity defender) { if (attacker == null || defender == null) { return; } SockettingSettings ss = mythicDrops.getSockettingSettings(); if (attacker instanceof Player) { if (ss.isUseAttackerArmorEquipped()) { for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) { if (attackersItem == null) { continue; } List<SocketGem> attackerSocketGems = getSocketGems(attackersItem); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } ((Player) attacker).chat("/" + command); } } } } } } if (ss.isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) { List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand()); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } ((Player) attacker).chat("/" + command); } } } } } } if (defender instanceof Player) { if (ss.isUseDefenderArmorEquipped()) { for (ItemStack defendersItem : defender.getEquipment().getArmorContents()) { if (defendersItem == null) { continue; } List<SocketGem> defenderSocketGems = getSocketGems(defendersItem); if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) { for (SocketGem sg : defenderSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } ((Player) defender).chat("/" + command); } } } } } } if (ss.isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) { List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand()); if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) { for (SocketGem sg : defenderSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } ((Player) defender).chat("/" + command); } } } } } } } public void applyEffects(LivingEntity attacker, LivingEntity defender) { if (attacker == null || defender == null) { return; } SockettingSettings ss = mythicDrops.getSockettingSettings(); // handle attacker if (ss.isUseAttackerArmorEquipped()) { for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) { if (attackersItem == null) { continue; } List<SocketGem> attackerSocketGems = getSocketGems(attackersItem); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(attacker); break; case OTHER: se.apply(defender); break; case AREA: for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(defender)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(attacker); } break; default: break; } } } } } } if (ss.isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) { List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand()); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(attacker); break; case OTHER: se.apply(defender); break; case AREA: for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(defender)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(attacker); } break; default: break; } } } } } // handle defender if (ss.isUseDefenderArmorEquipped()) { for (ItemStack defenderItem : defender.getEquipment().getArmorContents()) { if (defenderItem == null) { continue; } List<SocketGem> defenderSocketGems = getSocketGems(defenderItem); for (SocketGem sg : defenderSocketGems) { if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(defender); break; case OTHER: se.apply(attacker); break; case AREA: for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(attacker)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(defender); } break; default: break; } } } } } if (ss.isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) { List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand()); if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) { for (SocketGem sg : defenderSocketGems) { if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(defender); break; case OTHER: se.apply(attacker); break; case AREA: for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(attacker)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(defender); } break; default: break; } } } } } } private void addHeldSocket(PlayerInteractEvent event, final Player player, ItemStack itemInHand) { if (!mythicDrops.getSockettingSettings().getSocketGemMaterials() .contains(itemInHand.getType())) { return; } if (!itemInHand.hasItemMeta()) { return; } ItemMeta im = itemInHand.getItemMeta(); if (!im.hasDisplayName()) { return; } String replacedArgs = ChatColor.stripColor(replaceArgs(mythicDrops.getSockettingSettings().getSocketGemName(), new String[][]{{"%socketgem%", ""}}).replace('&', '\u00A7') .replace("\u00A7\u00A7", "&")); String type = ChatColor.stripColor(im.getDisplayName().replace(replacedArgs, "")); if (type == null) { return; } if (!replaceArgs(mythicDrops.getSockettingSettings().getSocketGemName(), new String[][]{{"%socketgem%", type}}).replace('&', '\u00A7') .replace("\u00A7\u00A7", "&").equals(im.getDisplayName())) { return; } SocketGem socketGem = mythicDrops.getSockettingSettings().getSocketGemMap().get(type); if (socketGem == null) { socketGem = SocketGemUtil.getSocketGemFromName(type); if (socketGem == null) { return; } } player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-instructions", new String[][]{}) ); HeldItem hg = new HeldItem(socketGem.getName(), itemInHand); heldSocket.put(player.getName(), hg); Bukkit.getScheduler().runTaskLaterAsynchronously(mythicDrops, new Runnable() { @Override public void run() { heldSocket.remove(player.getName()); } }, 30 * 20L); event.setCancelled(true); event.setUseInteractedBlock(Event.Result.DENY); event.setUseItemInHand(Event.Result.DENY); player.updateInventory(); } private String replaceArgs(String string, String[][] args) { String s = string; for (String[] arg : args) { s = s.replace(arg[0], arg[1]); } return s; } private void socketItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) { if (ItemUtil.isArmor(itemType) || ItemUtil.isTool(itemType)) { if (!itemInHand.hasItemMeta()) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } ItemMeta im = itemInHand.getItemMeta(); if (!im.hasLore()) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } List<String> lore = new ArrayList<>(im.getLore()); String socketString = mythicDrops.getSockettingSettings().getSockettedItemString().replace('&', '\u00A7') .replace("\u00A7\u00A7", "&").replace("%tiercolor%", ""); int index = indexOfStripColor(lore, socketString); if (index < 0) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } HeldItem heldSocket1 = heldSocket.get(player.getName()); String socketGemType = ChatColor.stripColor(heldSocket1 .getName()); SocketGem socketGem = SocketGemUtil.getSocketGemFromName(socketGemType); if (socketGem == null || !socketGemTypeMatchesItemStack(socketGem, itemInHand)) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } if (!player.getInventory().contains(heldSocket1.getItemStack())) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-do-not-have", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } if (itemInHand.getAmount() > heldSocket1.getItemStack().getAmount()) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-do-not-have", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } Tier tier = TierUtil.getTierFromItemStack(itemInHand); ChatColor cc = tier != null ? tier.getDisplayColor() : ChatColor.GOLD; lore.set(index, cc + socketGem.getName()); List<String> colorCoded = StringListUtils.replaceArgs( StringListUtils.colorList(mythicDrops.getSockettingSettings() .getSockettedItemLore(), '&'), new String[][]{{"%tiercolor%", tier != null ? tier.getDisplayColor() + "" : ""}} ); lore = StringListUtils.removeIfMatchesColorless(lore, colorCoded); im.setLore(lore); im = prefixItemStack(im, socketGem); im = suffixItemStack(im, socketGem); im = loreItemStack(im, socketGem); im = enchantmentItemStack(im, socketGem); int indexOfItem = player.getInventory().first(heldSocket1.getItemStack()); ItemStack inInventory = player.getInventory().getItem(indexOfItem); inInventory.setAmount(inInventory.getAmount() - itemInHand.getAmount()); player.getInventory().setItem(indexOfItem, inInventory); player.updateInventory(); itemInHand.setItemMeta(im); player.setItemInHand(itemInHand); player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-success", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); } else { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); } } private void cancelDenyRemove(PlayerInteractEvent event, Player player) { event.setCancelled(true); event.setUseInteractedBlock(Event.Result.DENY); event.setUseItemInHand(Event.Result.DENY); heldSocket.remove(player.getName()); } public boolean socketGemTypeMatchesItemStack(SocketGem socketGem, ItemStack itemStack) { String itemType = ItemUtil.getItemTypeFromMaterial(itemStack.getType()); if (itemType == null) { return false; } switch (socketGem.getGemType()) { case TOOL: return ItemUtil.isTool(itemType); case ARMOR: return ItemUtil.isArmor(itemType); case ANY: return true; default: return false; } } public int indexOfStripColor(List<String> list, String string) { String[] array = list.toArray(new String[list.size()]); for (int i = 0; i < array.length; i++) { if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) { return i; } } return -1; } public int indexOfStripColor(String[] array, String string) { for (int i = 0; i < array.length; i++) { if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) { return i; } } return -1; } public ItemMeta loreItemStack(ItemMeta im, SocketGem socketGem) { if (!im.hasLore()) { im.setLore(new ArrayList<String>()); } List<String> lore = new ArrayList<>(im.getLore()); if (lore.containsAll(socketGem.getLore())) { return im; } for (String s : socketGem.getLore()) { lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&")); } im.setLore(lore); return im; } public ItemMeta enchantmentItemStack(ItemMeta itemMeta, SocketGem socketGem) { if (itemMeta == null || socketGem == null) { return itemMeta; } Map<Enchantment, Integer> itemStackEnchantments = new HashMap<>(itemMeta.getEnchants()); for (Map.Entry<Enchantment, Integer> entry : socketGem.getEnchantments().entrySet()) { int currentLevel = itemStackEnchantments.containsKey(entry.getKey()) ? itemStackEnchantments.get(entry.getKey()) : 0; currentLevel += entry.getValue(); itemStackEnchantments.put(entry.getKey(), currentLevel); } for (Enchantment ench : itemStackEnchantments.keySet()) { itemMeta.removeEnchant(ench); } for (Map.Entry<Enchantment, Integer> entry : itemStackEnchantments.entrySet()) { itemMeta.addEnchant(entry.getKey(), entry.getValue(), true); } return itemMeta; } public ItemMeta suffixItemStack(ItemMeta im, SocketGem socketGem) { String name = im.getDisplayName(); if (name == null) { return im; } ChatColor beginColor = findColor(name); String lastColors = ChatColor.getLastColors(name); if (beginColor == null) { beginColor = ChatColor.WHITE; } String suffix = socketGem.getSuffix(); if (suffix == null || suffix.equalsIgnoreCase("")) { return im; } if (mythicDrops.getSockettingSettings().isPreventMultipleChangesFromSockets() && ChatColor.stripColor(name).contains(suffix) || containsAnyFromList(ChatColor.stripColor(name), mythicDrops.getSockettingSettings().getSocketGemSuffixes())) { return im; } im.setDisplayName(name + " " + beginColor + suffix + lastColors); return im; } public ItemMeta prefixItemStack(ItemMeta im, SocketGem socketGem) { String name = im.getDisplayName(); if (name == null) { return im; } ChatColor beginColor = findColor(name); if (beginColor == null) { beginColor = ChatColor.WHITE; } String prefix = socketGem.getPrefix(); if (prefix == null || prefix.equalsIgnoreCase("")) { return im; } if (mythicDrops.getSockettingSettings().isPreventMultipleChangesFromSockets() && ChatColor.stripColor(name).contains(prefix) || containsAnyFromList( ChatColor.stripColor(name), mythicDrops.getSockettingSettings().getSocketGemPrefixes())) { return im; } im.setDisplayName(beginColor + prefix + " " + name); return im; } public boolean containsAnyFromList(String string, List<String> list) { for (String s : list) { if (string.toUpperCase().contains(s.toUpperCase())) { return true; } } return false; } public ChatColor findColor(final String s) { char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == (char) 167 && i + 1 < c.length) { return ChatColor.getByChar(c[i + 1]); } } return null; } private static class HeldItem { private final String name; private final ItemStack itemStack; public HeldItem(String name, ItemStack itemStack) { this.name = name; this.itemStack = itemStack; } public String getName() { return name; } public ItemStack getItemStack() { return itemStack; } } }
src/main/java/net/nunnerycode/bukkit/mythicdrops/socketting/SockettingListener.java
package net.nunnerycode.bukkit.mythicdrops.socketting; import net.nunnerycode.bukkit.libraries.ivory.utils.StringListUtils; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.settings.SockettingSettings; import net.nunnerycode.bukkit.mythicdrops.api.socketting.GemType; import net.nunnerycode.bukkit.mythicdrops.api.socketting.SocketCommandRunner; import net.nunnerycode.bukkit.mythicdrops.api.socketting.SocketEffect; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.utils.ItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.SocketGemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.Event; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public final class SockettingListener implements Listener { private final Map<String, HeldItem> heldSocket = new HashMap<>(); private MythicDropsPlugin mythicDrops; public SockettingListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.NORMAL) public void onRightClick(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_AIR && event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } if (event.getItem() == null) { return; } Player player = event.getPlayer(); if (!player.hasPermission("mythicdrops.socket")) { return; } ItemStack itemInHand = event.getItem(); String itemType = ItemUtil.getItemTypeFromMaterial(itemInHand.getType()); if (mythicDrops.getSockettingSettings().getSocketGemMaterials() .contains(itemInHand.getType())) { event.setUseItemInHand(Event.Result.DENY); player.updateInventory(); } if (itemType != null && ItemUtil.isArmor(itemType) && itemInHand.hasItemMeta()) { event.setUseItemInHand(Event.Result.DENY); player.updateInventory(); } if (heldSocket.containsKey(player.getName())) { socketItem(event, player, itemInHand, itemType); heldSocket.remove(player.getName()); } else { addHeldSocket(event, player, itemInHand); } } public List<SocketGem> getSocketGems(ItemStack itemStack) { List<SocketGem> socketGemList = new ArrayList<SocketGem>(); ItemMeta im; if (itemStack.hasItemMeta()) { im = itemStack.getItemMeta(); } else { return socketGemList; } List<String> lore = im.getLore(); if (lore == null) { return socketGemList; } for (String s : lore) { SocketGem sg = SocketGemUtil.getSocketGemFromName(ChatColor.stripColor(s)); if (sg == null) { continue; } socketGemList.add(sg); } return socketGemList; } @EventHandler(priority = EventPriority.MONITOR) public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { if (event.isCancelled()) { return; } Entity e = event.getEntity(); Entity d = event.getDamager(); if (!(e instanceof LivingEntity)) { return; } LivingEntity lee = (LivingEntity) e; LivingEntity led; if (d instanceof LivingEntity) { led = (LivingEntity) d; } else if (d instanceof Projectile) { Projectile p = (Projectile) d; if (!(p.getShooter() instanceof LivingEntity)) { return; } led = (LivingEntity) ((Projectile) d).getShooter(); } else { return; } applyEffects(led, lee); runCommands(led, lee); } public void runCommands(LivingEntity attacker, LivingEntity defender) { if (attacker == null || defender == null) { return; } SockettingSettings ss = mythicDrops.getSockettingSettings(); if (attacker instanceof Player) { if (ss.isUseAttackerArmorEquipped()) { for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) { if (attackersItem == null) { continue; } List<SocketGem> attackerSocketGems = getSocketGems(attackersItem); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } ((Player) attacker).chat("/" + command); } } } } } } if (ss.isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) { List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand()); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) attacker).getName()); } if (command.contains("%target%")) { if (defender instanceof Player) { command = command.replace("%target%", ((Player) defender).getName()); } else { continue; } } ((Player) attacker).chat("/" + command); } } } } } } if (defender instanceof Player) { if (ss.isUseDefenderArmorEquipped()) { for (ItemStack defendersItem : defender.getEquipment().getArmorContents()) { if (defendersItem == null) { continue; } List<SocketGem> defenderSocketGems = getSocketGems(defendersItem); if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) { for (SocketGem sg : defenderSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } ((Player) defender).chat("/" + command); } } } } } } if (ss.isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) { List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand()); if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) { for (SocketGem sg : defenderSocketGems) { if (sg == null) { continue; } for (SocketCommand sc : sg.getCommands()) { if (sc.getRunner() == SocketCommandRunner.CONSOLE) { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command); } else { String command = sc.getCommand(); if (command.contains("%wielder%")) { command = command.replace("%wielder%", ((Player) defender).getName()); } if (command.contains("%target%")) { if (attacker instanceof Player) { command = command.replace("%target%", ((Player) attacker).getName()); } else { continue; } } ((Player) defender).chat("/" + command); } } } } } } } public void applyEffects(LivingEntity attacker, LivingEntity defender) { if (attacker == null || defender == null) { return; } SockettingSettings ss = mythicDrops.getSockettingSettings(); // handle attacker if (ss.isUseAttackerArmorEquipped()) { for (ItemStack attackersItem : attacker.getEquipment().getArmorContents()) { if (attackersItem == null) { continue; } List<SocketGem> attackerSocketGems = getSocketGems(attackersItem); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(attacker); break; case OTHER: se.apply(defender); break; case AREA: for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(defender)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(attacker); } break; default: break; } } } } } } if (ss.isUseAttackerItemInHand() && attacker.getEquipment().getItemInHand() != null) { List<SocketGem> attackerSocketGems = getSocketGems(attacker.getEquipment().getItemInHand()); if (attackerSocketGems != null && !attackerSocketGems.isEmpty()) { for (SocketGem sg : attackerSocketGems) { if (sg == null) { continue; } if (sg.getGemType() != GemType.TOOL && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(attacker); break; case OTHER: se.apply(defender); break; case AREA: for (Entity e : attacker.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(defender)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(attacker); } break; default: break; } } } } } // handle defender if (ss.isUseDefenderArmorEquipped()) { for (ItemStack defenderItem : defender.getEquipment().getArmorContents()) { if (defenderItem == null) { continue; } List<SocketGem> defenderSocketGems = getSocketGems(defenderItem); for (SocketGem sg : defenderSocketGems) { if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(defender); break; case OTHER: se.apply(attacker); break; case AREA: for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(attacker)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(defender); } break; default: break; } } } } } if (ss.isUseDefenderItemInHand() && defender.getEquipment().getItemInHand() != null) { List<SocketGem> defenderSocketGems = getSocketGems(defender.getEquipment().getItemInHand()); if (defenderSocketGems != null && !defenderSocketGems.isEmpty()) { for (SocketGem sg : defenderSocketGems) { if (sg.getGemType() != GemType.ARMOR && sg.getGemType() != GemType.ANY) { continue; } for (SocketEffect se : sg.getSocketEffects()) { if (se == null) { continue; } switch (se.getEffectTarget()) { case SELF: se.apply(defender); break; case OTHER: se.apply(attacker); break; case AREA: for (Entity e : defender.getNearbyEntities(se.getRadius(), se.getRadius(), se.getRadius())) { if (!(e instanceof LivingEntity)) { continue; } if (!se.isAffectsTarget() && e.equals(attacker)) { continue; } se.apply((LivingEntity) e); } if (se.isAffectsWielder()) { se.apply(defender); } break; default: break; } } } } } } private void addHeldSocket(PlayerInteractEvent event, final Player player, ItemStack itemInHand) { if (!mythicDrops.getSockettingSettings().getSocketGemMaterials() .contains(itemInHand.getType())) { return; } if (!itemInHand.hasItemMeta()) { return; } ItemMeta im = itemInHand.getItemMeta(); if (!im.hasDisplayName()) { return; } String replacedArgs = ChatColor.stripColor(replaceArgs(mythicDrops.getSockettingSettings().getSocketGemName(), new String[][]{{"%socketgem%", ""}}).replace('&', '\u00A7') .replace("\u00A7\u00A7", "&")); String type = ChatColor.stripColor(im.getDisplayName().replace(replacedArgs, "")); if (type == null) { return; } if (!replaceArgs(mythicDrops.getSockettingSettings().getSocketGemName(), new String[][]{{"%socketgem%", type}}).replace('&', '\u00A7') .replace("\u00A7\u00A7", "&").equals(im.getDisplayName())) { return; } SocketGem socketGem = mythicDrops.getSockettingSettings().getSocketGemMap().get(type); if (socketGem == null) { socketGem = SocketGemUtil.getSocketGemFromName(type); if (socketGem == null) { return; } } player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-instructions", new String[][]{}) ); HeldItem hg = new HeldItem(socketGem.getName(), itemInHand); heldSocket.put(player.getName(), hg); Bukkit.getScheduler().runTaskLaterAsynchronously(mythicDrops, new Runnable() { @Override public void run() { heldSocket.remove(player.getName()); } }, 30 * 20L); event.setCancelled(true); event.setUseInteractedBlock(Event.Result.DENY); event.setUseItemInHand(Event.Result.DENY); player.updateInventory(); } private String replaceArgs(String string, String[][] args) { String s = string; for (String[] arg : args) { s = s.replace(arg[0], arg[1]); } return s; } private void socketItem(PlayerInteractEvent event, Player player, ItemStack itemInHand, String itemType) { if (ItemUtil.isArmor(itemType) || ItemUtil.isTool(itemType)) { if (!itemInHand.hasItemMeta()) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } ItemMeta im = itemInHand.getItemMeta(); if (!im.hasLore()) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } List<String> lore = new ArrayList<>(im.getLore()); String socketString = mythicDrops.getSockettingSettings().getSockettedItemString().replace('&', '\u00A7') .replace("\u00A7\u00A7", "&").replace("%tiercolor%", ""); int index = indexOfStripColor(lore, socketString); if (index < 0) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } HeldItem heldSocket1 = heldSocket.get(player.getName()); String socketGemType = ChatColor.stripColor(heldSocket1 .getName()); SocketGem socketGem = SocketGemUtil.getSocketGemFromName(socketGemType); if (socketGem == null || !socketGemTypeMatchesItemStack(socketGem, itemInHand)) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } if (!player.getInventory().contains(heldSocket1.getItemStack())) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-do-not-have", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } if (itemInHand.getAmount() > heldSocket1.getItemStack().getAmount()) { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-do-not-have", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); return; } Tier tier = TierUtil.getTierFromItemStack(itemInHand); ChatColor cc = tier != null ? tier.getDisplayColor() : ChatColor.GOLD; lore.set(index, cc + socketGem.getName()); List<String> colorCoded = StringListUtils.replaceArgs( StringListUtils.colorList(mythicDrops.getSockettingSettings() .getSockettedItemLore(), '&'), new String[][]{{"%tiercolor%", tier != null ? tier.getDisplayColor() + "" : ""}} ); lore = StringListUtils.removeIfMatchesColorless(lore, colorCoded); im.setLore(lore); im = prefixItemStack(im, socketGem); im = suffixItemStack(im, socketGem); im = loreItemStack(im, socketGem); im = enchantmentItemStack(im, socketGem); int indexOfItem = player.getInventory().first(heldSocket1.getItemStack()); ItemStack inInventory = player.getInventory().getItem(indexOfItem); inInventory.setAmount(inInventory.getAmount() - itemInHand.getAmount()); player.getInventory().setItem(indexOfItem, inInventory); player.updateInventory(); itemInHand.setItemMeta(im); player.setItemInHand(itemInHand); player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-success", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); } else { player.sendMessage( mythicDrops.getConfigSettings().getFormattedLanguageString("command.socket-cannot-use", new String[][]{}) ); cancelDenyRemove(event, player); player.updateInventory(); } } private void cancelDenyRemove(PlayerInteractEvent event, Player player) { event.setCancelled(true); event.setUseInteractedBlock(Event.Result.DENY); event.setUseItemInHand(Event.Result.DENY); heldSocket.remove(player.getName()); } public boolean socketGemTypeMatchesItemStack(SocketGem socketGem, ItemStack itemStack) { String itemType = ItemUtil.getItemTypeFromMaterial(itemStack.getType()); if (itemType == null) { return false; } switch (socketGem.getGemType()) { case TOOL: return ItemUtil.isTool(itemType); case ARMOR: return ItemUtil.isArmor(itemType); case ANY: return true; default: return false; } } public int indexOfStripColor(List<String> list, String string) { String[] array = list.toArray(new String[list.size()]); for (int i = 0; i < array.length; i++) { if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) { return i; } } return -1; } public int indexOfStripColor(String[] array, String string) { for (int i = 0; i < array.length; i++) { if (ChatColor.stripColor(array[i]).equalsIgnoreCase(ChatColor.stripColor(string))) { return i; } } return -1; } public ItemMeta loreItemStack(ItemMeta im, SocketGem socketGem) { if (!im.hasLore()) { im.setLore(new ArrayList<String>()); } List<String> lore = new ArrayList<>(im.getLore()); if (lore.containsAll(socketGem.getLore())) { return im; } for (String s : socketGem.getLore()) { lore.add(s.replace('&', '\u00A7').replace("\u00A7\u00A7", "&")); } im.setLore(lore); return im; } public ItemMeta enchantmentItemStack(ItemMeta itemMeta, SocketGem socketGem) { if (itemMeta == null || socketGem == null) { return itemMeta; } Map<Enchantment, Integer> itemStackEnchantments = new HashMap<>(itemMeta.getEnchants()); for (Map.Entry<Enchantment, Integer> entry : socketGem.getEnchantments().entrySet()) { int currentLevel = itemStackEnchantments.containsKey(entry.getKey()) ? itemStackEnchantments.get(entry.getKey()) : 0; currentLevel += entry.getValue(); itemStackEnchantments.put(entry.getKey(), currentLevel); } for (Enchantment ench : itemStackEnchantments.keySet()) { itemMeta.removeEnchant(ench); } for (Map.Entry<Enchantment, Integer> entry : itemStackEnchantments.entrySet()) { itemMeta.addEnchant(entry.getKey(), entry.getValue(), true); } return itemMeta; } public ItemMeta suffixItemStack(ItemMeta im, SocketGem socketGem) { String name = im.getDisplayName(); if (name == null) { return im; } ChatColor beginColor = findColor(name); String lastColors = ChatColor.getLastColors(name); if (beginColor == null) { beginColor = ChatColor.WHITE; } String suffix = socketGem.getSuffix(); if (suffix == null || suffix.equalsIgnoreCase("")) { return im; } if (mythicDrops.getSockettingSettings().isPreventMultipleChangesFromSockets() && ChatColor.stripColor(name).contains(suffix) || containsAnyFromList(ChatColor.stripColor(name), mythicDrops.getSockettingSettings().getSocketGemSuffixes())) { return im; } im.setDisplayName(name + " " + beginColor + suffix + lastColors); return im; } public ItemMeta prefixItemStack(ItemMeta im, SocketGem socketGem) { String name = im.getDisplayName(); if (name == null) { return im; } ChatColor beginColor = findColor(name); if (beginColor == null) { beginColor = ChatColor.WHITE; } String prefix = socketGem.getPrefix(); if (prefix == null || prefix.equalsIgnoreCase("")) { return im; } if (mythicDrops.getSockettingSettings().isPreventMultipleChangesFromSockets() && ChatColor.stripColor(name).contains(prefix) || containsAnyFromList( ChatColor.stripColor(name), mythicDrops.getSockettingSettings().getSocketGemPrefixes())) { return im; } im.setDisplayName(beginColor + prefix + " " + name); return im; } public boolean containsAnyFromList(String string, List<String> list) { for (String s : list) { if (string.toUpperCase().contains(s.toUpperCase())) { return true; } } return false; } public ChatColor findColor(final String s) { char[] c = s.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == (char) 167 && i + 1 < c.length) { return ChatColor.getByChar(c[i + 1]); } } return null; } private static class HeldItem { private final String name; private final ItemStack itemStack; public HeldItem(String name, ItemStack itemStack) { this.name = name; this.itemStack = itemStack; } public String getName() { return name; } public ItemStack getItemStack() { return itemStack; } } }
changing method of getting projectile launcher
src/main/java/net/nunnerycode/bukkit/mythicdrops/socketting/SockettingListener.java
changing method of getting projectile launcher
<ide><path>rc/main/java/net/nunnerycode/bukkit/mythicdrops/socketting/SockettingListener.java <ide> package net.nunnerycode.bukkit.mythicdrops.socketting; <ide> <add>import net.nunnerycode.bukkit.libraries.ivory.utils.ProjectileWrapperUtils; <ide> import net.nunnerycode.bukkit.libraries.ivory.utils.StringListUtils; <ide> import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; <ide> import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; <ide> led = (LivingEntity) d; <ide> } else if (d instanceof Projectile) { <ide> Projectile p = (Projectile) d; <del> if (!(p.getShooter() instanceof LivingEntity)) { <add> led = ProjectileWrapperUtils.getShooter(p); <add> if (led == null) { <ide> return; <ide> } <del> led = (LivingEntity) ((Projectile) d).getShooter(); <ide> } else { <ide> return; <ide> }
JavaScript
mit
9af99ab750c0f7d74e88a1a0b30ed05ec17b6691
0
DataEstate/dataestate-angular,DataEstate/datae-state-angular,DataEstate/dataestate-angular
//Version 0.5.5 added support for Signups endpoint var de = angular.module("dataEstateModule", []); //CONSTANTS de.constant('VERSION', 0.5); //Main Provider de.provider('DeApi', function () { this.apiUrl = "https://api.dataestate.net/v2"; //Default this.apiKey = ""; this.authType = "api-key"; //Default v0.1.4 this.oauthData = {}; //Configurations. this.setApi = function (api_url) { this.apiUrl = api_url; } this.setApiKey = function (api_key) { this.apiKey = api_key; } //v0.1.4 this.setToken = function (auth_token) { this.oauthData.token = auth_token; } //v0.4.9: added "none" for proxies this.setAuthType = function (auth_type) { var allowedTypes = ["token", "api-key", "none"]; if (allowedTypes.indexOf(auth_type) >= 0) { this.authType = auth_type; } } this.getAuthType = function () { return this.authType; } //RETURN THIS this.$get = function ($http) { //Base requester. this.get = function (endpoints, params) { if (endpoints !== undefined) { var httpReq = { url: this.apiUrl + endpoints, method: "GET" }; if (this.authType == "api-key") { if (params !== undefined && !params.hasOwnProperty("api_key")) { params.api_key = this.apiKey; } } else if (this.authType == "token") { httpReq.headers = { "Authorization": "Bearer " + this.oauthData.token }; } if (params !== undefined && params.keyword !== undefined) { params.keyword = decodeURI(params.keyword); } httpReq.params = params; return $http(httpReq); } } this.put = function (endpoints, data) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; }; return $http({ url: this.apiUrl + endpoints, method: "PUT", data: data, headers: rh }); } } this.post = function (endpoints, data) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; } return $http({ url: this.apiUrl + endpoints, method: "POST", data: data, headers: rh }); } } this.delete = function (endpoints) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; } return $http({ url: this.apiUrl + endpoints, method: "DELETE", headers: rh }); } } //Must follow RFC6902 structure this.patch = function (endpoints, pipeline) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; } return $http({ url: this.apiUrl + endpoints, method: "PATCH", data: pipeline, headers: rh }); } } return this; } }); //Estate Service de.factory('DeEstates', function (DeApi) { return { data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/estates/data/" + id; return DeApi.get(endpoints, params); }, update: function (id, data, language, remove_data, add_data) { var endpoints = "/estates/data/" + id; var putData = { "data": data }; if (language !== undefined && language != "english") { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, create: function (category_code, data) { var endpoints = "/estates/data/"; var postData = { "data": data } return DeApi.post(endpoints, postData); }, remove: function (id) { var endpoints = "/estates/data/" + id; return DeApi.delete(endpoints); } } }); // v0.1.6: assets added categories as dictionary. de.factory('DeAssets', function (DeApi) { var currentEstate = ""; return { setEstate: function (estate) { currentEstate = estate; }, getEstate: function () { return currentEstate; }, data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/assets/data/" + id; return DeApi.get(endpoints, params); }, articles: function (estate, slug, params = {}) { if (slug == undefined) { slug = ""; } var endpoints = "/assets/articles/" + estate + "/" + slug; return DeApi.get(endpoints, params); }, // v0.1.3 timetable: function (params) { var endpoints = "/assets/timetable/"; return DeApi.get(endpoints, params); }, //v0.1.8 flights: function (params) { var endpoints = "/assets/flights/"; return DeApi.get(endpoints, params); }, update: function (id, data, language, remove_data, add_data) { var endpoints = "/assets/data/" + id; var putData = { "data": data }; if (language !== undefined) { putData.language = language; } if (remove_data !== undefined && remove_data !== null && Object.keys(remove_data).length > 0) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, create: function (estate, type, data) { var endpoints = "/assets/data/"; if (!data.hasOwnProperty("type")) { data.type = type; } if (estate === undefined) { estate = currentEstate; } var postData = { "data": data, "estate_id": estate } return DeApi.post(endpoints, postData); }, remove: function (id) { var endpoints = "/assets/data/" + id; return DeApi.delete(endpoints); }, bulkRemove: function (estate, type, ids) { var endpoints = "/assets/data/" + estate; var bulkPipeline = []; for (var i in ids) { bulkPipeline.push({ "op": "remove", "path": type + "/" + ids[i] }); } return DeApi.patch(endpoints, bulkPipeline); } } }); // v0.3.6 de.factory('DeUsers', function (DeApi, $q) { var currentUser = null; return { data: function (reload) { var d = $q.defer(); var endpoints = "/users/data/"; if (reload == true || currentUser === null) { DeApi.get(endpoints).then( function success(res) { currentUser = res.data; d.resolve(currentUser); }, function error(err) { d.reject(err); }); } else { d.resolve(currentUser); } return d.promise; } } }) // v0.1.2: taxonomy - TODO: Get from API. de.factory('DeTaxonomy', function (DeApi) { var subtypes = [ { "type": "LANDMARK", "description": "Landmark" }, { "type": "EDUCATION", "description": "Educational" }, { "type": "FOODDRINK", "description": "Food and Drink" }, { "type": "MUSICAL", "description": "Musical Performance" }, { "type": "CEREMONY", "description": "Ceremony" }, { "type": "SPORT", "description": "Sports Event" }, { "type": "PERFORMANCE", "description": "Performances" }, { "type": "PARADE", "description": "March and Parade" }, { "type": "CULTURAL", "description": "Cutural" }, { "type": "ACTIVITY", "description": "Activities" }, { "type": "MEDITATION", "description": "Meditation" }, { "type": "PHOTOGRAPHY", "description": "Photography Event" }, { "type": "TALK", "description": "Talks" }, { "type": "FORUM", "description": "Forums" }, { "type": "FOOD", "description": "Food" }, { "type": "DESSERT", "description": "Snacks and Desserts" }, { "type": "DRINK", "description": "Drinks" }, { "type": "SHOP", "description": "Shops" }, { "type": "INFO", "description": "Information" }, { "type": "VOLUNTEER", "description": "Volunteers" }, { "type": "DISPLAY", "description": "Art and Display" }, { "type": "SERVICE", "description": "Services" } ]; var locations = [ { "id": "BNELETTER", "name": "Brisbane Letters", "loc": [ -27.474147, 153.020482 ] }, { "id": "QC", "name": "Queensland Conservatorium", "loc": [ -27.4768193, 153.0208075 ] }, { "id": "LIANA", "name": "Liana Lounge", "loc": [ -27.475902, 153.021213 ] }, { "loc": [ -27.4706487, 153.0170457 ], "id": "GOMA", "name": "GOMA (Gallery of Modern Art)" }, { "id": "CF", "name": "Cultural Forecourt", "loc": [ -27.4739896, 153.0203686 ] }, { "loc": [ -27.4748418, 153.0212796 ], "id": "RB", "name": "Riverbank" }, { "loc": [ -27.476474, 153.021173 ], "name": "Lumbini Garden", "id": "LG" }, { "loc": [ -27.4771943, 153.0217732 ], "id": "NB", "name": "No Boundaries" }, { "loc": [ -27.476186, 153.021666 ], "name": "Rainforest Green", "id": "RG" }, { "id": "CMP", "name": "The South Bank Piazza", "loc": [ -27.4769716, 153.0214888 ] }, { "id": "PAS", "loc": [ -27.474771, 153.0209563 ], "name": "Performing Arts Stage" } ]; var categories = { "ACCOMM": "Accommodation", "APP": "Application", "ATTRACTION": "Attraction", "COMPANY": "Company", "DESTINFO": "Destination Information", "EVENT": "Event", "GROUP": "Group", "HIRE": "Hire", "INFO": "Information Services", "JOURNEY": "Journey", "ORG": "Organisation", "RESTAURANT": "Food and Drink", "TOUR": "Tour", "TRANSPORT": "Transport" }; var social = [ { id: "in", name: "Instagram" }, { id: "fb", name: "Facebook" }, { id: "li", name: "LinkedIn" }, { id: "tw", name: "Twitter" }, { id: "yt", name: "YouTube" } ]; return { subtypes: function () { return subtypes; }, locations: function () { return locations; }, categories: function () { return categories; }, accreditations: function () { var endpoints = "/taxonomy/data/ACCREDITN"; return DeApi.get(endpoints, {}); },//v0.3 social: function () { return social; }, data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/taxonomy/data/" + id; return DeApi.get(endpoints, params); }, //v0.3.8 update: function (id, data, language, remove_data, add_data) { var endpoints = "/taxonomy/data/" + id; var putData = { "data": data }; if (language !== undefined) { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, create: function (type, data) { var endpoints = "/taxonomy/data/"; if (!data.hasOwnProperty("type")) { data.type = type; } var postData = { "data": data } return DeApi.post(endpoints, postData); }, remove: function (id) { var endpoints = "/taxonomy/data/" + id; return DeApi.delete(endpoints); } } }); // v0.4.5 de.factory('DeLocations', function (DeApi) { return { data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/locations/data/" + id; return DeApi.get(endpoints, params); }, //v0.4.7 country: function (path, params) { var endpoints = "/locations/country/" + path; return DeApi.get(endpoints, params); },//v0.5.1 update: function (id, data, language, remove_data, add_data) { var endpoints = "/locations/data/" + id; var putData = { "data": data }; if (language !== undefined && language != "english") { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); } } }); // v0.4.8 de.factory('DeCollectors', function (DeApi) { return { data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/collector/data/" + id; return DeApi.get(endpoints, params); }, create: function (data, estate_id) { var endpoints = "/collector/data/"; var postData = { "data": data } if (estate_id !== undefined) { postData.estate_id = estate_id; } return DeApi.post(endpoints, postData); }, update: function (id, data, language, remove_data, add_data) { var endpoints = "/collector/data/" + id; var putData = { "data": data }; if (language !== undefined && language != "english") { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); } } }); // v0.2.4: Multimedia Merge de.factory('DeMultimedia', function (DeApi, $http) { var multimedia = []; return { data: function (estate, params) { if (estate == undefined) { estate = ""; } var endpoints = "/multimedia/" + estate; return DeApi.get(endpoints, params); }, update: function (estate, data, remove_data, add_data) { var endpoints = "/multimedia/" + estate; var putData = { "data": data }; if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, upload: function (estate, file, uploadEventHandlers, meta) { //Construct file. var endpoints = "/multimedia/" + estate; var fd = new FormData(); fd.append("file", file, file.name); fd.append("estate", estate); //v0.3.3 if (meta !== undefined) { for (var m in meta) { fd.append(m, meta[m]); } } var rh = { "Content-Type": undefined }; if (DeApi.authType == "api-key") { rh["API-KEY"] = DeApi.apiKey } else if (DeApi.authType == "token") { rh["Authorization"] = "Bearer " + DeApi.oauthData.token; } var httpRequest = { url: DeApi.apiUrl + endpoints, method: "POST", data: fd, headers: rh, transformRequest: function (data, header) { return data; } }; if (uploadEventHandlers !== undefined && uploadEventHandlers != "") { httpRequest.uploadEventHandlers = uploadEventHandlers; } return $http(httpRequest); }, remove: function (estate, id) { var endpoints = "/multimedia/" + estate + "/" + id; return DeApi.delete(endpoints); }, loadLast: function () { //TODO: Use Promise return multimedia; } } }); // v0.5.5: Signups de.factory('DeSignups', function(DeApi) { return { data: function(id, params = {}) { if (id==undefined) { id=""; } var endpoint="/signups/data/"+id; return DeApi.get(endpoint, params); }, update: function(id, data) { var endpoint="/signups/data/"+id; return DeApi.put(endpoint, data); }, create: function(data) { var endpoint="/signups/data/"; return DeApi.post(endpoint, data); }, commit: function(id) { var endpoint="/signups/commit/"; var data={ "id":id } return DeApi.post(endpoint, data); }, checkEmail: function(address) { var endpoint="/signups/email/"; var data={ "email":address }; return DeApi.get(endpoint, data); } } }); // v0.1.2: HELPER de.factory('DeHelper', function () { function removeEmpty(jsonOriginal) { if (jsonOriginal === undefined) { return null; } else { var jsonData = JSON.parse(JSON.stringify(jsonOriginal)); if (!isEmpty(jsonData)) { switch (getType(jsonData)) { case "Array": for (var k in jsonData) { if (isEmpty(jsonData[k], true)) { jsonData = jsonData.splice(k, 1); } else { jsonData[k] = removeEmpty(jsonData[k]); if (jsonData[k] == undefined || jsonData[k] === null) { jsonData.splice(k, 1); } } } break; case "Object": for (var k in jsonData) { if (isEmpty(jsonData[k], true)) { delete jsonData[k]; } else { jsonData[k] = removeEmpty(jsonData[k]); if (jsonData[k] == undefined || jsonData[k] === null) { delete jsonData[k]; } } } break; } if (isEmpty(jsonData)) { return null; } else { return jsonData; } } else { return null; } } } function isEmpty(jsonObj, testString) { var empty = false; if (typeof testString == 'undefined') { testString = true; } else { testString = false; } switch (getType(jsonObj)) { case "Array": if (jsonObj.length <= 0) { empty = true; } else { empty = true; for (var a in jsonObj) { if (!isEmpty(jsonObj[a])) { empty = false; } } } break; case "Object": if (Object.keys(jsonObj).length <= 0) { empty = true; } break; case "String": if (testString && jsonObj == "") { empty = true; } break; default: if (typeof jsonObj == 'undefined') { empty = true; } break; } return empty; } function getType(data) { var typeString = Object.prototype.toString.call(data); if (typeString !== undefined) { return typeString.replace("[object ", "").replace("]", ""); } else { return "undefined"; } } //Model editor function addItem(childScope, fieldKey, atStart, defaultItem) { var newObj = {}; if (defaultItem !== undefined) { newObj = defaultItem; } if (fieldKey !== undefined && fieldKey !== "") { if (!childScope.hasOwnProperty(fieldKey)) { childScope[fieldKey] = []; } if (atStart == true) { childScope[fieldKey].unshift(newObj); } else { childScope[fieldKey].push(newObj); } } else { if (atStart == true) { childScope.unshift(newObj); } else { childScope.push(newObj); } } } function copyItem(childScope, itemIndex, objectScope) { var newObject = angular.copy(objectScope); if (newObject.hasOwnProperty("id")) { newObject.id = newObject.id + "-copy"; } if (typeof itemIndex === 'undefined' || itemIndex == "null") { childScope.splice(0, 0, newObject); } else { childScope.splice(itemIndex, 0, newObject); } } function removeItem(childScope, itemIndex, fieldKey) { if (typeof itemIndex === 'undefined' || itemIndex == "null") { if (fieldKey !== undefined) { childScope[fieldKey].splice(0); } else { childScope.splice(0); } } else { if (fieldKey !== undefined) { childScope[fieldKey].splice(itemIndex, 1); } else { childScope.splice(itemIndex, 1); } } } function addObject(childScope, fieldKey, itemType, objectId) { if (objectId == undefined) { var idPrefix = (fieldKey == undefined) ? "temp" : fieldKey; objectId = getTempId(fieldKey); } if (fieldKey !== undefined) { if (!childScope.hasOwnProperty(fieldKey)) { childScope[fieldKey] = {}; } while (childScope[fieldKey].hasOwnProperty(objectId)) { objectId = getTempId(idPrefix); } if (itemType == "Array") { childScope[fieldKey][objectId] = []; } else { childScope[fieldKey][objectId] = {}; } } else { while (childScope.hasOwnProperty(objectId)) { objectId = getTempId(idPrefix); } if (itemType == "Array") { childScope[objectId] = []; } else { childScope[objectId] = {}; } } } return { inArray: function (item, array, compare_key) { if (array == undefined) { return false; } else { if (Array.isArray(item)) { for (var i in array) { for (var j in item) { if (item[j] == array[i]) { return true; } } } } else if (typeof item == "object") { //var same=false; for (var i in array) { if (angular.equals(array[i], item)) { return true; } } return false; } else { if (compare_key !== undefined) { for (var i in array) { if (array[i][compare_key] == item) { return true; } } } return (array.indexOf(item) >= 0); } } }, getQueryParameter: function (str) { var locationSearch = document.location.search.replace(/(^\?)/, ''); if (locationSearch == "") { return {}; } var queryDoc = locationSearch.split("&").map(function (n) { return n = n.split("="), this[n[0]] = n[1], this }.bind({}))[0]; if (str === undefined) { return queryDoc; } else { return queryDoc[str]; } }, //v0.2.9 getURLPaths: function (index) { var urlPaths = window.location.pathname.split("/"); urlPaths.shift(); //Remove the front, as it's always "" if (index == -1) { //Get last non empty element var elem = urlPaths.pop(); if (elem == "") { elem = urlPaths.pop(); } return elem; } else if (index !== undefined) { return urlPaths[index]; } else { return urlPaths; } }, getDiff: function (json1, json2, includeDelete) { var changed = {}; var removed = {}; if (getType(json2) == "Array") { changed = []; } if (typeof json2 == 'object' && typeof json1 == 'object' && !angular.equals(json1, json2)) { var newJson = angular.copy(json2); for (var key in newJson) { if (!json1.hasOwnProperty(key) || !angular.equals(json1[key], newJson[key])) { newJson[key] = removeEmpty(newJson[key]); if (newJson[key] !== null) { changed[key] = newJson[key]; } } } if (includeDelete == true) { for (var okey in json1) { if (!newJson.hasOwnProperty(okey) || newJson[okey] == null) { removed[okey] = ""; } } return { "changed": changed, "removed": removed }; } else { return changed; } } else { return changed; } }, isEmpty: isEmpty, model: { //0.2.5 addItem: addItem, copyItem: copyItem, removeItem: removeItem, addObject: addObject } } }); // v0.2.2: Require CATEGORY ICONS de.provider('DeIcons', function () { this.categoryURL = "http://warehouse.dataestate.com.au/DE/categories/"; //Config this.setCategoryURL = function (catURL) { this.categoryURL = catURL; }; this.$get = function () { this.categoryIcon = function (categoryString) { if (categoryString !== undefined) { return this.categoryURL + categoryString + ".svg"; } } return this; } }); //DIRECTIVES /** * deLink: * de-link='' * de-link-action='' (optional) * Used to parse Data Estate Link objects. If object type is api or internal, then * the de-link-action attribute is used to identify what function to call. */ //DE-LINK FORMAT CHANGED! Won't work with md-button de.directive('deLink', function () { return { scope: { deLink: '=?deLink', apiAction: '&?deApiAction', internalAction: '&?deInternalAction', linkOptions: '=?deLinkOptions' }, transclude: 'element', link: function (scope, element, attrs, mdb) { var boundScope = scope.deLink; if (scope.deLink.type !== undefined) { if (scope.deLink.type == "api") { element.on('click', function () { scope.apiAction( { "$elem": element, "endpoints": scope.deLink.endpoints, "params": scope.deLink.params }); }); } else if (scope.deLink.type == "internal") { element.on('click', function () { scope.internalAction( { "$elem": element, "link": scope.deLink.link }); }); } else { if (scope.linkOptions !== undefined) { if (scope.linkOptions.targets !== undefined) { for (var typeKey in scope.linkOptions.targets) { if (typeKey == scope.deLink.type) { element.attr("target", scope.linkOptions.targets[typeKey]); } } } } element.attr("href", scope.deLink.link); } } } } }); de.directive('deJson', function ($parse) { return { restrict: 'A', scope: { jsonValue: "=deJson" }, link: function (scope, element, attrs) { if (scope.jsonValue !== undefined) { var jsonText = JSON.stringify(scope.jsonValue); element.text(jsonText); } element.on('change', function (ev) { scope.$apply(function () { try { scope.jsonValue = JSON.parse(ev.currentTarget.value); } catch (e) { alert(ev.currentTarget.value + " is not a valid JSON string. Changes not saved."); } }); }); } } }); de.directive('deDateModel', function () { return { restrict: 'A', scope: { dateObj: "=deDateModel" }, link: function (scope, element, attrs) { if (scope.dateObj !== undefined) { if (typeof scope.dateObj == "string") { var dateString = scope.dateObj.split("+")[0]; element.val(dateString); } else { var jsString = scope.dateObj.toISOString().split("Z")[0]; element.val(jsString); } } element.on('change', function (ev) { scope.$apply(function () { if (element.val() != "") { scope.dateObj = element.val(); } }) }); } } }); de.directive('ngEnter', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if (event.which === 13) { scope.$apply(function () { scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; }); de.directive('deAnimateEnd', function ($animate) { return { scope: { deAnimateEnd: '&' }, link: function (scope, element, attr) { $animate.on('leave', element, function () { scope.deAnimateEnd({ '$scope': scope, '$element': element }); }); } } }); //v0.2.8 Immitation of angular-material tooltip de.directive('deTooltip', function ($document) { return { link: function (scope, element, attrs) { var parentElem = element.parent(); var styles = [ "position:absolute", "z-index:100000" ]; element.addClass("de-tooltip"); var styleString = styles.join(";"); element.parent().on('mouseover', function (e) { element.attr("style", styleString); element.appendTo(parentElem.parent()); }); element.parent().on('mouseout', function () { element.remove(); }); element.remove(); } } }); //v0.4.6 - require dataEstateUI.css de.directive('deImgCredit', function () { return { restrict: 'A', scope: { creditText: '=?deImgCredit', customClass: '@?deCreditClass' }, link: function (scope, element, attrs) { if (scope.creditText !== undefined && scope.creditText != "") { var styleClass = ''; styleClass = scope.customClass ? ' ' + scope.customClass : ''; var creditHtml = '<div class="de-img-credit' + styleClass + '">' + scope.creditText + '</div>'; element.parent().append(creditHtml); } } } }); //v0.4 - Added min length and onSelect function de.directive('jqAutocomplete', function () { return { require: "ngModel", scope: { source: "=jqAutoSource", onCreate: "&?jqOnCreate", onSelect: "&?jqOnSelect", onFocus: "&?jqOnFocus", jqShowfield: "=", minLength: "=jqMinLength" }, link: function (scope, element, attrs, modelCtrl) { element.autocomplete({ minLength: (scope.minLength === undefined || isNaN(scope.minLength)) ? 2 : scope.minLength, source: scope.source, create: function (event, ui) { if (scope.onCreate !== undefined) { scope.onCreate({ '$event': event, 'element': element }); } }, focus: function (event, ui) { event.preventDefault(); element.val(ui.item ? ui.item.label : ""); //scope.onFocus({'$event':event, '$ui':ui}); }, select: function (event, ui) { event.preventDefault(); modelCtrl.$setViewValue(ui.item.value); element.val(ui.item ? ui.item.label : ""); if (attrs.jqShowfield == 'value') { element.val(ui.item ? ui.item.value : ""); } else { element.val(ui.item ? ui.item.label : ""); } if (scope.onSelect !== undefined && typeof scope.onSelect == "function") { scope.onSelect({ '$event': event, '$ui': ui }); } }, change: function (event, ui) { event.preventDefault(); if (ui.item === null) { element.val(""); modelCtrl.$setViewValue(null); } else { modelCtrl.$setViewValue(ui.item.value); } } }) .data("ui-autocomplete")._renderItem = function (ul, item) { var newText = String(item.label).replace( new RegExp(this.term, "ig"), '<span class="ui-autocomplete-highlight">' + this.term + "</span>"); return $('<li class="ui-menu-item"></li>') .data("item.autocomplete", item) .append('<div class="ui-menu-item-wrapper">' + newText + '</div>') .appendTo(ul); } } } }); //v0.3.4 de.directive('deCurrency', function () { return { restrict: 'E', scope: { money: '=ngModel' }, link: function (scope, elem, attrs) { scope.editing = false; scope.toggleEdit = function (isEditing) { scope.editing = isEditing; } }, template: '<input type="number" ng-model="money" ng-show="editing" ng-blur="toggleEdit(false)"><span ng-bind="money | currency" ng-hide="editing" ng-click="toggleEdit(true)"></span>' } }); //v0.5 /** * Custom built search input container. Requires an <input> with de-search-bar as attribute. * Attributes: * location-label-alias (string) - Title for the location search result. Default is Location * estate-label-alias (string) - Title for the estate search result. Default is Estate * keyword-label-alias (string) - Title for the keyword search result. Default is Keyword * estate-url (string) - The base url to link to the estate detail view. */ de.directive('deSearch', function (DeEstates, DeAssets, DeLocations, $rootScope) { return { scope: { locationLabel: "@?locationLabelAlias", estateLabel: "@?estateLabelAlias", keywordLabel: "@?keywordLabelAlias", estateUrl: "@?estateUrl", showState: "=?" }, transclude: true, controller: ["$scope", "$element", function DeSearchController($scope, $element) { var vm = this; //Init this.$onInit = function () { vm.name = $scope.name; vm.searchText = ""; vm.searchEstateOptions = []; vm.searchLocationOptions = []; vm.searchRegion = false; vm.searchLocality = false; vm.searchState = false; $scope.popupOpen = false; $scope.showLocationSearch = false; $scope.showEstateSearch = false; $scope.showState = $scope.showState === undefined ? true : $scope.showState; var searchEstatePromise = false; var searchLocationPromise = false; //Set defaults vm.locationLabel = $scope.locationLabel !== undefined ? $scope.locationLabel : "Location"; vm.estateLabel = $scope.estateLabel !== undefined ? $scope.estateLabel : "Estate"; vm.keywordLabel = $scope.keywordLabel !== undefined ? $scope.keywordLabel : "Keyword"; vm.estateUrl = $scope.estateUrl !== undefined ? $scope.estateUrl : "/detail/"; } this.$postLink = function () { //Decide which searches are available vm.searchModes = []; vm.searchParams = {}; if ($scope.searchControl.searchModes !== undefined) { vm.searchModes = $scope.searchControl.searchModes.split("|"); } if ($scope.searchControl.defaultFilters !== undefined) { vm.searchParams = $scope.searchControl.defaultFilters; } } //Set the child search bar. vm.setSearchControl = function (searchControl) { $scope.searchControl = searchControl; } vm.searchChanged = function (newSearch, oldSearch) { vm.searchType = ""; //Don't do search if empty or if there has been no changes. Clear everything if (newSearch == "") { vm.searchText = ""; $scope.searchControl.searchText = ""; //Updates the child search bar. vm.searchText = ""; vm.searchLocality = false; vm.searchRegion = false; vm.searchState = false; return; } if (vm.searchText == newSearch) { return; } vm.searchText = newSearch; vm.searchType = vm.keywordLabel; $scope.popupOpen = true; if (vm.searchModes.length <= 0 || vm.searchModes.includes("LOCATION")) { doLocationSearch(); } if (vm.searchModes.length <= 0 || vm.searchModes.includes("ESTATE")) { doEstateSearch(); } //TODO: Search modes. } function doEstateSearch() { //Setup search estates. vm.searchParams.name = vm.searchText; if (vm.searchParams.fields == undefined) { vm.searchParams.fields = "id,name"; } if (vm.searchParams.size == undefined) { vm.searchParams.size = 5; } searchEstatePromise = DeEstates.data(vm.searchParams) .then(function (response) { searchEstatePromise = false; vm.searchEstateOptions = []; for (var i = 0; i < Math.min(5, response.data.length); i++) { vm.searchEstateOptions.push({ label: response.data[i].name, estateId: response.data[i].id }); } $scope.showEstateSearch = true; }, function (error) { }); } function doLocationSearch() { $scope.searchControl.searchLocality = false; $scope.searchControl.searchRegion = false; $scope.searchControl.searchState = false; //Setup search locations. searchLocationPromise = DeLocations.data({ name: vm.searchText, fields: 'id,name,state_code,type', types: 'LOCALITY,REGION,STATE' }, 'data').then(function (response) { searchLocationPromise = false; //cleanup //prioritise results exactly matching the query, then starting with the query, then containing the query anywhere else var compareSearch = response.config.params.name.toLowerCase(); response.data.forEach(function (row) { var compareResult = row.name.toLowerCase(); if (compareResult == compareSearch) { row.priority = 1; } else if (compareResult.substring(0, compareSearch.length) == compareSearch) { row.priority = 2; } else { row.priority = 3; } }); response.data.sort((a, b) => (a.priority > b.priority) ? 1 : ((b.priority > a.priority) ? -1 : 0)); vm.searchLocationOptions = []; var j = 0; for (var i = 0; i < response.data.length && j < 5; i++) { if (!('state_code' in response.data[i])) { continue; } if (response.data[i].type == "STATE") { vm.searchLocationOptions.push({ label: response.data[i].name, state_code: response.data[i].state_code, type: response.data[i].type }); } else if (response.data[i].type == "REGION") { vm.searchLocationOptions.push({ label: response.data[i].name + ' (Region), ' + response.data[i].state_code, region: response.data[i].name, state_code: response.data[i].state_code, type: response.data[i].type }); } else { vm.searchLocationOptions.push({ label: response.data[i].name + ', ' + response.data[i].state_code, locality: response.data[i].name, state_code: response.data[i].state_code, type: response.data[i].type }); } j++; } $scope.showLocationSearch = true; }, function (error) { console.log(error) }); } vm.searchLocationClicked = function (location) { if ($scope.showState != false) { $scope.searchControl.searchText = location.label; //Updates the child search bar. vm.searchText = location.label; } else if (location.type == "REGION") { $scope.searchControl.searchText = location.region; vm.searchText = location.region; } else { $scope.searchControl.searchText = location.locality; vm.searchText = location.locality; } $scope.searchControl.searchLocality = location.locality; $scope.searchControl.searchState = location.state_code; $scope.searchControl.searchRegion = location.region; $scope.searchControl.searchUpdated(); vm.searchLocality = location.locality; vm.searchState = location.state_code; vm.searchRegion = location.region; vm.searchType = vm.locationLabel.toLowerCase(); $scope.showEstateSearch = false; $scope.showLocationSearch = false; } vm.searchKeywordClicked = function () { $scope.searchControl.searchLocality = false; $scope.searchControl.searchState = false; $scope.searchControl.searchRegion = false; $scope.searchControl.searchUpdated(); vm.searchLocality = false; vm.searchState = false; vm.searchRegion = false; vm.searchType = vm.keywordLabel.toLowerCase(); $scope.showEstateSearch = false; $scope.showLocationSearch = false; } }], controllerAs: 'sc', link: function (scope, element, attr, ownCtrl) { //Track windows click for clickout close event. var winClickEventConstant = "windowsClicked"; window.onclick = function (ev) { $rootScope.$broadcast(winClickEventConstant); } scope.$on(winClickEventConstant, function (ev, data) { if (data) { if (data.$id != ev.currentScope.$id && ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; //No need to $apply, as previous event would've fired it off. if (ev.currentScope.searchControl !== undefined && ev.currentScope.searchControl.onClose !== undefined) { var searchScope = { "keyword": ev.currentScope.searchControl.searchText, "locality": ev.currentScope.searchControl.searchLocality, "region": ev.currentScope.searchControl.searchRegion, "state_code": ev.currentScope.searchControl.searchState }; ev.currentScope.searchControl.onClose({ "$searchScope": searchScope }); } } } else { scope.$apply(function () { if (ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; if (ev.currentScope.searchControl !== undefined && ev.currentScope.searchControl.onClose !== undefined) { var searchScope = { "keyword": ev.currentScope.searchControl.searchText, "locality": ev.currentScope.searchControl.searchLocality, "region": ev.currentScope.searchControl.searchRegion, "state_code": ev.currentScope.searchControl.searchState }; ev.currentScope.searchControl.onClose({ "$searchScope": searchScope }); } } }); } }); }, template: '<div ng-transclude></div><span class="searchinput-type">{{sc.searchType}}</span>' + '<div class="searchinput-dropdown" ng-show="popupOpen">' + '<div class="keyword-search" ng-click="sc.searchKeywordClicked()"><h4>{{sc.keywordLabel}}: </h4><span class="search-term">{{sc.searchText}}</span></div>' + '<div ng-if="showLocationSearch"><h4>{{sc.locationLabel}}</h4>' + '<ul><li ng-repeat="searchOption in sc.searchLocationOptions track by $index" ng-click="sc.searchLocationClicked(searchOption)">' + '<span>{{searchOption.label}}</span>' + '</li></ul>' + '</div>' + '<div ng-if="showEstateSearch"><h4>{{sc.estateLabel}}</h4>' + '<ul><li ng-repeat="searchOption in sc.searchEstateOptions track by $index">' + '<span><a ng-href="{{sc.estateUrl + searchOption.estateId}}">{{searchOption.label}}</a></span>' + '</li></ul>' + '</div>' + '</div>' } }) /** * Custom built search input that will search the Data Estate API. This requires the DE API services. Used as an attribute on INPUT * This requires the parent "de-search" container. * search-types (| separated string) - Indicates what search types to enable. * - KEYWORD (default) - No popup, just does a keyword search to the API. * - ESTATE (default) - Brings up a popup list of estates matching the name. * - LOCATION (default) - Brings up a list of locations. * on-submit (function($searchScope)) - Optional. Used for when location is clicked or keyword is clocked. * Returns the $searchScope object, with three properties: keyword, locality and state_code. * on-close (function($searchScope)) - Optional. Similar to the above, but fired when the dropdown closes. * on-clear (function($searchScope)) - Optional. Fired when the search field is cleared, * defaul-filters = param object to be applied onto estate search. */ .directive('deSearchBar', function () { return { restrict: "A", require: "^^?deSearch", scope: { searchModes: "@?", searchText: "=?ngModel", onSubmit: '&?', onClose: '&?', onClear: '&?', defaultFilters: "=?" }, link: function (scope, elem, attr, parentCtrl) { parentCtrl.setSearchControl(scope); scope.$watch('searchText', function (newVal, oldVal, curScope) { if (newVal != oldVal) { parentCtrl.searchChanged(newVal, oldVal); } if (newVal == "" && scope.onClear !== undefined) { scope.onClear({ "$searchScope": { "keyword": "", "region": false, "locality": false, "state_code": false } }); } }, true); scope.searchUpdated = function () { if (scope.onSubmit !== undefined) { var searchScope = { "keyword": scope.searchText, "region": scope.searchRegion, "locality": scope.searchLocality, "state_code": scope.searchState }; scope.onSubmit({ "$searchScope": searchScope }); } } } } }); //v0.5 /** * Creates a custom dropdown menu. Used as an element. * DOM Attributes: * multi (bool | expression) - Indicates whether the selection allows for multiple selection. * label (expression) - Label of the control. It can be a function. * options (array | expression) - The source of the dropdown menu. This needs to be an array. * model (angular scope) - The two-way bound scope for the selected (array or single value), hijects the ng-model. * label-model (angular scope) - Optional, used to contain selected "label" if the selected value is not sufficient. * label-field (string) - Optional. If the options is an array of objects, indicates which property to use to show in the option's label. * value-field (string) - Optional. If the options is an array of objects, indicates which property to use to show in the option's value. Also shows what is returned. * button-text (expression) - Optional. Used for the "Apply" button label. * on-submit (function($searchScope, $event)) - Optional. Used for when the apply button is clicked. Default is closing the menu. * returns the $searchScope object with 2 properties, selectedValue and selectedLabel * on-close (function($searchScope, $event)) - Optional. Similar to on submit, but is fired with the dropdown window is dismissed. */ de.directive('deDropdown', function ($rootScope) { return { restrict: 'E', scope: { multiple: '=multi', label: '=label', options: '=options', model: '=ngModel', labelModel: '=?', labelField: '@?', valueField: '@?', buttonText: '=?buttonLabel', onSubmit: '&?', onClose: '&?' }, link: function (scope, elem, attr) { scope.popupOpen = false; if (scope.buttonText === undefined) { scope.buttonText = "Apply"; } scope.clearButtonText = "Clear"; var winClickEventConstant = "windowsClicked"; window.onclick = function (ev) { $rootScope.$broadcast(winClickEventConstant); } //Bind custom event scope.$on(winClickEventConstant, function (ev, data) { if (data) { if (data.$id != ev.currentScope.$id && ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; //No need to $apply, as previous event would've fired it off. if (ev.currentScope.onClose !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; ev.currentScope.onClose({ "$searchScope": searchScope, "$event": ev }); } } } else { scope.$apply(function () { if (ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; if (ev.currentScope.onClose !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; ev.currentScope.onClose({ "$searchScope": searchScope, "$event": ev }); } } }); } }); //TODO: ADD PARENT ID!!! scope.parentId = attr.id === undefined ? scope.$id : attr.id; //if multi if (scope.model === undefined && scope.multiple) { scope.model = []; } scope.optionClicked = function (optionVal, ev) { if (ev) { ev.stopPropagation(); } //For multi var checkedItem = optionVal; if (scope.valueField !== undefined) { checkedItem = optionVal[scope.valueField]; } var itemIndex = -1; if (scope.multiple) { var itemIndex = scope.model.indexOf(checkedItem); if (itemIndex >= 0) { //has it. scope.model.splice(itemIndex, 1); } else { scope.model.push(checkedItem); } } else { scope.model = checkedItem; scope.popupOpen = false; } //Label Model (if used) if (scope.labelModel !== undefined) { var labelItem = optionVal; if (scope.labelField !== undefined) { labelItem = optionVal[scope.labelField]; } if (scope.multiple) { if (itemIndex >= 0) { //has it. scope.labelModel.splice(itemIndex, 1); } else { scope.labelModel.push(labelItem); } } else { if (scope.labelField !== undefined) { scope.labelModel = optionVal[scope.labelField]; } else { scope.labelModel = labelItem; } } } if (!scope.multiple) { //Not Multiple, send submit message. if (scope.onSubmit !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; scope.onSubmit({ "$searchScope": searchScope, "$event": ev }); } } } scope.toggleDropdown = function (ev, open) { if (ev) { ev.stopPropagation(); $rootScope.$broadcast("windowsClicked", scope); } scope.togglePopup(open); } scope.togglePopup = function (open) { if (open === undefined) { scope.popupOpen = !scope.popupOpen; } else { scope.popupOpen = open; } } scope.itemInArray = function (haystack, needle) { var needleItem = needle; if (scope.valueField !== undefined) { needleItem = needle[scope.valueField]; } if (haystack.indexOf(needleItem) >= 0) { return true; } else { return false; } } scope.inputLabel = function (item) { if (scope.labelField !== undefined) { return item[scope.labelField]; } else { return item; } } scope.submitSelection = function (ev) { if (scope.onSubmit !== undefined) { if (scope.onSubmit !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; scope.onSubmit({ "$searchScope": searchScope, "$event": ev }); } } }; scope.clearSelection = function (ev) { if (ev) { ev.stopPropagation(); } scope.model = []; if (scope.labelModel !== undefined) { scope.labelModel = []; } } scope.noInvoke = function (ev) { ev.stopPropagation(); } }, template: '<div class="de-dropdown {{class}}" ng-click="toggleDropdown($event)">{{label}}</div><div class="de-dropdown-menu" ng-show="popupOpen"><ul class="de-dropdown-menu-list">' + '<li ng-repeat="option in options track by $index">' + '<label for="{{parentId}}-{{$index}}" ng-click="noInvoke($event)">' + '<input type="checkbox" name="{{parentId}}-{{$index}}" ng-checked="itemInArray(model, option)" id="{{parentId}}-{{$index}}" ng-show="multiple"' + ' ng-click="optionClicked(option, $event)">' + '<span>{{ inputLabel(option) }}</span></label>' + '</li></ul><button type="button" class="de-button btn-clear" ng-click="clearSelection($event)" ng-if="multiple">{{ clearButtonText }}</button>' + '<button type="button" class="de-button" ng-click="submitSelection($selectedScope, $event)">{{ buttonText }}</button></div>' } }); //v0.3.7 de.factory('DeChangeRegister', function (DeHelper) { var changeSets = {}; var originals = {}; var newData = {}; var trackedScopes = {}; function startTracking(setName, dataId, trackData) { if (setName !== undefined && dataId !== undefined && trackData !== undefined) { if (originals[setName] === undefined) { originals[setName] = {}; } if (newData[setName] === undefined) { newData[setName] = {}; } originals[setName][dataId] = angular.copy(trackData); newData[setName][dataId] = trackData; return true; } } return { //This will override original data. registerTracking: function (setName, dataId, trackData, trackScope) { if (setName !== undefined && dataId !== undefined && trackData !== undefined) { startTracking(setName, dataId, trackData, trackScope); if (trackScope !== undefined) { if (trackedScopes[setName] === undefined) { trackedScopes[setName] = {}; } trackedScopes[setName][dataId] = trackScope; } } }, commitTracking: function (setName, dataId) { if (setName === undefined) { originals = {}; changeSets = {}; } else { if (newData[setName] !== undefined) { if (dataId !== undefined && newData[setName][dataId] !== undefined) { originals[setName][dataId] = angular.copy(newData[setName][dataId]); if (trackedScopes[setName] !== undefined && trackedScopes[setName][dataId] !== undefined) { if (typeof trackedScopes[setName][dataId].DeChangeReset === 'function') { trackedScopes[setName][dataId].DeChangeReset(); }; } } else { originals[setName] = angular.copy(newData[setName]); if (trackedScopes[setName] !== undefined) { for (var k in trackedScopes[setName]) { if (typeof trackedScopes[setName][k].DeChangeReset === 'function') { trackedScopes[setName][k].DeChangeReset(); }; } } } } if (changeSets[setName] !== undefined && dataId !== undefined) { delete changeSets[setName][dataId]; } } }, resetTracking: startTracking, //Return true if there're changes, false if none. trackChanges: function (setName, dataId, compareData) { if (originals[setName] !== undefined && originals[setName][dataId] !== undefined) { var changes = DeHelper.getDiff(originals[setName][dataId], compareData, true); if (!DeHelper.isEmpty(changes.changed) || !DeHelper.isEmpty(changes.removed)) { //if (!angular.equals(originals[setName][dataId], compareData)) { if (changeSets[setName] === undefined) { changeSets[setName] = {}; } changeSets[setName][dataId] = changes; return true; } else { if (changeSets[setName] !== undefined) { delete changeSets[setName][dataId]; } return false; } } }, getChanges: function (setName, dataId) { if (setName !== undefined) { if (changeSets[setName] !== undefined) { if (dataId === undefined || changeSets[setName][dataId] === undefined) { return changeSets[setName]; } else { return changeSets[setName][dataId]; } } else { return null; } } else { return null; } }, getOriginals: function (setName, dataId) { if (setName !== undefined && originals[setName] !== undefined) { if (dataId !== undefined && originals[setName][dataId] !== undefined) { return originals[setName][dataId]; } else { return originals[setName]; } } else { return originals; } }, hasChanged: function (setName, dataId) { var itHas = true; if (setName !== undefined) { if (changeSet[setName] === undefined) { itHas = false; } else if (dataId !== undefined) { if (changeSet[setName][dataId] === undefined) { itHas = false; } } } else { itHas = false; } return itHas; } } }); //v0.3.7 - TODO: Revisit how "reset is used"; de.directive('deTrackChanges', function (DeChangeRegister) { return { scope: { trackModel: "=deTrackChanges", trackName: "=deTrackName", trackId: "=?deTrackId" }, link: function (scope, elem, attrs) { var trackId = (scope.trackId === undefined) ? scope.$id : scope.trackId; DeChangeRegister.registerTracking(scope.trackName, trackId, scope.trackModel, scope); scope.$watch('trackModel', function (newVal, oldVal) { if (DeChangeRegister.trackChanges(scope.trackName, trackId, newVal)) { elem.addClass("data-changed"); } else { elem.removeClass("data-changed"); } }, true); scope.DeChangeReset = function () { elem.removeClass("data-changed"); } } } }); //v0.3.9 - Tags de.directive('deTagInput', function () { return { scope: { tags: '=ngModel', delimiter: '=?deTagDelimiter', maxLength: '=?deTagMax' }, link: function (scope, elem, attrs) { scope.maxSize = scope.maxLength === undefined ? 5 : intVal(scope.maxLength); var delimit = scope.delimiter === undefined ? "," : scope.delimiter; scope.$watch('tagText', function (newVal, oldVal) { if (newVal !== undefined && newVal[newVal.length - 1] == delimit) { if (scope.tags == undefined) { scope.tags = []; } var insertVal = oldVal.trim().replace(" ", "-"); if (scope.tags.indexOf(insertVal) < 0 && scope.tags.length < scope.maxSize) { scope.tags.push(insertVal); } scope.tagText = ""; } }); scope.canAddTags = function () { if (scope.tags === undefined) { return true; } else if (scope.tags.length < scope.maxSize) { return true; } else { return false; } } scope.deleteTag = function (index) { scope.tags.splice(index, 1); } }, template: '<div class="tags-container">' + '<div class="tags" ng-repeat="tag in tags">' + '<span type="tag-text" ng-bind="tag"></span>' + '<button class="tags-delete material-icons" ng-click="deleteTag($index)">close</button>' + '</div>' + '<div class="tags-input">' + '<input class="tag-text" ng-model="tagText" ng-show="canAddTags()" placeholder="new tag">' + '<span class="tags-message" ng-hide="canAddTags()" ng-cloak>Max. tags ({{maxSize}}) reached!</span>' + '</div>' + '</div>' } }); //FILTERS de.filter('validity', function () { return function (valString) { if (isNaN(valString.charAt(0))) { valString = valString.replace("M", "1 month"); valString = valString.replace("D", "1 day"); valString = valString.replace("Y", "1 year"); } else { valString = valString.replace("M", " months"); valString = valString.replace("D", " days"); valString = valString.replace("Y", " years"); } return valString; } }); de.filter('filterId', function () { return function (deObj, objId, field) { for (var i in deObj) { if (deObj[i].id == objId) { if (field === undefined) { return deObj[i]; } else { return deObj[i][field]; } } } return ""; } }); //v5.0 de.filter('starratings', function () { return function (ratingText) { var oneStar = '<span class="fa fa-star"></span>'; var halfStar = '<span class="fa fa-star-half-empty"></span>'; switch (ratingText) { case "NA": case -1: return '<div class="rating">Not Available</div>'; case "1": case "1.0": case 1: return '<div class="rating">' + oneStar + '</div>'; case "1.5": case 1.5: return '<div class="rating">' + oneStar + halfStar + '</div>'; case "2": case "2.0": case 2: return '<div class="rating">' + oneStar + oneStar + '</div>'; case "2.5": case 2.5: return '<div class="rating">' + oneStar + oneStar + halfStar + '</div>'; case "3": case "3.0": case 3: return '<div class="rating">' + oneStar + oneStar + oneStar + '</div>'; case "3.5": case 3.5: return '<div class="rating">' + oneStar + oneStar + oneStar + halfStar + '</div>'; case "4": case "4.0": case 4: return '<div class="rating">' + oneStar + oneStar + oneStar + oneStar + '</div>'; case "4.5": case 4.5: return '<div class="rating">' + oneStar + oneStar + oneStar + oneStar + halfStar + '</div>'; case "5": case "5.0": case 5: return '<div class="rating">' + oneStar + oneStar + oneStar + oneStar + oneStar + '</div>'; default: return ""; } } });
src/dataEstateModule.js
//Version 0.5.3 searchBar modes, updated "GET" to not decode keyword quotes twice. var de = angular.module("dataEstateModule", []); //CONSTANTS de.constant('VERSION', 0.5); //Main Provider de.provider('DeApi', function () { this.apiUrl = "https://api.dataestate.net/v2"; //Default this.apiKey = ""; this.authType = "api-key"; //Default v0.1.4 this.oauthData = {}; //Configurations. this.setApi = function (api_url) { this.apiUrl = api_url; } this.setApiKey = function (api_key) { this.apiKey = api_key; } //v0.1.4 this.setToken = function (auth_token) { this.oauthData.token = auth_token; } //v0.4.9: added "none" for proxies this.setAuthType = function (auth_type) { var allowedTypes = ["token", "api-key", "none"]; if (allowedTypes.indexOf(auth_type) >= 0) { this.authType = auth_type; } } this.getAuthType = function () { return this.authType; } //RETURN THIS this.$get = function ($http) { //Base requester. this.get = function (endpoints, params) { if (endpoints !== undefined) { var httpReq = { url: this.apiUrl + endpoints, method: "GET" }; if (this.authType == "api-key") { if (params !== undefined && !params.hasOwnProperty("api_key")) { params.api_key = this.apiKey; } } else if (this.authType == "token") { httpReq.headers = { "Authorization": "Bearer " + this.oauthData.token }; } if (params !== undefined && params.keyword !== undefined) { params.keyword = decodeURI(params.keyword); } httpReq.params = params; return $http(httpReq); } } this.put = function (endpoints, data) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; }; return $http({ url: this.apiUrl + endpoints, method: "PUT", data: data, headers: rh }); } } this.post = function (endpoints, data) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; } return $http({ url: this.apiUrl + endpoints, method: "POST", data: data, headers: rh }); } } this.delete = function (endpoints) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; } return $http({ url: this.apiUrl + endpoints, method: "DELETE", headers: rh }); } } //Must follow RFC6902 structure this.patch = function (endpoints, pipeline) { if (endpoints !== undefined) { var rh = {}; if (this.authType == "api-key") { rh["API-KEY"] = this.apiKey } else if (this.authType == "token") { rh["Authorization"] = "Bearer " + this.oauthData.token; } return $http({ url: this.apiUrl + endpoints, method: "PATCH", data: pipeline, headers: rh }); } } return this; } }); //Estate Service de.factory('DeEstates', function (DeApi) { return { data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/estates/data/" + id; return DeApi.get(endpoints, params); }, update: function (id, data, language, remove_data, add_data) { var endpoints = "/estates/data/" + id; var putData = { "data": data }; if (language !== undefined && language != "english") { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, create: function (category_code, data) { var endpoints = "/estates/data/"; var postData = { "data": data } return DeApi.post(endpoints, postData); }, remove: function (id) { var endpoints = "/estates/data/" + id; return DeApi.delete(endpoints); } } }); // v0.1.6: assets added categories as dictionary. de.factory('DeAssets', function (DeApi) { var currentEstate = ""; return { setEstate: function (estate) { currentEstate = estate; }, getEstate: function () { return currentEstate; }, data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/assets/data/" + id; return DeApi.get(endpoints, params); }, articles: function (estate, slug, params = {}) { if (slug == undefined) { slug = ""; } var endpoints = "/assets/articles/" + estate + "/" + slug; return DeApi.get(endpoints, params); }, // v0.1.3 timetable: function (params) { var endpoints = "/assets/timetable/"; return DeApi.get(endpoints, params); }, //v0.1.8 flights: function (params) { var endpoints = "/assets/flights/"; return DeApi.get(endpoints, params); }, update: function (id, data, language, remove_data, add_data) { var endpoints = "/assets/data/" + id; var putData = { "data": data }; if (language !== undefined) { putData.language = language; } if (remove_data !== undefined && remove_data !== null && Object.keys(remove_data).length > 0) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, create: function (estate, type, data) { var endpoints = "/assets/data/"; if (!data.hasOwnProperty("type")) { data.type = type; } if (estate === undefined) { estate = currentEstate; } var postData = { "data": data, "estate_id": estate } return DeApi.post(endpoints, postData); }, remove: function (id) { var endpoints = "/assets/data/" + id; return DeApi.delete(endpoints); }, bulkRemove: function (estate, type, ids) { var endpoints = "/assets/data/" + estate; var bulkPipeline = []; for (var i in ids) { bulkPipeline.push({ "op": "remove", "path": type + "/" + ids[i] }); } return DeApi.patch(endpoints, bulkPipeline); } } }); // v0.3.6 de.factory('DeUsers', function (DeApi, $q) { var currentUser = null; return { data: function (reload) { var d = $q.defer(); var endpoints = "/users/data/"; if (reload == true || currentUser === null) { DeApi.get(endpoints).then( function success(res) { currentUser = res.data; d.resolve(currentUser); }, function error(err) { d.reject(err); }); } else { d.resolve(currentUser); } return d.promise; } } }) // v0.1.2: taxonomy - TODO: Get from API. de.factory('DeTaxonomy', function (DeApi) { var subtypes = [ { "type": "LANDMARK", "description": "Landmark" }, { "type": "EDUCATION", "description": "Educational" }, { "type": "FOODDRINK", "description": "Food and Drink" }, { "type": "MUSICAL", "description": "Musical Performance" }, { "type": "CEREMONY", "description": "Ceremony" }, { "type": "SPORT", "description": "Sports Event" }, { "type": "PERFORMANCE", "description": "Performances" }, { "type": "PARADE", "description": "March and Parade" }, { "type": "CULTURAL", "description": "Cutural" }, { "type": "ACTIVITY", "description": "Activities" }, { "type": "MEDITATION", "description": "Meditation" }, { "type": "PHOTOGRAPHY", "description": "Photography Event" }, { "type": "TALK", "description": "Talks" }, { "type": "FORUM", "description": "Forums" }, { "type": "FOOD", "description": "Food" }, { "type": "DESSERT", "description": "Snacks and Desserts" }, { "type": "DRINK", "description": "Drinks" }, { "type": "SHOP", "description": "Shops" }, { "type": "INFO", "description": "Information" }, { "type": "VOLUNTEER", "description": "Volunteers" }, { "type": "DISPLAY", "description": "Art and Display" }, { "type": "SERVICE", "description": "Services" } ]; var locations = [ { "id": "BNELETTER", "name": "Brisbane Letters", "loc": [ -27.474147, 153.020482 ] }, { "id": "QC", "name": "Queensland Conservatorium", "loc": [ -27.4768193, 153.0208075 ] }, { "id": "LIANA", "name": "Liana Lounge", "loc": [ -27.475902, 153.021213 ] }, { "loc": [ -27.4706487, 153.0170457 ], "id": "GOMA", "name": "GOMA (Gallery of Modern Art)" }, { "id": "CF", "name": "Cultural Forecourt", "loc": [ -27.4739896, 153.0203686 ] }, { "loc": [ -27.4748418, 153.0212796 ], "id": "RB", "name": "Riverbank" }, { "loc": [ -27.476474, 153.021173 ], "name": "Lumbini Garden", "id": "LG" }, { "loc": [ -27.4771943, 153.0217732 ], "id": "NB", "name": "No Boundaries" }, { "loc": [ -27.476186, 153.021666 ], "name": "Rainforest Green", "id": "RG" }, { "id": "CMP", "name": "The South Bank Piazza", "loc": [ -27.4769716, 153.0214888 ] }, { "id": "PAS", "loc": [ -27.474771, 153.0209563 ], "name": "Performing Arts Stage" } ]; var categories = { "ACCOMM": "Accommodation", "APP": "Application", "ATTRACTION": "Attraction", "COMPANY": "Company", "DESTINFO": "Destination Information", "EVENT": "Event", "GROUP": "Group", "HIRE": "Hire", "INFO": "Information Services", "JOURNEY": "Journey", "ORG": "Organisation", "RESTAURANT": "Food and Drink", "TOUR": "Tour", "TRANSPORT": "Transport" }; var social = [ { id: "in", name: "Instagram" }, { id: "fb", name: "Facebook" }, { id: "li", name: "LinkedIn" }, { id: "tw", name: "Twitter" }, { id: "yt", name: "YouTube" } ]; return { subtypes: function () { return subtypes; }, locations: function () { return locations; }, categories: function () { return categories; }, accreditations: function () { var endpoints = "/taxonomy/data/ACCREDITN"; return DeApi.get(endpoints, {}); },//v0.3 social: function () { return social; }, data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/taxonomy/data/" + id; return DeApi.get(endpoints, params); }, //v0.3.8 update: function (id, data, language, remove_data, add_data) { var endpoints = "/taxonomy/data/" + id; var putData = { "data": data }; if (language !== undefined) { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, create: function (type, data) { var endpoints = "/taxonomy/data/"; if (!data.hasOwnProperty("type")) { data.type = type; } var postData = { "data": data } return DeApi.post(endpoints, postData); }, remove: function (id) { var endpoints = "/taxonomy/data/" + id; return DeApi.delete(endpoints); } } }); // v0.4.5 de.factory('DeLocations', function (DeApi) { return { data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/locations/data/" + id; return DeApi.get(endpoints, params); }, //v0.4.7 country: function (path, params) { var endpoints = "/locations/country/" + path; return DeApi.get(endpoints, params); },//v0.5.1 update: function (id, data, language, remove_data, add_data) { var endpoints = "/locations/data/" + id; var putData = { "data": data }; if (language !== undefined && language != "english") { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); } } }); // v0.4.8 de.factory('DeCollectors', function (DeApi) { return { data: function (params, id) { if (id == undefined) { id = ""; } var endpoints = "/collector/data/" + id; return DeApi.get(endpoints, params); }, create: function (data, estate_id) { var endpoints = "/collector/data/"; var postData = { "data": data } if (estate_id !== undefined) { postData.estate_id = estate_id; } return DeApi.post(endpoints, postData); }, update: function (id, data, language, remove_data, add_data) { var endpoints = "/collector/data/" + id; var putData = { "data": data }; if (language !== undefined && language != "english") { putData.language = language; } if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); } } }); // v0.2.4: Multimedia Merge de.factory('DeMultimedia', function (DeApi, $http) { var multimedia = []; return { data: function (estate, params) { if (estate == undefined) { estate = ""; } var endpoints = "/multimedia/" + estate; return DeApi.get(endpoints, params); }, update: function (estate, data, remove_data, add_data) { var endpoints = "/multimedia/" + estate; var putData = { "data": data }; if (remove_data !== undefined && remove_data !== null) { putData.remove = remove_data; } if (add_data !== undefined && add_data !== null) { putData.add = add_data; } return DeApi.put(endpoints, putData); }, upload: function (estate, file, uploadEventHandlers, meta) { //Construct file. var endpoints = "/multimedia/" + estate; var fd = new FormData(); fd.append("file", file, file.name); fd.append("estate", estate); //v0.3.3 if (meta !== undefined) { for (var m in meta) { fd.append(m, meta[m]); } } var rh = { "Content-Type": undefined }; if (DeApi.authType == "api-key") { rh["API-KEY"] = DeApi.apiKey } else if (DeApi.authType == "token") { rh["Authorization"] = "Bearer " + DeApi.oauthData.token; } var httpRequest = { url: DeApi.apiUrl + endpoints, method: "POST", data: fd, headers: rh, transformRequest: function (data, header) { return data; } }; if (uploadEventHandlers !== undefined && uploadEventHandlers != "") { httpRequest.uploadEventHandlers = uploadEventHandlers; } return $http(httpRequest); }, remove: function (estate, id) { var endpoints = "/multimedia/" + estate + "/" + id; return DeApi.delete(endpoints); }, loadLast: function () { //TODO: Use Promise return multimedia; } } }); // v0.1.2: HELPER de.factory('DeHelper', function () { function removeEmpty(jsonOriginal) { if (jsonOriginal === undefined) { return null; } else { var jsonData = JSON.parse(JSON.stringify(jsonOriginal)); if (!isEmpty(jsonData)) { switch (getType(jsonData)) { case "Array": for (var k in jsonData) { if (isEmpty(jsonData[k], true)) { jsonData = jsonData.splice(k, 1); } else { jsonData[k] = removeEmpty(jsonData[k]); if (jsonData[k] == undefined || jsonData[k] === null) { jsonData.splice(k, 1); } } } break; case "Object": for (var k in jsonData) { if (isEmpty(jsonData[k], true)) { delete jsonData[k]; } else { jsonData[k] = removeEmpty(jsonData[k]); if (jsonData[k] == undefined || jsonData[k] === null) { delete jsonData[k]; } } } break; } if (isEmpty(jsonData)) { return null; } else { return jsonData; } } else { return null; } } } function isEmpty(jsonObj, testString) { var empty = false; if (typeof testString == 'undefined') { testString = true; } else { testString = false; } switch (getType(jsonObj)) { case "Array": if (jsonObj.length <= 0) { empty = true; } else { empty = true; for (var a in jsonObj) { if (!isEmpty(jsonObj[a])) { empty = false; } } } break; case "Object": if (Object.keys(jsonObj).length <= 0) { empty = true; } break; case "String": if (testString && jsonObj == "") { empty = true; } break; default: if (typeof jsonObj == 'undefined') { empty = true; } break; } return empty; } function getType(data) { var typeString = Object.prototype.toString.call(data); if (typeString !== undefined) { return typeString.replace("[object ", "").replace("]", ""); } else { return "undefined"; } } //Model editor function addItem(childScope, fieldKey, atStart, defaultItem) { var newObj = {}; if (defaultItem !== undefined) { newObj = defaultItem; } if (fieldKey !== undefined && fieldKey !== "") { if (!childScope.hasOwnProperty(fieldKey)) { childScope[fieldKey] = []; } if (atStart == true) { childScope[fieldKey].unshift(newObj); } else { childScope[fieldKey].push(newObj); } } else { if (atStart == true) { childScope.unshift(newObj); } else { childScope.push(newObj); } } } function copyItem(childScope, itemIndex, objectScope) { var newObject = angular.copy(objectScope); if (newObject.hasOwnProperty("id")) { newObject.id = newObject.id + "-copy"; } if (typeof itemIndex === 'undefined' || itemIndex == "null") { childScope.splice(0, 0, newObject); } else { childScope.splice(itemIndex, 0, newObject); } } function removeItem(childScope, itemIndex, fieldKey) { if (typeof itemIndex === 'undefined' || itemIndex == "null") { if (fieldKey !== undefined) { childScope[fieldKey].splice(0); } else { childScope.splice(0); } } else { if (fieldKey !== undefined) { childScope[fieldKey].splice(itemIndex, 1); } else { childScope.splice(itemIndex, 1); } } } function addObject(childScope, fieldKey, itemType, objectId) { if (objectId == undefined) { var idPrefix = (fieldKey == undefined) ? "temp" : fieldKey; objectId = getTempId(fieldKey); } if (fieldKey !== undefined) { if (!childScope.hasOwnProperty(fieldKey)) { childScope[fieldKey] = {}; } while (childScope[fieldKey].hasOwnProperty(objectId)) { objectId = getTempId(idPrefix); } if (itemType == "Array") { childScope[fieldKey][objectId] = []; } else { childScope[fieldKey][objectId] = {}; } } else { while (childScope.hasOwnProperty(objectId)) { objectId = getTempId(idPrefix); } if (itemType == "Array") { childScope[objectId] = []; } else { childScope[objectId] = {}; } } } return { inArray: function (item, array, compare_key) { if (array == undefined) { return false; } else { if (Array.isArray(item)) { for (var i in array) { for (var j in item) { if (item[j] == array[i]) { return true; } } } } else if (typeof item == "object") { //var same=false; for (var i in array) { if (angular.equals(array[i], item)) { return true; } } return false; } else { if (compare_key !== undefined) { for (var i in array) { if (array[i][compare_key] == item) { return true; } } } return (array.indexOf(item) >= 0); } } }, getQueryParameter: function (str) { var locationSearch = document.location.search.replace(/(^\?)/, ''); if (locationSearch == "") { return {}; } var queryDoc = locationSearch.split("&").map(function (n) { return n = n.split("="), this[n[0]] = n[1], this }.bind({}))[0]; if (str === undefined) { return queryDoc; } else { return queryDoc[str]; } }, //v0.2.9 getURLPaths: function (index) { var urlPaths = window.location.pathname.split("/"); urlPaths.shift(); //Remove the front, as it's always "" if (index == -1) { //Get last non empty element var elem = urlPaths.pop(); if (elem == "") { elem = urlPaths.pop(); } return elem; } else if (index !== undefined) { return urlPaths[index]; } else { return urlPaths; } }, getDiff: function (json1, json2, includeDelete) { var changed = {}; var removed = {}; if (getType(json2) == "Array") { changed = []; } if (typeof json2 == 'object' && typeof json1 == 'object' && !angular.equals(json1, json2)) { var newJson = angular.copy(json2); for (var key in newJson) { if (!json1.hasOwnProperty(key) || !angular.equals(json1[key], newJson[key])) { newJson[key] = removeEmpty(newJson[key]); if (newJson[key] !== null) { changed[key] = newJson[key]; } } } if (includeDelete == true) { for (var okey in json1) { if (!newJson.hasOwnProperty(okey) || newJson[okey] == null) { removed[okey] = ""; } } return { "changed": changed, "removed": removed }; } else { return changed; } } else { return changed; } }, isEmpty: isEmpty, model: { //0.2.5 addItem: addItem, copyItem: copyItem, removeItem: removeItem, addObject: addObject } } }); // v0.2.2: Require CATEGORY ICONS de.provider('DeIcons', function () { this.categoryURL = "http://warehouse.dataestate.com.au/DE/categories/"; //Config this.setCategoryURL = function (catURL) { this.categoryURL = catURL; }; this.$get = function () { this.categoryIcon = function (categoryString) { if (categoryString !== undefined) { return this.categoryURL + categoryString + ".svg"; } } return this; } }); //DIRECTIVES /** * deLink: * de-link='' * de-link-action='' (optional) * Used to parse Data Estate Link objects. If object type is api or internal, then * the de-link-action attribute is used to identify what function to call. */ //DE-LINK FORMAT CHANGED! Won't work with md-button de.directive('deLink', function () { return { scope: { deLink: '=?deLink', apiAction: '&?deApiAction', internalAction: '&?deInternalAction', linkOptions: '=?deLinkOptions' }, transclude: 'element', link: function (scope, element, attrs, mdb) { var boundScope = scope.deLink; if (scope.deLink.type !== undefined) { if (scope.deLink.type == "api") { element.on('click', function () { scope.apiAction( { "$elem": element, "endpoints": scope.deLink.endpoints, "params": scope.deLink.params }); }); } else if (scope.deLink.type == "internal") { element.on('click', function () { scope.internalAction( { "$elem": element, "link": scope.deLink.link }); }); } else { if (scope.linkOptions !== undefined) { if (scope.linkOptions.targets !== undefined) { for (var typeKey in scope.linkOptions.targets) { if (typeKey == scope.deLink.type) { element.attr("target", scope.linkOptions.targets[typeKey]); } } } } element.attr("href", scope.deLink.link); } } } } }); de.directive('deJson', function ($parse) { return { restrict: 'A', scope: { jsonValue: "=deJson" }, link: function (scope, element, attrs) { if (scope.jsonValue !== undefined) { var jsonText = JSON.stringify(scope.jsonValue); element.text(jsonText); } element.on('change', function (ev) { scope.$apply(function () { try { scope.jsonValue = JSON.parse(ev.currentTarget.value); } catch (e) { alert(ev.currentTarget.value + " is not a valid JSON string. Changes not saved."); } }); }); } } }); de.directive('deDateModel', function () { return { restrict: 'A', scope: { dateObj: "=deDateModel" }, link: function (scope, element, attrs) { if (scope.dateObj !== undefined) { if (typeof scope.dateObj == "string") { var dateString = scope.dateObj.split("+")[0]; element.val(dateString); } else { var jsString = scope.dateObj.toISOString().split("Z")[0]; element.val(jsString); } } element.on('change', function (ev) { scope.$apply(function () { if (element.val() != "") { scope.dateObj = element.val(); } }) }); } } }); de.directive('ngEnter', function () { return function (scope, element, attrs) { element.bind("keydown keypress", function (event) { if (event.which === 13) { scope.$apply(function () { scope.$eval(attrs.ngEnter); }); event.preventDefault(); } }); }; }); de.directive('deAnimateEnd', function ($animate) { return { scope: { deAnimateEnd: '&' }, link: function (scope, element, attr) { $animate.on('leave', element, function () { scope.deAnimateEnd({ '$scope': scope, '$element': element }); }); } } }); //v0.2.8 Immitation of angular-material tooltip de.directive('deTooltip', function ($document) { return { link: function (scope, element, attrs) { var parentElem = element.parent(); var styles = [ "position:absolute", "z-index:100000" ]; element.addClass("de-tooltip"); var styleString = styles.join(";"); element.parent().on('mouseover', function (e) { element.attr("style", styleString); element.appendTo(parentElem.parent()); }); element.parent().on('mouseout', function () { element.remove(); }); element.remove(); } } }); //v0.4.6 - require dataEstateUI.css de.directive('deImgCredit', function () { return { restrict: 'A', scope: { creditText: '=?deImgCredit', customClass: '@?deCreditClass' }, link: function (scope, element, attrs) { if (scope.creditText !== undefined && scope.creditText != "") { var styleClass = ''; styleClass = scope.customClass ? ' ' + scope.customClass : ''; var creditHtml = '<div class="de-img-credit' + styleClass + '">' + scope.creditText + '</div>'; element.parent().append(creditHtml); } } } }); //v0.4 - Added min length and onSelect function de.directive('jqAutocomplete', function () { return { require: "ngModel", scope: { source: "=jqAutoSource", onCreate: "&?jqOnCreate", onSelect: "&?jqOnSelect", onFocus: "&?jqOnFocus", jqShowfield: "=", minLength: "=jqMinLength" }, link: function (scope, element, attrs, modelCtrl) { element.autocomplete({ minLength: (scope.minLength === undefined || isNaN(scope.minLength)) ? 2 : scope.minLength, source: scope.source, create: function (event, ui) { if (scope.onCreate !== undefined) { scope.onCreate({ '$event': event, 'element': element }); } }, focus: function (event, ui) { event.preventDefault(); element.val(ui.item ? ui.item.label : ""); //scope.onFocus({'$event':event, '$ui':ui}); }, select: function (event, ui) { event.preventDefault(); modelCtrl.$setViewValue(ui.item.value); element.val(ui.item ? ui.item.label : ""); if (attrs.jqShowfield == 'value') { element.val(ui.item ? ui.item.value : ""); } else { element.val(ui.item ? ui.item.label : ""); } if (scope.onSelect !== undefined && typeof scope.onSelect == "function") { scope.onSelect({ '$event': event, '$ui': ui }); } }, change: function (event, ui) { event.preventDefault(); if (ui.item === null) { element.val(""); modelCtrl.$setViewValue(null); } else { modelCtrl.$setViewValue(ui.item.value); } } }) .data("ui-autocomplete")._renderItem = function (ul, item) { var newText = String(item.label).replace( new RegExp(this.term, "ig"), '<span class="ui-autocomplete-highlight">' + this.term + "</span>"); return $('<li class="ui-menu-item"></li>') .data("item.autocomplete", item) .append('<div class="ui-menu-item-wrapper">' + newText + '</div>') .appendTo(ul); } } } }); //v0.3.4 de.directive('deCurrency', function () { return { restrict: 'E', scope: { money: '=ngModel' }, link: function (scope, elem, attrs) { scope.editing = false; scope.toggleEdit = function (isEditing) { scope.editing = isEditing; } }, template: '<input type="number" ng-model="money" ng-show="editing" ng-blur="toggleEdit(false)"><span ng-bind="money | currency" ng-hide="editing" ng-click="toggleEdit(true)"></span>' } }); //v0.5 /** * Custom built search input container. Requires an <input> with de-search-bar as attribute. * Attributes: * location-label-alias (string) - Title for the location search result. Default is Location * estate-label-alias (string) - Title for the estate search result. Default is Estate * keyword-label-alias (string) - Title for the keyword search result. Default is Keyword * estate-url (string) - The base url to link to the estate detail view. */ de.directive('deSearch', function (DeEstates, DeAssets, DeLocations, $rootScope) { return { scope: { locationLabel: "@?locationLabelAlias", estateLabel: "@?estateLabelAlias", keywordLabel: "@?keywordLabelAlias", estateUrl: "@?estateUrl", showState: "=?" }, transclude: true, controller: ["$scope", "$element", function DeSearchController($scope, $element) { var vm = this; //Init this.$onInit = function () { vm.name = $scope.name; vm.searchText = ""; vm.searchEstateOptions = []; vm.searchLocationOptions = []; vm.searchRegion = false; vm.searchLocality = false; vm.searchState = false; $scope.popupOpen = false; $scope.showLocationSearch = false; $scope.showEstateSearch = false; $scope.showState = $scope.showState === undefined ? true : $scope.showState; var searchEstatePromise = false; var searchLocationPromise = false; //Set defaults vm.locationLabel = $scope.locationLabel !== undefined ? $scope.locationLabel : "Location"; vm.estateLabel = $scope.estateLabel !== undefined ? $scope.estateLabel : "Estate"; vm.keywordLabel = $scope.keywordLabel !== undefined ? $scope.keywordLabel : "Keyword"; vm.estateUrl = $scope.estateUrl !== undefined ? $scope.estateUrl : "/detail/"; } this.$postLink = function () { //Decide which searches are available vm.searchModes = []; vm.searchParams = {}; if ($scope.searchControl.searchModes !== undefined) { vm.searchModes = $scope.searchControl.searchModes.split("|"); } if ($scope.searchControl.defaultFilters !== undefined) { vm.searchParams = $scope.searchControl.defaultFilters; } } //Set the child search bar. vm.setSearchControl = function (searchControl) { $scope.searchControl = searchControl; } vm.searchChanged = function (newSearch, oldSearch) { vm.searchType = ""; //Don't do search if empty or if there has been no changes. Clear everything if (newSearch == "") { vm.searchText = ""; $scope.searchControl.searchText = ""; //Updates the child search bar. vm.searchText = ""; vm.searchLocality = false; vm.searchRegion = false; vm.searchState = false; return; } if (vm.searchText == newSearch) { return; } vm.searchText = newSearch; vm.searchType = vm.keywordLabel; $scope.popupOpen = true; if (vm.searchModes.length <= 0 || vm.searchModes.includes("LOCATION")) { doLocationSearch(); } if (vm.searchModes.length <= 0 || vm.searchModes.includes("ESTATE")) { doEstateSearch(); } //TODO: Search modes. } function doEstateSearch() { //Setup search estates. vm.searchParams.name = vm.searchText; if (vm.searchParams.fields == undefined) { vm.searchParams.fields = "id,name"; } if (vm.searchParams.size == undefined) { vm.searchParams.size = 5; } searchEstatePromise = DeEstates.data(vm.searchParams) .then(function (response) { searchEstatePromise = false; vm.searchEstateOptions = []; for (var i = 0; i < Math.min(5, response.data.length); i++) { vm.searchEstateOptions.push({ label: response.data[i].name, estateId: response.data[i].id }); } $scope.showEstateSearch = true; }, function (error) { }); } function doLocationSearch() { $scope.searchControl.searchLocality = false; $scope.searchControl.searchRegion = false; $scope.searchControl.searchState = false; //Setup search locations. searchLocationPromise = DeLocations.data({ name: vm.searchText, fields: 'id,name,state_code,type', types: 'LOCALITY,REGION,STATE' }, 'data').then(function (response) { searchLocationPromise = false; //cleanup //prioritise results exactly matching the query, then starting with the query, then containing the query anywhere else var compareSearch = response.config.params.name.toLowerCase(); response.data.forEach(function (row) { var compareResult = row.name.toLowerCase(); if (compareResult == compareSearch) { row.priority = 1; } else if (compareResult.substring(0, compareSearch.length) == compareSearch) { row.priority = 2; } else { row.priority = 3; } }); response.data.sort((a, b) => (a.priority > b.priority) ? 1 : ((b.priority > a.priority) ? -1 : 0)); vm.searchLocationOptions = []; var j = 0; for (var i = 0; i < response.data.length && j < 5; i++) { if (!('state_code' in response.data[i])) { continue; } if (response.data[i].type == "STATE") { vm.searchLocationOptions.push({ label: response.data[i].name, state_code: response.data[i].state_code, type: response.data[i].type }); } else if (response.data[i].type == "REGION") { vm.searchLocationOptions.push({ label: response.data[i].name + ' (Region), ' + response.data[i].state_code, region: response.data[i].name, state_code: response.data[i].state_code, type: response.data[i].type }); } else { vm.searchLocationOptions.push({ label: response.data[i].name + ', ' + response.data[i].state_code, locality: response.data[i].name, state_code: response.data[i].state_code, type: response.data[i].type }); } j++; } $scope.showLocationSearch = true; }, function (error) { console.log(error) }); } vm.searchLocationClicked = function (location) { if ($scope.showState != false) { $scope.searchControl.searchText = location.label; //Updates the child search bar. vm.searchText = location.label; } else if (location.type == "REGION") { $scope.searchControl.searchText = location.region; vm.searchText = location.region; } else { $scope.searchControl.searchText = location.locality; vm.searchText = location.locality; } $scope.searchControl.searchLocality = location.locality; $scope.searchControl.searchState = location.state_code; $scope.searchControl.searchRegion = location.region; $scope.searchControl.searchUpdated(); vm.searchLocality = location.locality; vm.searchState = location.state_code; vm.searchRegion = location.region; vm.searchType = vm.locationLabel.toLowerCase(); $scope.showEstateSearch = false; $scope.showLocationSearch = false; } vm.searchKeywordClicked = function () { $scope.searchControl.searchLocality = false; $scope.searchControl.searchState = false; $scope.searchControl.searchRegion = false; $scope.searchControl.searchUpdated(); vm.searchLocality = false; vm.searchState = false; vm.searchRegion = false; vm.searchType = vm.keywordLabel.toLowerCase(); $scope.showEstateSearch = false; $scope.showLocationSearch = false; } }], controllerAs: 'sc', link: function (scope, element, attr, ownCtrl) { //Track windows click for clickout close event. var winClickEventConstant = "windowsClicked"; window.onclick = function (ev) { $rootScope.$broadcast(winClickEventConstant); } scope.$on(winClickEventConstant, function (ev, data) { if (data) { if (data.$id != ev.currentScope.$id && ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; //No need to $apply, as previous event would've fired it off. if (ev.currentScope.searchControl !== undefined && ev.currentScope.searchControl.onClose !== undefined) { var searchScope = { "keyword": ev.currentScope.searchControl.searchText, "locality": ev.currentScope.searchControl.searchLocality, "region": ev.currentScope.searchControl.searchRegion, "state_code": ev.currentScope.searchControl.searchState }; ev.currentScope.searchControl.onClose({ "$searchScope": searchScope }); } } } else { scope.$apply(function () { if (ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; if (ev.currentScope.searchControl !== undefined && ev.currentScope.searchControl.onClose !== undefined) { var searchScope = { "keyword": ev.currentScope.searchControl.searchText, "locality": ev.currentScope.searchControl.searchLocality, "region": ev.currentScope.searchControl.searchRegion, "state_code": ev.currentScope.searchControl.searchState }; ev.currentScope.searchControl.onClose({ "$searchScope": searchScope }); } } }); } }); }, template: '<div ng-transclude></div><span class="searchinput-type">{{sc.searchType}}</span>' + '<div class="searchinput-dropdown" ng-show="popupOpen">' + '<div class="keyword-search" ng-click="sc.searchKeywordClicked()"><h4>{{sc.keywordLabel}}: </h4><span class="search-term">{{sc.searchText}}</span></div>' + '<div ng-if="showLocationSearch"><h4>{{sc.locationLabel}}</h4>' + '<ul><li ng-repeat="searchOption in sc.searchLocationOptions track by $index" ng-click="sc.searchLocationClicked(searchOption)">' + '<span>{{searchOption.label}}</span>' + '</li></ul>' + '</div>' + '<div ng-if="showEstateSearch"><h4>{{sc.estateLabel}}</h4>' + '<ul><li ng-repeat="searchOption in sc.searchEstateOptions track by $index">' + '<span><a ng-href="{{sc.estateUrl + searchOption.estateId}}">{{searchOption.label}}</a></span>' + '</li></ul>' + '</div>' + '</div>' } }) /** * Custom built search input that will search the Data Estate API. This requires the DE API services. Used as an attribute on INPUT * This requires the parent "de-search" container. * search-types (| separated string) - Indicates what search types to enable. * - KEYWORD (default) - No popup, just does a keyword search to the API. * - ESTATE (default) - Brings up a popup list of estates matching the name. * - LOCATION (default) - Brings up a list of locations. * on-submit (function($searchScope)) - Optional. Used for when location is clicked or keyword is clocked. * Returns the $searchScope object, with three properties: keyword, locality and state_code. * on-close (function($searchScope)) - Optional. Similar to the above, but fired when the dropdown closes. * on-clear (function($searchScope)) - Optional. Fired when the search field is cleared, * defaul-filters = param object to be applied onto estate search. */ .directive('deSearchBar', function () { return { restrict: "A", require: "^^?deSearch", scope: { searchModes: "@?", searchText: "=?ngModel", onSubmit: '&?', onClose: '&?', onClear: '&?', defaultFilters: "=?" }, link: function (scope, elem, attr, parentCtrl) { parentCtrl.setSearchControl(scope); scope.$watch('searchText', function (newVal, oldVal, curScope) { if (newVal != oldVal) { parentCtrl.searchChanged(newVal, oldVal); } if (newVal == "" && scope.onClear !== undefined) { scope.onClear({ "$searchScope": { "keyword": "", "region": false, "locality": false, "state_code": false } }); } }, true); scope.searchUpdated = function () { if (scope.onSubmit !== undefined) { var searchScope = { "keyword": scope.searchText, "region": scope.searchRegion, "locality": scope.searchLocality, "state_code": scope.searchState }; scope.onSubmit({ "$searchScope": searchScope }); } } } } }); //v0.5 /** * Creates a custom dropdown menu. Used as an element. * DOM Attributes: * multi (bool | expression) - Indicates whether the selection allows for multiple selection. * label (expression) - Label of the control. It can be a function. * options (array | expression) - The source of the dropdown menu. This needs to be an array. * model (angular scope) - The two-way bound scope for the selected (array or single value), hijects the ng-model. * label-model (angular scope) - Optional, used to contain selected "label" if the selected value is not sufficient. * label-field (string) - Optional. If the options is an array of objects, indicates which property to use to show in the option's label. * value-field (string) - Optional. If the options is an array of objects, indicates which property to use to show in the option's value. Also shows what is returned. * button-text (expression) - Optional. Used for the "Apply" button label. * on-submit (function($searchScope, $event)) - Optional. Used for when the apply button is clicked. Default is closing the menu. * returns the $searchScope object with 2 properties, selectedValue and selectedLabel * on-close (function($searchScope, $event)) - Optional. Similar to on submit, but is fired with the dropdown window is dismissed. */ de.directive('deDropdown', function ($rootScope) { return { restrict: 'E', scope: { multiple: '=multi', label: '=label', options: '=options', model: '=ngModel', labelModel: '=?', labelField: '@?', valueField: '@?', buttonText: '=?buttonLabel', onSubmit: '&?', onClose: '&?' }, link: function (scope, elem, attr) { scope.popupOpen = false; if (scope.buttonText === undefined) { scope.buttonText = "Apply"; } scope.clearButtonText = "Clear"; var winClickEventConstant = "windowsClicked"; window.onclick = function (ev) { $rootScope.$broadcast(winClickEventConstant); } //Bind custom event scope.$on(winClickEventConstant, function (ev, data) { if (data) { if (data.$id != ev.currentScope.$id && ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; //No need to $apply, as previous event would've fired it off. if (ev.currentScope.onClose !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; ev.currentScope.onClose({ "$searchScope": searchScope, "$event": ev }); } } } else { scope.$apply(function () { if (ev.currentScope.popupOpen) { ev.currentScope.popupOpen = false; if (ev.currentScope.onClose !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; ev.currentScope.onClose({ "$searchScope": searchScope, "$event": ev }); } } }); } }); //TODO: ADD PARENT ID!!! scope.parentId = attr.id === undefined ? scope.$id : attr.id; //if multi if (scope.model === undefined && scope.multiple) { scope.model = []; } scope.optionClicked = function (optionVal, ev) { if (ev) { ev.stopPropagation(); } //For multi var checkedItem = optionVal; if (scope.valueField !== undefined) { checkedItem = optionVal[scope.valueField]; } var itemIndex = -1; if (scope.multiple) { var itemIndex = scope.model.indexOf(checkedItem); if (itemIndex >= 0) { //has it. scope.model.splice(itemIndex, 1); } else { scope.model.push(checkedItem); } } else { scope.model = checkedItem; scope.popupOpen = false; } //Label Model (if used) if (scope.labelModel !== undefined) { var labelItem = optionVal; if (scope.labelField !== undefined) { labelItem = optionVal[scope.labelField]; } if (scope.multiple) { if (itemIndex >= 0) { //has it. scope.labelModel.splice(itemIndex, 1); } else { scope.labelModel.push(labelItem); } } else { if (scope.labelField !== undefined) { scope.labelModel = optionVal[scope.labelField]; } else { scope.labelModel = labelItem; } } } if (!scope.multiple) { //Not Multiple, send submit message. if (scope.onSubmit !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; scope.onSubmit({ "$searchScope": searchScope, "$event": ev }); } } } scope.toggleDropdown = function (ev, open) { if (ev) { ev.stopPropagation(); $rootScope.$broadcast("windowsClicked", scope); } scope.togglePopup(open); } scope.togglePopup = function (open) { if (open === undefined) { scope.popupOpen = !scope.popupOpen; } else { scope.popupOpen = open; } } scope.itemInArray = function (haystack, needle) { var needleItem = needle; if (scope.valueField !== undefined) { needleItem = needle[scope.valueField]; } if (haystack.indexOf(needleItem) >= 0) { return true; } else { return false; } } scope.inputLabel = function (item) { if (scope.labelField !== undefined) { return item[scope.labelField]; } else { return item; } } scope.submitSelection = function (ev) { if (scope.onSubmit !== undefined) { if (scope.onSubmit !== undefined) { var searchScope = { "selectedValue": scope.model, "selectedLabel": scope.labelModel }; scope.onSubmit({ "$searchScope": searchScope, "$event": ev }); } } }; scope.clearSelection = function (ev) { if (ev) { ev.stopPropagation(); } scope.model = []; if (scope.labelModel !== undefined) { scope.labelModel = []; } } scope.noInvoke = function (ev) { ev.stopPropagation(); } }, template: '<div class="de-dropdown {{class}}" ng-click="toggleDropdown($event)">{{label}}</div><div class="de-dropdown-menu" ng-show="popupOpen"><ul class="de-dropdown-menu-list">' + '<li ng-repeat="option in options track by $index">' + '<label for="{{parentId}}-{{$index}}" ng-click="noInvoke($event)">' + '<input type="checkbox" name="{{parentId}}-{{$index}}" ng-checked="itemInArray(model, option)" id="{{parentId}}-{{$index}}" ng-show="multiple"' + ' ng-click="optionClicked(option, $event)">' + '<span>{{ inputLabel(option) }}</span></label>' + '</li></ul><button type="button" class="de-button btn-clear" ng-click="clearSelection($event)" ng-if="multiple">{{ clearButtonText }}</button>' + '<button type="button" class="de-button" ng-click="submitSelection($selectedScope, $event)">{{ buttonText }}</button></div>' } }); //v0.3.7 de.factory('DeChangeRegister', function (DeHelper) { var changeSets = {}; var originals = {}; var newData = {}; var trackedScopes = {}; function startTracking(setName, dataId, trackData) { if (setName !== undefined && dataId !== undefined && trackData !== undefined) { if (originals[setName] === undefined) { originals[setName] = {}; } if (newData[setName] === undefined) { newData[setName] = {}; } originals[setName][dataId] = angular.copy(trackData); newData[setName][dataId] = trackData; return true; } } return { //This will override original data. registerTracking: function (setName, dataId, trackData, trackScope) { if (setName !== undefined && dataId !== undefined && trackData !== undefined) { startTracking(setName, dataId, trackData, trackScope); if (trackScope !== undefined) { if (trackedScopes[setName] === undefined) { trackedScopes[setName] = {}; } trackedScopes[setName][dataId] = trackScope; } } }, commitTracking: function (setName, dataId) { if (setName === undefined) { originals = {}; changeSets = {}; } else { if (newData[setName] !== undefined) { if (dataId !== undefined && newData[setName][dataId] !== undefined) { originals[setName][dataId] = angular.copy(newData[setName][dataId]); if (trackedScopes[setName] !== undefined && trackedScopes[setName][dataId] !== undefined) { if (typeof trackedScopes[setName][dataId].DeChangeReset === 'function') { trackedScopes[setName][dataId].DeChangeReset(); }; } } else { originals[setName] = angular.copy(newData[setName]); if (trackedScopes[setName] !== undefined) { for (var k in trackedScopes[setName]) { if (typeof trackedScopes[setName][k].DeChangeReset === 'function') { trackedScopes[setName][k].DeChangeReset(); }; } } } } if (changeSets[setName] !== undefined && dataId !== undefined) { delete changeSets[setName][dataId]; } } }, resetTracking: startTracking, //Return true if there're changes, false if none. trackChanges: function (setName, dataId, compareData) { if (originals[setName] !== undefined && originals[setName][dataId] !== undefined) { var changes = DeHelper.getDiff(originals[setName][dataId], compareData, true); if (!DeHelper.isEmpty(changes.changed) || !DeHelper.isEmpty(changes.removed)) { //if (!angular.equals(originals[setName][dataId], compareData)) { if (changeSets[setName] === undefined) { changeSets[setName] = {}; } changeSets[setName][dataId] = changes; return true; } else { if (changeSets[setName] !== undefined) { delete changeSets[setName][dataId]; } return false; } } }, getChanges: function (setName, dataId) { if (setName !== undefined) { if (changeSets[setName] !== undefined) { if (dataId === undefined || changeSets[setName][dataId] === undefined) { return changeSets[setName]; } else { return changeSets[setName][dataId]; } } else { return null; } } else { return null; } }, getOriginals: function (setName, dataId) { if (setName !== undefined && originals[setName] !== undefined) { if (dataId !== undefined && originals[setName][dataId] !== undefined) { return originals[setName][dataId]; } else { return originals[setName]; } } else { return originals; } }, hasChanged: function (setName, dataId) { var itHas = true; if (setName !== undefined) { if (changeSet[setName] === undefined) { itHas = false; } else if (dataId !== undefined) { if (changeSet[setName][dataId] === undefined) { itHas = false; } } } else { itHas = false; } return itHas; } } }); //v0.3.7 - TODO: Revisit how "reset is used"; de.directive('deTrackChanges', function (DeChangeRegister) { return { scope: { trackModel: "=deTrackChanges", trackName: "=deTrackName", trackId: "=?deTrackId" }, link: function (scope, elem, attrs) { var trackId = (scope.trackId === undefined) ? scope.$id : scope.trackId; DeChangeRegister.registerTracking(scope.trackName, trackId, scope.trackModel, scope); scope.$watch('trackModel', function (newVal, oldVal) { if (DeChangeRegister.trackChanges(scope.trackName, trackId, newVal)) { elem.addClass("data-changed"); } else { elem.removeClass("data-changed"); } }, true); scope.DeChangeReset = function () { elem.removeClass("data-changed"); } } } }); //v0.3.9 - Tags de.directive('deTagInput', function () { return { scope: { tags: '=ngModel', delimiter: '=?deTagDelimiter', maxLength: '=?deTagMax' }, link: function (scope, elem, attrs) { scope.maxSize = scope.maxLength === undefined ? 5 : intVal(scope.maxLength); var delimit = scope.delimiter === undefined ? "," : scope.delimiter; scope.$watch('tagText', function (newVal, oldVal) { if (newVal !== undefined && newVal[newVal.length - 1] == delimit) { if (scope.tags == undefined) { scope.tags = []; } var insertVal = oldVal.trim().replace(" ", "-"); if (scope.tags.indexOf(insertVal) < 0 && scope.tags.length < scope.maxSize) { scope.tags.push(insertVal); } scope.tagText = ""; } }); scope.canAddTags = function () { if (scope.tags === undefined) { return true; } else if (scope.tags.length < scope.maxSize) { return true; } else { return false; } } scope.deleteTag = function (index) { scope.tags.splice(index, 1); } }, template: '<div class="tags-container">' + '<div class="tags" ng-repeat="tag in tags">' + '<span type="tag-text" ng-bind="tag"></span>' + '<button class="tags-delete material-icons" ng-click="deleteTag($index)">close</button>' + '</div>' + '<div class="tags-input">' + '<input class="tag-text" ng-model="tagText" ng-show="canAddTags()" placeholder="new tag">' + '<span class="tags-message" ng-hide="canAddTags()" ng-cloak>Max. tags ({{maxSize}}) reached!</span>' + '</div>' + '</div>' } }); //FILTERS de.filter('validity', function () { return function (valString) { if (isNaN(valString.charAt(0))) { valString = valString.replace("M", "1 month"); valString = valString.replace("D", "1 day"); valString = valString.replace("Y", "1 year"); } else { valString = valString.replace("M", " months"); valString = valString.replace("D", " days"); valString = valString.replace("Y", " years"); } return valString; } }); de.filter('filterId', function () { return function (deObj, objId, field) { for (var i in deObj) { if (deObj[i].id == objId) { if (field === undefined) { return deObj[i]; } else { return deObj[i][field]; } } } return ""; } }); //v5.0 de.filter('starratings', function () { return function (ratingText) { var oneStar = '<span class="fa fa-star"></span>'; var halfStar = '<span class="fa fa-star-half-empty"></span>'; switch (ratingText) { case "NA": case -1: return '<div class="rating">Not Available</div>'; case "1": case "1.0": case 1: return '<div class="rating">' + oneStar + '</div>'; case "1.5": case 1.5: return '<div class="rating">' + oneStar + halfStar + '</div>'; case "2": case "2.0": case 2: return '<div class="rating">' + oneStar + oneStar + '</div>'; case "2.5": case 2.5: return '<div class="rating">' + oneStar + oneStar + halfStar + '</div>'; case "3": case "3.0": case 3: return '<div class="rating">' + oneStar + oneStar + oneStar + '</div>'; case "3.5": case 3.5: return '<div class="rating">' + oneStar + oneStar + oneStar + halfStar + '</div>'; case "4": case "4.0": case 4: return '<div class="rating">' + oneStar + oneStar + oneStar + oneStar + '</div>'; case "4.5": case 4.5: return '<div class="rating">' + oneStar + oneStar + oneStar + oneStar + halfStar + '</div>'; case "5": case "5.0": case 5: return '<div class="rating">' + oneStar + oneStar + oneStar + oneStar + oneStar + '</div>'; default: return ""; } } });
add support for Signups endpoint
src/dataEstateModule.js
add support for Signups endpoint
<ide><path>rc/dataEstateModule.js <del>//Version 0.5.3 searchBar modes, updated "GET" to not decode keyword quotes twice. <add>//Version 0.5.5 added support for Signups endpoint <ide> var de = angular.module("dataEstateModule", []); <ide> //CONSTANTS <ide> de.constant('VERSION', 0.5); <ide> //TODO: Use Promise <ide> return multimedia; <ide> } <add> } <add>}); <add>// v0.5.5: Signups <add>de.factory('DeSignups', function(DeApi) { <add> return { <add> data: function(id, params = {}) { <add> if (id==undefined) { <add> id=""; <add> } <add> var endpoint="/signups/data/"+id; <add> return DeApi.get(endpoint, params); <add> }, <add> update: function(id, data) { <add> var endpoint="/signups/data/"+id; <add> return DeApi.put(endpoint, data); <add> }, <add> create: function(data) { <add> var endpoint="/signups/data/"; <add> return DeApi.post(endpoint, data); <add> }, <add> commit: function(id) { <add> var endpoint="/signups/commit/"; <add> var data={ <add> "id":id <add> } <add> return DeApi.post(endpoint, data); <add> }, <add> checkEmail: function(address) { <add> var endpoint="/signups/email/"; <add> var data={ <add> "email":address <add> }; <add> return DeApi.get(endpoint, data); <add> } <ide> } <ide> }); <ide> // v0.1.2: HELPER
JavaScript
mit
5def925e0e5c54232d82b4c52ca79269cf717559
0
gil0mendes/stellar
// Enable source map support import 'source-map-support/register' // Enable some ES6 features loading Babel Polyfill import 'babel-polyfill' // Module Dependencies import path from 'path' import async from 'async' import { Utils as UtilsClass } from './satellites/utils' // FIXME: this is a temporary workaround, we must make this more professional const Utils = new UtilsClass() // This stores the number of times that Stellar was started. Every time that // Stellar restarts this is incremented by 1 let startCount = 0 /** * Main Stellar entry point class. * * This makes the system bootstrap, loading and execution all satellites. Each * initializer load new features to the engine instance or perform a set of * instruction to accomplish a certain goal. */ export default class Engine { // --------------------------------------------------------------------------- [STATIC] /** * Default proprieties for the satellites. * * @type {{load: number, start: number, stop: number}} */ static defaultPriorities = { load: 100, start: 100, stop: 100 } /** * Normalize satellite priorities. * * @param satellite Satellite instance to be normalized. */ static normalizeInitializerPriority (satellite) { satellite.loadPriority = satellite.loadPriority || Engine.defaultPriorities.load satellite.startPriority = satellite.startPriority || Engine.defaultPriorities.start satellite.stopPriority = satellite.stopPriority || Engine.defaultPriorities.stop } /** * Order satellites array by their priority. * * @param collection Satellites array to be ordered. * @returns {Array} New ordered array. */ static flattenOrderedInitializer (collection) { let keys = [] let output = [] // get keys from the collection for (var key in collection) { keys.push(parseInt(key)) } // sort the keys in ascendant way keys.sort((a, b) => a - b) // iterate the ordered keys and create the new ordered object to be // outputted keys.forEach(key => collection[ key ].forEach(d => output.push(d))) // return the new ordered object return output } /** * Print fatal error on the console and exit from the engine execution. * * @private * @param api API instance. * @param errors String or array with the fatal error(s). * @param type String with the error type. */ static fatalError (api, errors, type) { // if errors variables if not defined return if (!errors) { return } // ensure the errors variable is an Array if (!Array.isArray(errors)) { errors = [ errors ] } // log an emergency message console.log() api.log(`Error with satellite step: ${type}`, 'emerg') // log all the errors errors.forEach(err => api.log(err, 'emerg')) // finish the process execution api.commands.stop.call(api, () => { process.exit(1) }) } // --------------------------------------------------------------------------- [Class] /** * API object. * * This object will be shared across all the platform, it's here the * satellites will load logic and the developers access the functions. * * @type {{}} */ api = { bootTime: null, status: 'stopped', commands: { initialize: null, start: null, stop: null, restart: null }, _self: null, log: null, scope: {} } /** * List with all satellites. * * @type {{}} */ satellites = {} /** * Array with the initial satellites. * * @type {Array} */ initialSatellites = [] /** * Array with the load satellites. * * This array contains all the satellites who has a load method. * * @type {Array} */ loadSatellites = [] /** * Array with the start satellites. * * This array contains all the satellites who has a start method. * * @type {Array} */ startSatellites = [] /** * Array with the stop satellites. * * This array contains all the satellites who has a stop method. * * @type {Array} */ stopSatellites = [] /** * Create a new instance of the Engine. * * @param scope Initial scope */ constructor (scope) { let self = this // save current execution scope self.api.scope = scope // define args if them are not already defined if (!self.api.scope.args) { self.api.scope.args = {} } // save the engine reference for external calls self.api._self = self // define a dummy logger // // this only should print error, emergency levels self.api.log = (msg, level = 'info') => { // if we are on test environment don't use the console if (process.env.NODE_ENV === 'test') { return } if (level === 'emergency' || level === 'error') { console.log(`\x1b[31m[-] ${msg}\x1b[37m`) } else if (level === 'info') { console.log(`[!] ${msg}`) } } // define the available engine commands self.api.commands = { initialize: self.initialize, start: self.start, stop: self.stop, restart: self.restart } } // --------------------------------------------------------------------------- [State Manager Functions] initialize (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } self.api._self = self // print current execution path self.api.log(`Current universe "${self.api.scope.rootPath}"`, 'info') // execute the stage 0 this.stage0(callback) } /** * Start engine execution. * * @param callback This function is called when the Engine finish their startup. */ start (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } self.api._self = self // reset start counter startCount = 0 // check if the engine was already initialized if (self.api.status !== 'init_stage0') { return self.initialize((error, api) => { // if an error occurs we stop here if (error) { return callback(error, api) } // start stage1 loading method self.stage1(callback) }) } // start stage1 loading method return self.stage1(callback) } /** * Stop the Engine execution. * * This method try shutdown the engine in a non violent way, this * starts to execute all the stop method on the supported satellites. * * @param callback Callback function to be executed at the stop end execution. */ stop (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } if (self.api.status === 'running') { // stop Engine self.api.status = 'shutting_down' // log a shutting down message self.api.log('Shutting down open servers and stopping task processing', 'alert') // if this is the second shutdown we need remove the `finalStopInitializer` callback if (self.stopSatellites[ (self.stopSatellites.length - 1) ].name === 'finalStopInitializer') { self.stopSatellites.pop() } // add the final callback self.stopSatellites.push(function finalStopInitializer (next) { // stop watch for file changes self.api.configs.unwatchAllFiles() // clear cluster PIDs self.api.pids.clearPidFile() // log a shutdown message self.api.log('Stellar has been stopped', 'alert') self.api.log('***', 'debug') // mark server as stopped self.api.status = 'stopped' // execute the callback on the next tick process.nextTick(() => { if (callback !== null) { callback(null, self.api) } }) // async callback next() }) // iterate all satellites and stop them async.series(self.stopSatellites, errors => Engine.fatalError(self.api, errors, 'stop')) } else if (self.api.status === 'shutting_down') { // double sigterm; ignore it } else { // we can shutdown the Engine if it is not running self.api.log('Cannot shutdown Stellar, not running', 'error') // exists a callback? if (callback !== null) { callback(null, self.api) } } } /** * Restart the Stellar Engine. * * This execute a stop action and execute the stage2 load actions. * * @param callback Callback function to be executed at the restart end.s */ restart (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } if (self.api.status === 'running') { // stop the engine self.stop(err => { // log error if present if (err) { self.api.log(err, 'error') } // start the engine again self.stage2(function (err) { if (err) { self.api.log(err, 'error') } // log a restart message self.api.log('*** Stellar Restarted ***', 'info') // exists a callback if (callback !== null) { callback(null, self.api) } }) }) } else { self.stage2(err => { // log any encountered error if (err) { self.api.log(err, 'error') } // log a restart message self.api.log('*** Stellar Restarted ***', 'info') // exists a callback if (callback !== null) { callback(null, self.api) } }) } } // --------------------------------------------------------------------------- [States Functions] /** * First startup stage. * * Steps: * - executes the initial satellites; * - call stage1 * * @param callback This callback only are executed at the end of stage2. */ stage0 (callback = null) { // set the state this.api.status = 'init_stage0' // we need to load the config first let initialSatellites = [ path.resolve(`${__dirname}/satellites/utils.js`), path.resolve(`${__dirname}/satellites/config.js`) ] initialSatellites.forEach(file => { // get full file name let filename = file.replace(/^.*[\\\/]/, '') // get the first part of the file name let initializer = filename.split('.')[ 0 ] // get the initializer const Satellite = require(file).default this.satellites[ initializer ] = new Satellite() // add it to array this.initialSatellites.push(next => this.satellites[ initializer ].load(this.api, next)) }) // execute stage0 satellites in series async.series(this.initialSatellites, error => { // execute the callback callback(error, this.api) // if an error occurs show if (error) { Engine.fatalError(this.api, error, 'stage0') } }) } /** * Second startup stage. * * Steps: * - load all satellites into memory; * - load satellites; * - mark Engine like initialized; * - call stage2. * * @param callback This callback only is executed at the stage2 end. */ stage1 (callback = null) { // put the status in the next stage this.api.status = 'init_stage1' // ranked object for all stages let loadSatellitesRankings = {} let startSatellitesRankings = {} let stopSatellitesRankings = {} // reset satellites arrays this.satellites = {} // function to load the satellites in the right place let loadSatellitesInPlace = satellitesFiles => { // iterate all files for (let key in satellitesFiles) { let f = satellitesFiles[ key ] // get satellite normalized file name and let file = path.normalize(f) let initializer = path.basename(f).split('.')[ 0 ] let ext = file.split('.').pop() // only load files with the `.js` extension if (ext !== 'js') { continue } // get initializer module and instantiate it const Satellite = require(file).default this.satellites[ initializer ] = new Satellite() // initializer load function let loadFunction = next => { // check if the initializer have a load function if (typeof this.satellites[ initializer ].load === 'function') { this.api.log(` > load: ${initializer}`, 'debug') // call `load` property this.satellites[ initializer ].load(this.api, err => { if (!err) { this.api.log(` loaded: ${initializer}`, 'debug') } next(err) }) } else { next() } } // initializer start function let startFunction = next => { // check if the initializer have a start function if (typeof this.satellites[ initializer ].start === 'function') { this.api.log(` > start: ${initializer}`, 'debug') // execute start routine this.satellites[ initializer ].start(this.api, err => { if (!err) { this.api.log(` started: ${initializer}`, 'debug') } next(err) }) } else { next() } } // initializer stop function let stopFunction = next => { if (typeof this.satellites[ initializer ].stop === 'function') { this.api.log(` > stop: ${initializer}`, 'debug') this.satellites[ initializer ].stop(this.api, err => { if (!err) { this.api.log(` stopped: ${initializer}`, 'debug') } next(err) }) } else { next() } } // normalize satellite priorities Engine.normalizeInitializerPriority(this.satellites[ initializer ]) loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ] = loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ] || [] startSatellitesRankings[ this.satellites[ initializer ].startPriority ] = startSatellitesRankings[ this.satellites[ initializer ].startPriority ] || [] stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ] = stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ] || [] // push loader state function to ranked arrays loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ].push(loadFunction) startSatellitesRankings[ this.satellites[ initializer ].startPriority ].push(startFunction) stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ].push(stopFunction) } } // get an array with all satellites loadSatellitesInPlace(Utils.getFiles(`${__dirname}/satellites`)) // load satellites from all the active modules this.api.config.modules.forEach(moduleName => { // build the full path to the satellites folder let moduleSatellitePaths = `${this.api.scope.rootPath}/modules/${moduleName}/satellites` // check if the folder exists if (Utils.directoryExists(moduleSatellitePaths)) { loadSatellitesInPlace(Utils.getFiles(moduleSatellitePaths)) } }) // organize final array to match the satellites priorities this.loadSatellites = Engine.flattenOrderedInitializer(loadSatellitesRankings) this.startSatellites = Engine.flattenOrderedInitializer(startSatellitesRankings) this.stopSatellites = Engine.flattenOrderedInitializer(stopSatellitesRankings) // on the end of loading all satellites set engine like initialized this.loadSatellites.push(() => { this.stage2(callback) }) // start initialization process async.series(this.loadSatellites, errors => Engine.fatalError(this.api, errors, 'stage1')) } /** * Third startup stage. * * Steps: * - start satellites; * - mark Engine as running. * * @param callback */ stage2 (callback = null) { // put the engine in the stage2 state this.api.status = 'init_stage2' if (startCount === 0) { this.startSatellites.push(next => { // set the state this.api.status = 'running' this.api.bootTime = new Date().getTime() if (startCount === 0) { this.api.log('** Server Started @ ' + new Date() + ' ***', 'alert') } else { this.api.log('** Server Restarted @ ' + new Date() + ' ***', 'alert') } // increment the number of starts startCount++ // call the callback if it's present if (callback !== null) { callback(null, this.api) } next() }) } // start all initializers async.series(this.startSatellites, err => Engine.fatalError(this.api, err, 'stage2')) } }
src/engine.js
// Enable source map support import 'source-map-support/register' // Enable some ES6 features loading Babel Polyfill import 'babel-polyfill' // Module Dependencies import path from 'path' import async from 'async' import { Utils as UtilsClass } from './satellites/utils' // FIXME: this is a temporary workaround, we must make this more professional const Utils = new UtilsClass() // This stores the number of times that Stellar was started. Every time that // Stellar restarts this is incremented by 1 let startCount = 0 /** * Main Stellar entry point class. * * This makes the system bootstrap, loading and execution all satellites. Each * initializer load new features to the engine instance or perform a set of * instruction to accomplish a certain goal. */ export default class Engine { // --------------------------------------------------------------------------- [STATIC] /** * Default proprieties for the satellites. * * @type {{load: number, start: number, stop: number}} */ static defaultPriorities = { load: 100, start: 100, stop: 100 } /** * Normalize satellite priorities. * * @param satellite Satellite instance to be normalized. */ static normalizeInitializerPriority (satellite) { satellite.loadPriority = satellite.loadPriority || Engine.defaultPriorities.load satellite.startPriority = satellite.startPriority || Engine.defaultPriorities.start satellite.stopPriority = satellite.stopPriority || Engine.defaultPriorities.stop } /** * Order satellites array by their priority. * * @param collection Satellites array to be ordered. * @returns {Array} New ordered array. */ static flattenOrderedInitializer (collection) { let keys = [] let output = [] // get keys from the collection for (var key in collection) { keys.push(parseInt(key)) } // sort the keys in ascendant way keys.sort((a, b) => a - b) // iterate the ordered keys and create the new ordered object to be // outputted keys.forEach(key => collection[ key ].forEach(d => output.push(d))) // return the new ordered object return output } /** * Print fatal error on the console and exit from the engine execution. * * @private * @param api API instance. * @param errors String or array with the fatal error(s). * @param type String with the error type. */ static fatalError (api, errors, type) { // if errors variables if not defined return if (!errors) { return } // ensure the errors variable is an instance of Array if (!(errors instanceof Array)) { errors = [ errors ] } // log an emergency message api.log(`Error with satellite step: ${type}`, 'emergency') // log all the errors errors.forEach(err => api.log(err, 'emergency')) // finish the process execution process.exit(1) } // --------------------------------------------------------------------------- [Class] /** * API object. * * This object will be shared across all the platform, it's here the * satellites will load logic and the developers access the functions. * * @type {{}} */ api = { bootTime: null, status: 'stopped', commands: { initialize: null, start: null, stop: null, restart: null }, _self: null, log: null, scope: {} } /** * List with all satellites. * * @type {{}} */ satellites = {} /** * Array with the initial satellites. * * @type {Array} */ initialSatellites = [] /** * Array with the load satellites. * * This array contains all the satellites who has a load method. * * @type {Array} */ loadSatellites = [] /** * Array with the start satellites. * * This array contains all the satellites who has a start method. * * @type {Array} */ startSatellites = [] /** * Array with the stop satellites. * * This array contains all the satellites who has a stop method. * * @type {Array} */ stopSatellites = [] /** * Create a new instance of the Engine. * * @param scope Initial scope */ constructor (scope) { let self = this // save current execution scope self.api.scope = scope // define args if them are not already defined if (!self.api.scope.args) { self.api.scope.args = {} } // save the engine reference for external calls self.api._self = self // define a dummy logger // // this only should print error, emergency levels self.api.log = (msg, level = 'info') => { // if we are on test environment don't use the console if (process.env.NODE_ENV === 'test') { return } if (level === 'emergency' || level === 'error') { console.log(`\x1b[31m[-] ${msg}\x1b[37m`) } else if (level === 'info') { console.log(`[!] ${msg}`) } } // define the available engine commands self.api.commands = { initialize: self.initialize, start: self.start, stop: self.stop, restart: self.restart } } // --------------------------------------------------------------------------- [State Manager Functions] initialize (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } self.api._self = self // print current execution path self.api.log(`Current universe "${self.api.scope.rootPath}"`, 'info') // execute the stage 0 this.stage0(callback) } /** * Start engine execution. * * @param callback This function is called when the Engine finish their startup. */ start (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } self.api._self = self // reset start counter startCount = 0 // check if the engine was already initialized if (self.api.status !== 'init_stage0') { return self.initialize((error, api) => { // if an error occurs we stop here if (error) { return callback(error, api) } // start stage1 loading method self.stage1(callback) }) } // start stage1 loading method return self.stage1(callback) } /** * Stop the Engine execution. * * This method try shutdown the engine in a non violent way, this * starts to execute all the stop method on the supported satellites. * * @param callback Callback function to be executed at the stop end execution. */ stop (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } if (self.api.status === 'running') { // stop Engine self.api.status = 'shutting_down' // log a shutting down message self.api.log('Shutting down open servers and stopping task processing', 'alert') // if this is the second shutdown we need remove the `finalStopInitializer` callback if (self.stopSatellites[ (self.stopSatellites.length - 1) ].name === 'finalStopInitializer') { self.stopSatellites.pop() } // add the final callback self.stopSatellites.push(function finalStopInitializer (next) { // stop watch for file changes self.api.configs.unwatchAllFiles() // clear cluster PIDs self.api.pids.clearPidFile() // log a shutdown message self.api.log('Stellar has been stopped', 'alert') self.api.log('***', 'debug') // mark server as stopped self.api.status = 'stopped' // execute the callback on the next tick process.nextTick(() => { if (callback !== null) { callback(null, self.api) } }) // async callback next() }) // iterate all satellites and stop them async.series(self.stopSatellites, errors => Engine.fatalError(self.api, errors, 'stop')) } else if (self.api.status === 'shutting_down') { // double sigterm; ignore it } else { // we can shutdown the Engine if it is not running self.api.log('Cannot shutdown Stellar, not running', 'error') // exists a callback? if (callback !== null) { callback(null, self.api) } } } /** * Restart the Stellar Engine. * * This execute a stop action and execute the stage2 load actions. * * @param callback Callback function to be executed at the restart end.s */ restart (callback = null) { let self = this // if this function has called outside of the Engine the 'this' // variable has an invalid reference if (this._self) { self = this._self } if (self.api.status === 'running') { // stop the engine self.stop(err => { // log error if present if (err) { self.api.log(err, 'error') } // start the engine again self.stage2(function (err) { if (err) { self.api.log(err, 'error') } // log a restart message self.api.log('*** Stellar Restarted ***', 'info') // exists a callback if (callback !== null) { callback(null, self.api) } }) }) } else { self.stage2(err => { // log any encountered error if (err) { self.api.log(err, 'error') } // log a restart message self.api.log('*** Stellar Restarted ***', 'info') // exists a callback if (callback !== null) { callback(null, self.api) } }) } } // --------------------------------------------------------------------------- [States Functions] /** * First startup stage. * * Steps: * - executes the initial satellites; * - call stage1 * * @param callback This callback only are executed at the end of stage2. */ stage0 (callback = null) { // set the state this.api.status = 'init_stage0' // we need to load the config first let initialSatellites = [ path.resolve(`${__dirname}/satellites/utils.js`), path.resolve(`${__dirname}/satellites/config.js`) ] initialSatellites.forEach(file => { // get full file name let filename = file.replace(/^.*[\\\/]/, '') // get the first part of the file name let initializer = filename.split('.')[ 0 ] // get the initializer const Satellite = require(file).default this.satellites[ initializer ] = new Satellite() // add it to array this.initialSatellites.push(next => this.satellites[ initializer ].load(this.api, next)) }) // execute stage0 satellites in series async.series(this.initialSatellites, error => { // execute the callback callback(error, this.api) // if an error occurs show if (error) { Engine.fatalError(this.api, error, 'stage0') } }) } /** * Second startup stage. * * Steps: * - load all satellites into memory; * - load satellites; * - mark Engine like initialized; * - call stage2. * * @param callback This callback only is executed at the stage2 end. */ stage1 (callback = null) { // put the status in the next stage this.api.status = 'init_stage1' // ranked object for all stages let loadSatellitesRankings = {} let startSatellitesRankings = {} let stopSatellitesRankings = {} // reset satellites arrays this.satellites = {} // function to load the satellites in the right place let loadSatellitesInPlace = satellitesFiles => { // iterate all files for (let key in satellitesFiles) { let f = satellitesFiles[ key ] // get satellite normalized file name and let file = path.normalize(f) let initializer = path.basename(f).split('.')[ 0 ] let ext = file.split('.').pop() // only load files with the `.js` extension if (ext !== 'js') { continue } // get initializer module and instantiate it const Satellite = require(file).default this.satellites[ initializer ] = new Satellite() // initializer load function let loadFunction = next => { // check if the initializer have a load function if (typeof this.satellites[ initializer ].load === 'function') { this.api.log(` > load: ${initializer}`, 'debug') // call `load` property this.satellites[ initializer ].load(this.api, err => { this.api.log(` loaded: ${initializer}`, 'debug') next(err) }) } else { next() } } // initializer start function let startFunction = next => { // check if the initializer have a start function if (typeof this.satellites[ initializer ].start === 'function') { this.api.log(` > start: ${initializer}`, 'debug') // execute start routine this.satellites[ initializer ].start(this.api, err => { this.api.log(` started: ${initializer}`, 'debug') next(err) }) } else { next() } } // initializer stop function let stopFunction = next => { if (typeof this.satellites[ initializer ].stop === 'function') { this.api.log(` > stop: ${initializer}`, 'debug') this.satellites[ initializer ].stop(this.api, err => { this.api.log(` stopped: ${initializer}`, 'debug') next(err) }) } else { next() } } // normalize satellite priorities Engine.normalizeInitializerPriority(this.satellites[ initializer ]) loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ] = loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ] || [] startSatellitesRankings[ this.satellites[ initializer ].startPriority ] = startSatellitesRankings[ this.satellites[ initializer ].startPriority ] || [] stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ] = stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ] || [] // push loader state function to ranked arrays loadSatellitesRankings[ this.satellites[ initializer ].loadPriority ].push(loadFunction) startSatellitesRankings[ this.satellites[ initializer ].startPriority ].push(startFunction) stopSatellitesRankings[ this.satellites[ initializer ].stopPriority ].push(stopFunction) } } // get an array with all satellites loadSatellitesInPlace(Utils.getFiles(`${__dirname}/satellites`)) // load satellites from all the active modules this.api.config.modules.forEach(moduleName => { // build the full path to the satellites folder let moduleSatellitePaths = `${this.api.scope.rootPath}/modules/${moduleName}/satellites` // check if the folder exists if (Utils.directoryExists(moduleSatellitePaths)) { loadSatellitesInPlace(Utils.getFiles(moduleSatellitePaths)) } }) // organize final array to match the satellites priorities this.loadSatellites = Engine.flattenOrderedInitializer(loadSatellitesRankings) this.startSatellites = Engine.flattenOrderedInitializer(startSatellitesRankings) this.stopSatellites = Engine.flattenOrderedInitializer(stopSatellitesRankings) // on the end of loading all satellites set engine like initialized this.loadSatellites.push(() => { this.stage2(callback) }) // start initialization process async.series(this.loadSatellites, errors => Engine.fatalError(this.api, errors, 'stage1')) } /** * Third startup stage. * * Steps: * - start satellites; * - mark Engine as running. * * @param callback */ stage2 (callback = null) { // put the engine in the stage2 state this.api.status = 'init_stage2' if (startCount === 0) { this.startSatellites.push(next => { // set the state this.api.status = 'running' this.api.bootTime = new Date().getTime() if (startCount === 0) { this.api.log('** Server Started @ ' + new Date() + ' ***', 'alert') } else { this.api.log('** Server Restarted @ ' + new Date() + ' ***', 'alert') } // increment the number of starts startCount++ // call the callback if it's present if (callback !== null) { callback(null, this.api) } next() }) } // start all initializers async.series(this.startSatellites, err => Engine.fatalError(this.api, err, 'stage2')) } }
Fix an error on the FatalError function
src/engine.js
Fix an error on the FatalError function
<ide><path>rc/engine.js <ide> // if errors variables if not defined return <ide> if (!errors) { return } <ide> <del> // ensure the errors variable is an instance of Array <del> if (!(errors instanceof Array)) { errors = [ errors ] } <add> // ensure the errors variable is an Array <add> if (!Array.isArray(errors)) { errors = [ errors ] } <ide> <ide> // log an emergency message <del> api.log(`Error with satellite step: ${type}`, 'emergency') <add> console.log() <add> api.log(`Error with satellite step: ${type}`, 'emerg') <ide> <ide> // log all the errors <del> errors.forEach(err => api.log(err, 'emergency')) <add> errors.forEach(err => api.log(err, 'emerg')) <ide> <ide> // finish the process execution <del> process.exit(1) <add> api.commands.stop.call(api, () => { process.exit(1) }) <ide> } <ide> <ide> // --------------------------------------------------------------------------- [Class] <ide> <ide> // call `load` property <ide> this.satellites[ initializer ].load(this.api, err => { <del> this.api.log(` loaded: ${initializer}`, 'debug') <add> if (!err) { this.api.log(` loaded: ${initializer}`, 'debug') } <ide> next(err) <ide> }) <ide> } else { <ide> <ide> // execute start routine <ide> this.satellites[ initializer ].start(this.api, err => { <del> this.api.log(` started: ${initializer}`, 'debug') <add> if (!err) { this.api.log(` started: ${initializer}`, 'debug') } <ide> next(err) <ide> }) <ide> } else { <ide> this.api.log(` > stop: ${initializer}`, 'debug') <ide> <ide> this.satellites[ initializer ].stop(this.api, err => { <del> this.api.log(` stopped: ${initializer}`, 'debug') <add> if (!err) { this.api.log(` stopped: ${initializer}`, 'debug') } <ide> next(err) <ide> }) <ide> } else {
Java
apache-2.0
error: pathspec 'core/src/test/java/ma/glasnost/orika/test/extensibility/PooledInstancesTestCase.java' did not match any file(s) known to git
dc9a81994f43c630eaf2b2e58f80d2231d8f46e1
1
leimer/orika,orika-mapper/orika,andreabertagnolli/orika,brabenetz/orika,ellis429/orika,acsl/orika,Log10Solutions/orika
package ma.glasnost.orika.test.extensibility; import java.util.HashMap; import java.util.Map; import ma.glasnost.orika.BoundMapperFacade; import ma.glasnost.orika.MappingContext; import ma.glasnost.orika.impl.DefaultMapperFactory; import ma.glasnost.orika.metadata.Type; import org.junit.Assert; import org.junit.Test; public class PooledInstancesTestCase { public static class MyMapperFactory extends DefaultMapperFactory { public static class Builder extends MapperFactoryBuilder<MyMapperFactory, Builder> { protected Builder self() { return this; } public MyMapperFactory build() { return new MyMapperFactory(this); } } private static class PoolingBoundMapperFacade<A, B> implements BoundMapperFacade<A, B> { private BoundMapperFacade<A, B> wrapped; private Map<String, Pooled> pool; public PoolingBoundMapperFacade(BoundMapperFacade<A, B> wrapped, Map<String, Pooled> pool) { this.wrapped = wrapped; this.pool = pool; } @SuppressWarnings("unchecked") public B map(A instanceA) { return (B) pool.get(((SourcePoolView) instanceA).getName()); } public Type<A> getAType() { return wrapped.getAType(); } public Type<B> getBType() { return wrapped.getBType(); } @SuppressWarnings("unchecked") public B map(A instanceA, MappingContext context) { return (B) pool.get(((SourcePoolView) instanceA).getName()); } public A mapReverse(B instanceB) { return wrapped.mapReverse(instanceB); } public A mapReverse(B instanceB, MappingContext context) { return wrapped.mapReverse(instanceB, context); } public void map(A instanceA, B instanceB) { pool.get(((SourcePoolView) instanceA).getName()); } public void map(A instanceA, B instanceB, MappingContext context) { pool.get(((SourcePoolView) instanceA).getName()); } public void mapReverse(B instanceB, A instanceA) { wrapped.mapReverse(instanceB, instanceA); } public void mapReverse(B instanceB, A instanceA, MappingContext context) { wrapped.mapReverse(instanceB, instanceA, context); } public B newObject(A source, MappingContext context) { return wrapped.newObject(source, context); } public A newObjectReverse(B source, MappingContext context) { return wrapped.newObjectReverse(source, context); } } /** * Since DefaultMapperFactory uses (some form of) the Builder pattern, * we need to provide a constructor which can accept an appropriate * builder and pass it to the super constructor. * * @param builder */ protected MyMapperFactory(Builder builder) { super(builder); pool.put("A", new Pooled("A")); pool.put("B", new Pooled("B")); pool.put("C", new Pooled("C")); } private Map<String, Pooled> pool = new HashMap<String, Pooled>(); public Map<String, Pooled> getPool() { return pool; } public <S, D> BoundMapperFacade<S, D> getMapperFacade( Type<S> sourceType, Type<D> destinationType, boolean containsCycles) { BoundMapperFacade<S, D> ret = super.getMapperFacade(sourceType, destinationType, containsCycles); if (sourceType.getRawType().equals(SourcePoolView.class) && destinationType.getRawType().equals(Pooled.class)) { ret = new PoolingBoundMapperFacade<S, D>(ret, pool); } return ret; } } @Test public void testExtendedMapper() { MyMapperFactory factory = new MyMapperFactory.Builder().build(); factory.registerClassMap(factory .classMap(SourcePoolView.class, Pooled.class).byDefault() .toClassMap()); factory.registerClassMap(factory .classMap(SourceObject.class, DestObject.class).byDefault() .toClassMap()); SourceObject source1 = new SourceObject(); source1.setPooled(new SourcePoolView("A")); DestObject dest1 = factory.getMapperFacade().map(source1, DestObject.class); SourceObject source2 = new SourceObject(); source2.setPooled(new SourcePoolView("A")); DestObject dest2 = factory.getMapperFacade().map(source2, DestObject.class); Assert.assertEquals(dest2.getPooled(), dest1.getPooled()); SourceObject source3 = new SourceObject(); source3.setPooled(new SourcePoolView("A")); DestObject dest3 = new DestObject(); dest3.setPooled(factory.getPool().get("C")); factory.getMapperFacade().map(source3, dest3); Assert.assertEquals(dest3.getPooled(), dest1.getPooled()); } public static class SourcePoolView { private String name; public SourcePoolView(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class SourceObject { private SourcePoolView pooled; public SourcePoolView getPooled() { return pooled; } public void setPooled(SourcePoolView pooled) { this.pooled = pooled; } } public static class Pooled { private String name; public Pooled() { } public Pooled(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static class DestObject { private Pooled pooled; public Pooled getPooled() { return pooled; } public void setPooled(Pooled pooled) { this.pooled = pooled; } } }
core/src/test/java/ma/glasnost/orika/test/extensibility/PooledInstancesTestCase.java
Testcase showing problem with replacement mapping
core/src/test/java/ma/glasnost/orika/test/extensibility/PooledInstancesTestCase.java
Testcase showing problem with replacement mapping
<ide><path>ore/src/test/java/ma/glasnost/orika/test/extensibility/PooledInstancesTestCase.java <add>package ma.glasnost.orika.test.extensibility; <add> <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>import ma.glasnost.orika.BoundMapperFacade; <add>import ma.glasnost.orika.MappingContext; <add>import ma.glasnost.orika.impl.DefaultMapperFactory; <add>import ma.glasnost.orika.metadata.Type; <add> <add>import org.junit.Assert; <add>import org.junit.Test; <add> <add>public class PooledInstancesTestCase { <add> <add> public static class MyMapperFactory extends DefaultMapperFactory { <add> public static class Builder extends <add> MapperFactoryBuilder<MyMapperFactory, Builder> { <add> <add> protected Builder self() { <add> return this; <add> } <add> <add> public MyMapperFactory build() { <add> return new MyMapperFactory(this); <add> } <add> } <add> <add> private static class PoolingBoundMapperFacade<A, B> implements <add> BoundMapperFacade<A, B> { <add> private BoundMapperFacade<A, B> wrapped; <add> private Map<String, Pooled> pool; <add> <add> public PoolingBoundMapperFacade(BoundMapperFacade<A, B> wrapped, <add> Map<String, Pooled> pool) { <add> this.wrapped = wrapped; <add> this.pool = pool; <add> } <add> <add> @SuppressWarnings("unchecked") <add> public B map(A instanceA) { <add> return (B) pool.get(((SourcePoolView) instanceA).getName()); <add> } <add> <add> public Type<A> getAType() { <add> return wrapped.getAType(); <add> } <add> <add> public Type<B> getBType() { <add> return wrapped.getBType(); <add> } <add> <add> @SuppressWarnings("unchecked") <add> public B map(A instanceA, MappingContext context) { <add> return (B) pool.get(((SourcePoolView) instanceA).getName()); <add> } <add> <add> public A mapReverse(B instanceB) { <add> return wrapped.mapReverse(instanceB); <add> } <add> <add> public A mapReverse(B instanceB, MappingContext context) { <add> return wrapped.mapReverse(instanceB, context); <add> } <add> <add> public void map(A instanceA, B instanceB) { <add> pool.get(((SourcePoolView) instanceA).getName()); <add> } <add> <add> public void map(A instanceA, B instanceB, MappingContext context) { <add> pool.get(((SourcePoolView) instanceA).getName()); <add> } <add> <add> public void mapReverse(B instanceB, A instanceA) { <add> wrapped.mapReverse(instanceB, instanceA); <add> } <add> <add> public void mapReverse(B instanceB, A instanceA, <add> MappingContext context) { <add> wrapped.mapReverse(instanceB, instanceA, context); <add> } <add> <add> public B newObject(A source, MappingContext context) { <add> return wrapped.newObject(source, context); <add> } <add> <add> public A newObjectReverse(B source, MappingContext context) { <add> return wrapped.newObjectReverse(source, context); <add> } <add> } <add> <add> /** <add> * Since DefaultMapperFactory uses (some form of) the Builder pattern, <add> * we need to provide a constructor which can accept an appropriate <add> * builder and pass it to the super constructor. <add> * <add> * @param builder <add> */ <add> protected MyMapperFactory(Builder builder) { <add> super(builder); <add> pool.put("A", new Pooled("A")); <add> pool.put("B", new Pooled("B")); <add> pool.put("C", new Pooled("C")); <add> } <add> <add> private Map<String, Pooled> pool = new HashMap<String, Pooled>(); <add> <add> public Map<String, Pooled> getPool() { <add> return pool; <add> } <add> <add> public <S, D> BoundMapperFacade<S, D> getMapperFacade( <add> Type<S> sourceType, Type<D> destinationType, <add> boolean containsCycles) { <add> BoundMapperFacade<S, D> ret = super.getMapperFacade(sourceType, <add> destinationType, containsCycles); <add> if (sourceType.getRawType().equals(SourcePoolView.class) <add> && destinationType.getRawType().equals(Pooled.class)) { <add> ret = new PoolingBoundMapperFacade<S, D>(ret, pool); <add> } <add> return ret; <add> } <add> } <add> <add> @Test <add> public void testExtendedMapper() { <add> MyMapperFactory factory = new MyMapperFactory.Builder().build(); <add> factory.registerClassMap(factory <add> .classMap(SourcePoolView.class, Pooled.class).byDefault() <add> .toClassMap()); <add> factory.registerClassMap(factory <add> .classMap(SourceObject.class, DestObject.class).byDefault() <add> .toClassMap()); <add> <add> SourceObject source1 = new SourceObject(); <add> source1.setPooled(new SourcePoolView("A")); <add> DestObject dest1 = factory.getMapperFacade().map(source1, <add> DestObject.class); <add> <add> SourceObject source2 = new SourceObject(); <add> source2.setPooled(new SourcePoolView("A")); <add> DestObject dest2 = factory.getMapperFacade().map(source2, <add> DestObject.class); <add> Assert.assertEquals(dest2.getPooled(), dest1.getPooled()); <add> <add> SourceObject source3 = new SourceObject(); <add> source3.setPooled(new SourcePoolView("A")); <add> DestObject dest3 = new DestObject(); <add> dest3.setPooled(factory.getPool().get("C")); <add> factory.getMapperFacade().map(source3, dest3); <add> Assert.assertEquals(dest3.getPooled(), dest1.getPooled()); <add> } <add> <add> public static class SourcePoolView { <add> private String name; <add> <add> public SourcePoolView(String name) { <add> this.name = name; <add> } <add> <add> public String getName() { <add> return name; <add> } <add> <add> public void setName(String name) { <add> this.name = name; <add> } <add> } <add> <add> public static class SourceObject { <add> private SourcePoolView pooled; <add> <add> public SourcePoolView getPooled() { <add> return pooled; <add> } <add> <add> public void setPooled(SourcePoolView pooled) { <add> this.pooled = pooled; <add> } <add> } <add> <add> public static class Pooled { <add> private String name; <add> <add> public Pooled() { <add> } <add> <add> public Pooled(String name) { <add> this.name = name; <add> } <add> <add> public String getName() { <add> return name; <add> } <add> <add> public void setName(String name) { <add> this.name = name; <add> } <add> } <add> <add> public static class DestObject { <add> private Pooled pooled; <add> <add> public Pooled getPooled() { <add> return pooled; <add> } <add> <add> public void setPooled(Pooled pooled) { <add> this.pooled = pooled; <add> } <add> } <add>}
JavaScript
mit
3b8967874aac11055d94386e65ab02bbc0ef129d
0
hogashi/twitterOpenOriginalImage,hogashi/twitterOpenOriginalImage,hogashi/twitterOpenOriginalImage
import * as main from '../src/main'; const { isTrue, isFalse, OPTION_KEYS, printException, collectUrlParams, formatUrl, openImages, updateOptions, setStyle, getImageFilenameByUrl, downloadImage, onOriginalButtonClick, getButtonSetter, ButtonSetter, ButtonSetterTweetDeck, } = main; const testParams = { protocol: 'https:', host: 'pbs.twimg.com', basename: 'hogefuga123', pathname: '/media/hogefuga123', }; const makeTestBaseURL = () => { const { protocol, host, pathname } = testParams; return `${protocol}//${host}${pathname}`; }; const makeResultParams = ({ format, name }) => { const { protocol, host, pathname } = testParams; return { protocol, host, pathname, format, name: name || null, }; }; describe('Utils', () => { describe('printException', () => { it('エラーメッセージの表示(予期せぬ状況の確認)', () => { /* eslint-disable no-console */ console.log = jest.fn(); printException('exception message'); expect(console.log.mock.calls[0][0]).toBeInstanceOf(Error); /* eslint-enable no-console */ }); }); describe('URLのツール', () => { // URLの変換のテストの場合たち const cases = [ { title: '何もなし', url: `${makeTestBaseURL()}`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.jpg', url: `${makeTestBaseURL()}.jpg`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.png', url: `${makeTestBaseURL()}.png`, params: { format: 'png' }, filename: `${testParams.basename}.png`, }, { title: '.jpg:orig', url: `${makeTestBaseURL()}.jpg:orig`, params: { format: 'jpg', name: 'orig' }, filename: `${testParams.basename}-orig.jpg`, }, { title: '.jpg:large', url: `${makeTestBaseURL()}.jpg:large`, params: { format: 'jpg', name: 'large' }, filename: `${testParams.basename}-large.jpg`, }, { title: '?format=jpg', url: `${makeTestBaseURL()}?format=jpg`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '?format=png', url: `${makeTestBaseURL()}?format=png`, params: { format: 'png' }, filename: `${testParams.basename}.png`, }, { title: '.jpg?format=jpg', url: `${makeTestBaseURL()}.jpg?format=jpg`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.jpg?format=png', url: `${makeTestBaseURL()}.jpg?format=png`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.png?format=jpg', url: `${makeTestBaseURL()}.png?format=jpg`, params: { format: 'png' }, filename: `${testParams.basename}.png`, }, { title: '.jpg?name=large', url: `${makeTestBaseURL()}.jpg?name=large`, params: { format: 'jpg', name: 'large' }, filename: `${testParams.basename}-large.jpg`, }, { title: '?format=jpg&name=large', url: `${makeTestBaseURL()}?format=jpg&name=large`, params: { format: 'jpg', name: 'large' }, filename: `${testParams.basename}-large.jpg`, }, { title: '.png?format=jpg&name=orig', url: `${makeTestBaseURL()}.png?format=jpg&name=orig`, params: { format: 'png', name: 'orig' }, filename: `${testParams.basename}-orig.png`, }, ]; describe('collectUrlParams 画像urlの要素を集める', () => { cases.forEach(singleCase => { const { title, url, params } = singleCase; it(`${title}`, () => { expect(collectUrlParams(url)).toStrictEqual(makeResultParams(params)); }); }); it('twitterの画像URLでないときnull', () => { expect(collectUrlParams('https://twitter.com/tos')).toBe(null); }); }); describe('formatUrl 画像URLを https~?format=〜&name=orig に揃える', () => { cases.forEach(singleCase => { const { title, url, params } = singleCase; it(`${title}`, () => { expect(formatUrl(url)).toBe( `https://pbs.twimg.com/media/hogefuga123?format=${params.format}&name=orig` ); }); }); it('twitterの画像URLでないときそのまま', () => { expect(formatUrl('https://twitter.com/tos')).toBe( 'https://twitter.com/tos' ); }); it('空文字渡すと null が返る', () => { expect(formatUrl('')).toBeNull(); }); }); describe('getImageFilenameByUrl 画像のファイル名をつくる', () => { cases.forEach(singleCase => { const { title, url, filename } = singleCase; it(`${title}`, () => { expect(getImageFilenameByUrl(url)).toBe(filename); }); }); it('twitterの画像URLでないときnull', () => { expect(getImageFilenameByUrl('https://twitter.com/tos')).toBe(null); }); }); }); describe('openImages 画像を開く', () => { it('画像URLを1つ渡したとき開く', () => { window.open = jest.fn(); openImages(['https://pbs.twimg.com/media/1st?format=jpg&name=orig']); expect(window.open.mock.calls.length).toBe(1); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('画像URLを2つ渡したとき逆順に開く', () => { window.open = jest.fn(); openImages([ 'https://pbs.twimg.com/media/1st?format=jpg&name=orig', 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig', ]); expect(window.open.mock.calls.length).toBe(2); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig' ); expect(window.open.mock.calls[1][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('画像URLを4つ渡したとき逆順に開く', () => { window.open = jest.fn(); openImages([ 'https://pbs.twimg.com/media/1st?format=jpg&name=orig', 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig', 'https://pbs.twimg.com/media/3rd?format=jpg&name=orig', 'https://pbs.twimg.com/media/4th?format=jpg&name=orig', ]); expect(window.open.mock.calls.length).toBe(4); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/4th?format=jpg&name=orig' ); expect(window.open.mock.calls[1][0]).toBe( 'https://pbs.twimg.com/media/3rd?format=jpg&name=orig' ); expect(window.open.mock.calls[2][0]).toBe( 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig' ); expect(window.open.mock.calls[3][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('画像URLでないURLを1つ渡したときもそのまま開く', () => { window.open = jest.fn(); openImages(['https://twitter.com/tos']); expect(window.open.mock.calls.length).toBe(1); expect(window.open.mock.calls[0][0]).toBe('https://twitter.com/tos'); }); it('空文字を1つ渡したとき開かない', () => { window.open = jest.fn(); openImages(['']); expect(window.open.mock.calls.length).toBe(0); }); it('URLとundefinedを混ぜたときURLだけ開いてundefinedは開かない', () => { window.open = jest.fn(); openImages([ 'https://pbs.twimg.com/media/1st?format=jpg&name=orig', '', 'https://twitter.com/tos', 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig', ]); expect(window.open.mock.calls.length).toBe(3); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig' ); expect(window.open.mock.calls[1][0]).toBe('https://twitter.com/tos'); expect(window.open.mock.calls[2][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('要素0個の配列を渡したとき開かない', () => { window.open = jest.fn(); openImages([]); expect(window.open.mock.calls.length).toBe(0); }); }); describe('updateOptions', () => { describe('Chrome拡張機能のとき', () => { const originalChrome = window.chrome; beforeAll(() => { delete window.chrome; window.chrome = { runtime: { id: 'id' } }; }); afterAll(() => { window.chrome = originalChrome; }); it('初期設定を取得できる', async () => { const expected = {}; OPTION_KEYS.forEach(key => { expected[key] = isTrue; }); window.chrome.runtime.sendMessage = jest.fn((_, callback) => callback({ data: {} }) ); await expect(updateOptions()).resolves.toStrictEqual(expected); }); it('設定した値を取得できる', async () => { const expected = {}; OPTION_KEYS.forEach((key, i) => { expected[key] = i % 2 === 0 ? isTrue : isFalse; }); window.chrome.runtime.sendMessage = jest.fn((_, callback) => callback({ data: { ...expected } }) ); await expect(updateOptions()).resolves.toStrictEqual(expected); }); it('設定が取得できなかったら初期設定', async () => { const expected = {}; OPTION_KEYS.forEach(key => { expected[key] = isTrue; }); window.chrome.runtime.sendMessage = jest.fn((_, callback) => callback({}) ); await expect(updateOptions()).resolves.toStrictEqual(expected); }); }); describe('Chrome拡張機能でないとき', () => { const originalChrome = window.chrome; beforeAll(() => { delete window.chrome; window.chrome = undefined; }); afterAll(() => { window.chrome = originalChrome; }); it('初期設定を取得できる', async () => { const expected = {}; OPTION_KEYS.forEach(key => { expected[key] = isTrue; }); await expect(updateOptions()).resolves.toStrictEqual(expected); }); }); }); describe('setStyle DOM要素にスタイルを当てる', () => { it('スタイル当たる', () => { const div = document.createElement('div'); expect(div).toMatchSnapshot(); setStyle(div, { display: 'none', color: '#123', 'background-color': 'rgba(12, 34, 56, 0.7)', }); expect(div).toMatchSnapshot(); }); it('空のスタイル渡すと何もしない', () => { const div = document.createElement('div'); expect(div).toMatchSnapshot(); setStyle(div, {}); expect(div).toMatchSnapshot(); }); it('すでにあるスタイルは上書きされるが消えることはない', () => { const div = document.createElement('div'); div.style.color = '#456'; div.style.backgroundColor = '#789abc'; div.style.fontSize = '150px'; expect(div).toMatchSnapshot(); setStyle(div, { display: 'none', color: '#123', 'background-color': 'rgba(12, 34, 56, 0.7)', }); expect(div).toMatchSnapshot(); }); }); describe('onOriginalButtonClick ボタンがクリックされたときのコールバック', () => { it('イベントを止める', () => { /* SKIP: なぜかうまくmockできないので飛ばす */ // jest.spyOn(main, 'openImages'); const event = { preventDefault: jest.fn(), stopPropagation: jest.fn(), }; const imgSrcs = ['src1', 'src2']; onOriginalButtonClick(event, imgSrcs); expect(event.preventDefault).toHaveBeenCalledTimes(1); expect(event.stopPropagation).toHaveBeenCalledTimes(1); // expect(openImages).toHaveBeenCalledTimes(1); // expect(openImages.mock.calls[0][0]).toStrictEqual(imgSrcs); }); }); describe('downloadImage 画像をダウンロードする', () => { let img; let event = {}; beforeEach(() => { img = document.createElement('img'); img.src = 'https://pbs.twimg.com/media/hogefuga123.jpg'; document.querySelector('body').appendChild(img); event = { preventDefault: jest.fn(), }; }); afterEach(() => { img.parentNode.removeChild(img); }); it('Ctrl-s', () => { event.ctrlKey = true; event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).toHaveBeenCalledTimes(1); }); it('Cmd-s', () => { event.metaKey = true; event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).toHaveBeenCalledTimes(1); }); it('ただのsなら何もしない', () => { event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); it('ただのCtrlなら何もしない', () => { event.ctrlKey = true; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); it('ただのCmdなら何もしない', () => { event.metaKey = true; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); it('imgのsrcがないときCtrl-sしても何もしない', () => { img.src = ''; event.ctrlKey = true; event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); }); describe('getButtonSetter ボタン設置するクラスのゲッタ', () => { const originalLocation = window.location; beforeAll(() => { delete window.location; }); afterAll(() => { window.location = originalLocation; }); it('公式WebではButtonSetter', () => { window.location = new URL('https://twitter.com'); expect(getButtonSetter()).toBeInstanceOf(ButtonSetter); }); it('TweetDeckではButtonSetterTweetDeck', () => { window.location = new URL('https://tweetdeck.twitter.com'); expect(getButtonSetter()).toBeInstanceOf(ButtonSetterTweetDeck); }); it('どちらでもなかったらButtonSetter', () => { window.location = new URL('https://hoge.test'); expect(getButtonSetter()).toBeInstanceOf(ButtonSetter); }); }); });
__tests__/Utils.test.js
import * as main from '../src/main'; const { isTrue, isFalse, OPTION_KEYS, printException, collectUrlParams, formatUrl, openImages, options, updateOptions, setStyle, getImageFilenameByUrl, downloadImage, onOriginalButtonClick, getButtonSetter, ButtonSetter, ButtonSetterTweetDeck, } = main; const testParams = { protocol: 'https:', host: 'pbs.twimg.com', basename: 'hogefuga123', pathname: '/media/hogefuga123', }; const makeTestBaseURL = () => { const { protocol, host, pathname } = testParams; return `${protocol}//${host}${pathname}`; }; const makeResultParams = ({ format, name }) => { const { protocol, host, pathname } = testParams; return { protocol, host, pathname, format, name: name || null, }; }; describe('Utils', () => { describe('printException', () => { it('エラーメッセージの表示(予期せぬ状況の確認)', () => { /* eslint-disable no-console */ console.log = jest.fn(); printException('exception message'); expect(console.log.mock.calls[0][0]).toBeInstanceOf(Error); /* eslint-enable no-console */ }); }); describe('URLのツール', () => { // URLの変換のテストの場合たち const cases = [ { title: '何もなし', url: `${makeTestBaseURL()}`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.jpg', url: `${makeTestBaseURL()}.jpg`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.png', url: `${makeTestBaseURL()}.png`, params: { format: 'png' }, filename: `${testParams.basename}.png`, }, { title: '.jpg:orig', url: `${makeTestBaseURL()}.jpg:orig`, params: { format: 'jpg', name: 'orig' }, filename: `${testParams.basename}-orig.jpg`, }, { title: '.jpg:large', url: `${makeTestBaseURL()}.jpg:large`, params: { format: 'jpg', name: 'large' }, filename: `${testParams.basename}-large.jpg`, }, { title: '?format=jpg', url: `${makeTestBaseURL()}?format=jpg`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '?format=png', url: `${makeTestBaseURL()}?format=png`, params: { format: 'png' }, filename: `${testParams.basename}.png`, }, { title: '.jpg?format=jpg', url: `${makeTestBaseURL()}.jpg?format=jpg`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.jpg?format=png', url: `${makeTestBaseURL()}.jpg?format=png`, params: { format: 'jpg' }, filename: `${testParams.basename}.jpg`, }, { title: '.png?format=jpg', url: `${makeTestBaseURL()}.png?format=jpg`, params: { format: 'png' }, filename: `${testParams.basename}.png`, }, { title: '.jpg?name=large', url: `${makeTestBaseURL()}.jpg?name=large`, params: { format: 'jpg', name: 'large' }, filename: `${testParams.basename}-large.jpg`, }, { title: '?format=jpg&name=large', url: `${makeTestBaseURL()}?format=jpg&name=large`, params: { format: 'jpg', name: 'large' }, filename: `${testParams.basename}-large.jpg`, }, { title: '.png?format=jpg&name=orig', url: `${makeTestBaseURL()}.png?format=jpg&name=orig`, params: { format: 'png', name: 'orig' }, filename: `${testParams.basename}-orig.png`, }, ]; describe('collectUrlParams 画像urlの要素を集める', () => { cases.forEach(singleCase => { const { title, url, params } = singleCase; it(`${title}`, () => { expect(collectUrlParams(url)).toStrictEqual(makeResultParams(params)); }); }); it('twitterの画像URLでないときnull', () => { expect(collectUrlParams('https://twitter.com/tos')).toBe(null); }); }); describe('formatUrl 画像URLを https~?format=〜&name=orig に揃える', () => { cases.forEach(singleCase => { const { title, url, params } = singleCase; it(`${title}`, () => { expect(formatUrl(url)).toBe( `https://pbs.twimg.com/media/hogefuga123?format=${params.format}&name=orig` ); }); }); it('twitterの画像URLでないときそのまま', () => { expect(formatUrl('https://twitter.com/tos')).toBe( 'https://twitter.com/tos' ); }); it('空文字渡すと null が返る', () => { expect(formatUrl('')).toBeNull(); }); }); describe('getImageFilenameByUrl 画像のファイル名をつくる', () => { cases.forEach(singleCase => { const { title, url, filename } = singleCase; it(`${title}`, () => { expect(getImageFilenameByUrl(url)).toBe(filename); }); }); it('twitterの画像URLでないときnull', () => { expect(getImageFilenameByUrl('https://twitter.com/tos')).toBe(null); }); }); }); describe('openImages 画像を開く', () => { it('画像URLを1つ渡したとき開く', () => { window.open = jest.fn(); openImages(['https://pbs.twimg.com/media/1st?format=jpg&name=orig']); expect(window.open.mock.calls.length).toBe(1); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('画像URLを2つ渡したとき逆順に開く', () => { window.open = jest.fn(); openImages([ 'https://pbs.twimg.com/media/1st?format=jpg&name=orig', 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig', ]); expect(window.open.mock.calls.length).toBe(2); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig' ); expect(window.open.mock.calls[1][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('画像URLを4つ渡したとき逆順に開く', () => { window.open = jest.fn(); openImages([ 'https://pbs.twimg.com/media/1st?format=jpg&name=orig', 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig', 'https://pbs.twimg.com/media/3rd?format=jpg&name=orig', 'https://pbs.twimg.com/media/4th?format=jpg&name=orig', ]); expect(window.open.mock.calls.length).toBe(4); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/4th?format=jpg&name=orig' ); expect(window.open.mock.calls[1][0]).toBe( 'https://pbs.twimg.com/media/3rd?format=jpg&name=orig' ); expect(window.open.mock.calls[2][0]).toBe( 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig' ); expect(window.open.mock.calls[3][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('画像URLでないURLを1つ渡したときもそのまま開く', () => { window.open = jest.fn(); openImages(['https://twitter.com/tos']); expect(window.open.mock.calls.length).toBe(1); expect(window.open.mock.calls[0][0]).toBe('https://twitter.com/tos'); }); it('空文字を1つ渡したとき開かない', () => { window.open = jest.fn(); openImages(['']); expect(window.open.mock.calls.length).toBe(0); }); it('URLとundefinedを混ぜたときURLだけ開いてundefinedは開かない', () => { window.open = jest.fn(); openImages([ 'https://pbs.twimg.com/media/1st?format=jpg&name=orig', '', 'https://twitter.com/tos', 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig', ]); expect(window.open.mock.calls.length).toBe(3); expect(window.open.mock.calls[0][0]).toBe( 'https://pbs.twimg.com/media/2nd?format=jpg&name=orig' ); expect(window.open.mock.calls[1][0]).toBe('https://twitter.com/tos'); expect(window.open.mock.calls[2][0]).toBe( 'https://pbs.twimg.com/media/1st?format=jpg&name=orig' ); }); it('要素0個の配列を渡したとき開かない', () => { window.open = jest.fn(); openImages([]); expect(window.open.mock.calls.length).toBe(0); }); }); describe('updateOptions', () => { describe('Chrome拡張機能のとき', () => { const originalChrome = window.chrome; beforeAll(() => { delete window.chrome; window.chrome = { runtime: { id: 'id' } }; }); afterAll(() => { window.chrome = originalChrome; }); it('初期設定を取得できる', async () => { const expected = {}; OPTION_KEYS.forEach(key => { expected[key] = isTrue; }); window.chrome.runtime.sendMessage = jest.fn((_, callback) => callback({ data: {} }) ); await expect(updateOptions()).resolves.toBeUndefined(); expect(options).toStrictEqual(expected); }); it('設定した値を取得できる', async () => { const expected = {}; OPTION_KEYS.forEach((key, i) => { expected[key] = i % 2 === 0 ? isTrue : isFalse; }); window.chrome.runtime.sendMessage = jest.fn((_, callback) => callback({ data: { ...expected } }) ); await expect(updateOptions()).resolves.toBeUndefined(); expect(options).toStrictEqual(expected); }); it('設定が取得できなかったら初期設定', async () => { const expected = {}; OPTION_KEYS.forEach(key => { expected[key] = isTrue; }); window.chrome.runtime.sendMessage = jest.fn((_, callback) => callback({}) ); await expect(updateOptions()).resolves.toBeUndefined(); expect(options).toStrictEqual(expected); }); }); describe('Chrome拡張機能でないとき', () => { const originalChrome = window.chrome; beforeAll(() => { delete window.chrome; window.chrome = undefined; }); afterAll(() => { window.chrome = originalChrome; }); it('初期設定を取得できる', async () => { const expected = {}; OPTION_KEYS.forEach(key => { expected[key] = isTrue; }); await expect(updateOptions()).resolves.toBeUndefined(); expect(options).toStrictEqual(expected); }); }); }); describe('setStyle DOM要素にスタイルを当てる', () => { it('スタイル当たる', () => { const div = document.createElement('div'); expect(div).toMatchSnapshot(); setStyle(div, { display: 'none', color: '#123', 'background-color': 'rgba(12, 34, 56, 0.7)', }); expect(div).toMatchSnapshot(); }); it('空のスタイル渡すと何もしない', () => { const div = document.createElement('div'); expect(div).toMatchSnapshot(); setStyle(div, {}); expect(div).toMatchSnapshot(); }); it('すでにあるスタイルは上書きされるが消えることはない', () => { const div = document.createElement('div'); div.style.color = '#456'; div.style.backgroundColor = '#789abc'; div.style.fontSize = '150px'; expect(div).toMatchSnapshot(); setStyle(div, { display: 'none', color: '#123', 'background-color': 'rgba(12, 34, 56, 0.7)', }); expect(div).toMatchSnapshot(); }); }); describe('onOriginalButtonClick ボタンがクリックされたときのコールバック', () => { it('イベントを止める', () => { /* SKIP: なぜかうまくmockできないので飛ばす */ // jest.spyOn(main, 'openImages'); const event = { preventDefault: jest.fn(), stopPropagation: jest.fn(), }; const imgSrcs = ['src1', 'src2']; onOriginalButtonClick(event, imgSrcs); expect(event.preventDefault).toHaveBeenCalledTimes(1); expect(event.stopPropagation).toHaveBeenCalledTimes(1); // expect(openImages).toHaveBeenCalledTimes(1); // expect(openImages.mock.calls[0][0]).toStrictEqual(imgSrcs); }); }); describe('downloadImage 画像をダウンロードする', () => { let img; let event = {}; beforeEach(() => { img = document.createElement('img'); img.src = 'https://pbs.twimg.com/media/hogefuga123.jpg'; document.querySelector('body').appendChild(img); event = { preventDefault: jest.fn(), }; }); afterEach(() => { img.parentNode.removeChild(img); }); it('Ctrl-s', () => { event.ctrlKey = true; event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).toHaveBeenCalledTimes(1); }); it('Cmd-s', () => { event.metaKey = true; event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).toHaveBeenCalledTimes(1); }); it('ただのsなら何もしない', () => { event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); it('ただのCtrlなら何もしない', () => { event.ctrlKey = true; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); it('ただのCmdなら何もしない', () => { event.metaKey = true; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); it('imgのsrcがないときCtrl-sしても何もしない', () => { img.src = ''; event.ctrlKey = true; event.key = 's'; downloadImage(event); // 便宜上event.preventDefaultまで到達したのでダウンロードされているはずとしてテスト expect(event.preventDefault).not.toHaveBeenCalled(); }); }); describe('getButtonSetter ボタン設置するクラスのゲッタ', () => { const originalLocation = window.location; beforeAll(() => { delete window.location; }); afterAll(() => { window.location = originalLocation; }); it('公式WebではButtonSetter', () => { window.location = new URL('https://twitter.com'); expect(getButtonSetter()).toBeInstanceOf(ButtonSetter); }); it('TweetDeckではButtonSetterTweetDeck', () => { window.location = new URL('https://tweetdeck.twitter.com'); expect(getButtonSetter()).toBeInstanceOf(ButtonSetterTweetDeck); }); it('どちらでもなかったらButtonSetter', () => { window.location = new URL('https://hoge.test'); expect(getButtonSetter()).toBeInstanceOf(ButtonSetter); }); }); });
fix test for updateOptions
__tests__/Utils.test.js
fix test for updateOptions
<ide><path>_tests__/Utils.test.js <ide> collectUrlParams, <ide> formatUrl, <ide> openImages, <del> options, <ide> updateOptions, <ide> setStyle, <ide> getImageFilenameByUrl, <ide> window.chrome.runtime.sendMessage = jest.fn((_, callback) => <ide> callback({ data: {} }) <ide> ); <del> await expect(updateOptions()).resolves.toBeUndefined(); <del> expect(options).toStrictEqual(expected); <add> await expect(updateOptions()).resolves.toStrictEqual(expected); <ide> }); <ide> <ide> it('設定した値を取得できる', async () => { <ide> window.chrome.runtime.sendMessage = jest.fn((_, callback) => <ide> callback({ data: { ...expected } }) <ide> ); <del> await expect(updateOptions()).resolves.toBeUndefined(); <del> expect(options).toStrictEqual(expected); <add> await expect(updateOptions()).resolves.toStrictEqual(expected); <ide> }); <ide> <ide> it('設定が取得できなかったら初期設定', async () => { <ide> window.chrome.runtime.sendMessage = jest.fn((_, callback) => <ide> callback({}) <ide> ); <del> await expect(updateOptions()).resolves.toBeUndefined(); <del> expect(options).toStrictEqual(expected); <add> await expect(updateOptions()).resolves.toStrictEqual(expected); <ide> }); <ide> }); <ide> <ide> OPTION_KEYS.forEach(key => { <ide> expected[key] = isTrue; <ide> }); <del> await expect(updateOptions()).resolves.toBeUndefined(); <del> expect(options).toStrictEqual(expected); <add> await expect(updateOptions()).resolves.toStrictEqual(expected); <ide> }); <ide> }); <ide> });
Java
mit
0caaba172020ddc99b3605057c21a38d3b7f6de6
0
curtbinder/AndroidStatus
/* * The MIT License (MIT) * * Copyright (c) 2014 Curt Binder * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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 info.curtbinder.reefangel.phone; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; 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.TableRow; import android.widget.TextView; import android.widget.ToggleButton; import info.curtbinder.reefangel.controller.Controller; import info.curtbinder.reefangel.controller.Relay; import info.curtbinder.reefangel.db.StatusProvider; import info.curtbinder.reefangel.db.StatusTable; import info.curtbinder.reefangel.service.MessageCommands; import info.curtbinder.reefangel.service.UpdateService; public class PageRelayFragment extends Fragment implements PageRefreshInterface, View.OnClickListener { private static final String TAG = PageRelayFragment.class.getSimpleName(); private static final int COL_R = 0; private static final int COL_RON = 1; private static final int COL_ROFF = 2; private int relayNumber; private ToggleButton[] portBtns = new ToggleButton[Controller.MAX_RELAY_PORTS]; private View[] portMaskBtns = new View[Controller.MAX_RELAY_PORTS]; private boolean[] controlsEnabled = new boolean[Controller.MAX_RELAY_PORTS]; private RAApplication raApp; public PageRelayFragment() { } public static PageRelayFragment newInstance(int position) { // pass in values to construct a new instance Bundle args = new Bundle(); args.putInt(Globals.RELAY_BOX_NUMBER, position); PageRelayFragment p = new PageRelayFragment(); p.setArguments(args); return p; } private void getRelayNumber() { Bundle args = getArguments(); if ( args != null ) { relayNumber = args.getInt(Globals.RELAY_BOX_NUMBER, 0); } else { relayNumber = 0; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.page_relaybox, container, false); findViews(rootView); raApp = (RAApplication) getActivity().getApplication(); getRelayNumber(); return rootView; } private void findViews(View root) { TableRow tr; tr = (TableRow) root.findViewById(R.id.rowPort1); portBtns[0] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[0] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort2); portBtns[1] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[1] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort3); portBtns[2] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[2] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort4); portBtns[3] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[3] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort5); portBtns[4] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[4] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort6); portBtns[5] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[5] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort7); portBtns[6] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[6] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort8); portBtns[7] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[7] = tr.findViewById(R.id.rowOverrideToggle); } @Override public void onResume() { super.onResume(); setOnClickListeners(); setPortLabels(); refreshButtonEnablement(); refreshData(); } @Override public void onPause() { super.onPause(); } private void refreshButtonEnablement() { for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { boolean enabled = isControlEnabled(i); portBtns[i].setEnabled(enabled); portMaskBtns[i].setClickable(enabled); } } private boolean isControlEnabled(int port) { // TODO if creating a monitor only mode for the controller, this is where we would alter the code // If we are communicating with the Portal, the buttons are always DISABLED // Otherwise, if we are communicating with a Controller, ENABLE/DISABLE the buttons based // on the user's preferences if (!raApp.raprefs.isCommunicateController()) return false; return controlsEnabled[port]; } private void setControlEnabled(int port, boolean enabled) { controlsEnabled[port] = enabled; } private void setClickable(boolean clickable) { for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { portBtns[i].setClickable(clickable); portMaskBtns[i].setClickable(clickable); } } private void setOnClickListeners() { for ( int i = 0; i < Controller.MAX_RELAY_PORTS; i++ ) { portBtns[i].setOnClickListener(this); portMaskBtns[i].setOnClickListener(this); } } private void setPortLabels() { RAPreferences raPrefs = raApp.raprefs; String defaultPort = raApp.getString(R.string.defaultPortName); for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { setPortLabel(i, raPrefs.getRelayLabel(relayNumber, i), defaultPort + (i+1)); setControlEnabled(i, raPrefs.getRelayControlEnabled(relayNumber, i)); } } private void setPortLabel(int port, String title, String subtitle) { // relay is 0 based // label is text to set Log.d(TAG, relayNumber + " Label: " + port + ", " + title); int id; switch (port) { default: case 0: id = R.id.rowPort1; break; case 1: id = R.id.rowPort2; break; case 2: id = R.id.rowPort3; break; case 3: id = R.id.rowPort4; break; case 4: id = R.id.rowPort5; break; case 5: id = R.id.rowPort6; break; case 6: id = R.id.rowPort7; break; case 7: id = R.id.rowPort8; break; } TableRow tr; tr = (TableRow) getView().findViewById(id); ((TextView) tr.findViewById(R.id.rowTitle)).setText(title); ((TextView) tr.findViewById(R.id.rowSubTitle)).setText(subtitle); } private void updateData() { Log.d(TAG, "updateData"); Uri uri = Uri.parse(StatusProvider.CONTENT_URI + "/" + StatusProvider.PATH_LATEST); Cursor c = getActivity().getContentResolver().query(uri, null, null, null, StatusTable.COL_ID + " DESC"); String updateStatus; short r, ron, roff; if (c.moveToFirst()) { updateStatus = c.getString(c.getColumnIndex(StatusTable.COL_LOGDATE)); r = c.getShort(c.getColumnIndex(getColumnName(COL_R))); ron = c.getShort(c.getColumnIndex(getColumnName(COL_RON))); roff = c.getShort(c.getColumnIndex(getColumnName(COL_ROFF))); } else { updateStatus = getString(R.string.messageNever); r = ron = roff = 0; } c.close(); ((StatusFragment) getParentFragment()).updateDisplayText(updateStatus); updateRelayValues(new Relay(r, ron, roff), ((RAApplication) getActivity().getApplication()).raprefs.isCommunicateController()); } private String getColumnName(int type) { String column = "r"; if (relayNumber > 0) { column += Integer.toString(relayNumber); } switch(type) { case COL_R: column += "data"; break; case COL_RON: column += "onmask"; break; case COL_ROFF: column += "offmask"; break; } return column; } private void updateRelayValues(Relay r, boolean fUseMask) { short status; for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { status = r.getPortStatus(i + 1); portBtns[i].setChecked(r.isPortOn(i + 1, fUseMask)); if (((status == Relay.PORT_ON) || (status == Relay.PORT_STATE_OFF)) && fUseMask) { // masked on or off, show button portMaskBtns[i].setVisibility(View.VISIBLE); } else { portMaskBtns[i].setVisibility(View.INVISIBLE); } } } @Override public void refreshData() { Activity a = getActivity(); if (a == null) { return; } updateData(); } @Override public void onClick(View v) { int box = getBoxNumber(); // inside Log.d, the + is string concatenation // so relayNumber + NUM is actually like doing 1 + 1 == 11 // however, when you get into arithmetic 1 + 1 = 2 and not 11 // The buttons are nested inside a LinearLayout and then inside a // TableRow // The TableRow is the View that contains the row id int port = 1; View parent = (View) v.getParent().getParent(); switch ( parent.getId() ) { default: case R.id.rowPort1: port = 1; break; case R.id.rowPort2: port = 2; break; case R.id.rowPort3: port = 3; break; case R.id.rowPort4: port = 4; break; case R.id.rowPort5: port = 5; break; case R.id.rowPort6: port = 6; break; case R.id.rowPort7: port = 7; break; case R.id.rowPort8: port = 8; break; } if ( v.getId() == R.id.rowOverrideToggle ) { sendRelayClearMaskTask( box + port ); } else if ( v.getId() == R.id.rowToggle ) { sendRelayToggleTask( box + port ); } } private int getBoxNumber ( ) { return relayNumber * 10; } private void sendRelayToggleTask ( int port ) { // port is 1 based Log.d( TAG, "sendRelayToggleTask" ); int p = port - getBoxNumber(); int status = Relay.PORT_STATE_OFF; if ( portBtns[p - 1].isChecked() ) { status = Relay.PORT_STATE_ON; } launchRelayToggleTask( port, status ); } private void sendRelayClearMaskTask ( int port ) { // port is 1 based Log.d( TAG, "sendRelayClearMaskTask" ); // hide ourself and clear the mask int p = port - getBoxNumber(); portMaskBtns[p - 1].setVisibility( View.INVISIBLE ); launchRelayToggleTask( port, Relay.PORT_STATE_AUTO ); } private void launchRelayToggleTask ( int relay, int status ) { // port is 1 based Intent i = new Intent( getActivity(), UpdateService.class ); i.setAction( MessageCommands.TOGGLE_RELAY_INTENT ); i.putExtra( MessageCommands.TOGGLE_RELAY_PORT_INT, relay ); i.putExtra( MessageCommands.TOGGLE_RELAY_MODE_INT, status ); getActivity().startService(i); } }
app/src/main/java/info/curtbinder/reefangel/phone/PageRelayFragment.java
/* * The MIT License (MIT) * * Copyright (c) 2014 Curt Binder * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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 info.curtbinder.reefangel.phone; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; 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.TableRow; import android.widget.TextView; import android.widget.ToggleButton; import info.curtbinder.reefangel.controller.Controller; import info.curtbinder.reefangel.controller.Relay; import info.curtbinder.reefangel.db.StatusProvider; import info.curtbinder.reefangel.db.StatusTable; import info.curtbinder.reefangel.service.MessageCommands; import info.curtbinder.reefangel.service.UpdateService; public class PageRelayFragment extends Fragment implements PageRefreshInterface, View.OnClickListener { private static final String TAG = PageRelayFragment.class.getSimpleName(); private static final int COL_R = 0; private static final int COL_RON = 1; private static final int COL_ROFF = 2; private int relayNumber; private ToggleButton[] portBtns = new ToggleButton[Controller.MAX_RELAY_PORTS]; private View[] portMaskBtns = new View[Controller.MAX_RELAY_PORTS]; private boolean[] controlsEnabled = new boolean[Controller.MAX_RELAY_PORTS]; public PageRelayFragment() { } public static PageRelayFragment newInstance(int position) { // pass in values to construct a new instance Bundle args = new Bundle(); args.putInt(Globals.RELAY_BOX_NUMBER, position); PageRelayFragment p = new PageRelayFragment(); p.setArguments(args); return p; } private void getRelayNumber() { Bundle args = getArguments(); if ( args != null ) { relayNumber = args.getInt(Globals.RELAY_BOX_NUMBER, 0); } else { relayNumber = 0; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.page_relaybox, container, false); findViews(rootView); getRelayNumber(); return rootView; } private void findViews(View root) { TableRow tr; tr = (TableRow) root.findViewById(R.id.rowPort1); portBtns[0] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[0] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort2); portBtns[1] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[1] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort3); portBtns[2] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[2] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort4); portBtns[3] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[3] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort5); portBtns[4] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[4] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort6); portBtns[5] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[5] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort7); portBtns[6] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[6] = tr.findViewById(R.id.rowOverrideToggle); tr = (TableRow) root.findViewById(R.id.rowPort8); portBtns[7] = (ToggleButton) tr.findViewById(R.id.rowToggle); portMaskBtns[7] = tr.findViewById(R.id.rowOverrideToggle); } @Override public void onResume() { super.onResume(); refreshButtonEnablement(); setOnClickListeners(); setPortLabels(); refreshData(); } @Override public void onPause() { super.onPause(); } private void refreshButtonEnablement() { for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { boolean enabled = isControlEnabled(i); portBtns[i].setEnabled(enabled); portMaskBtns[i].setClickable(enabled); } } private boolean isControlEnabled(int port) { return controlsEnabled[port]; } private void setControlEnabled(int port, boolean enabled) { controlsEnabled[port] = enabled; refreshButtonEnablement(); } private void setClickable(boolean clickable) { for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { portBtns[i].setClickable(false); portMaskBtns[i].setClickable(false); } } private void setOnClickListeners() { for ( int i = 0; i < Controller.MAX_RELAY_PORTS; i++ ) { portBtns[i].setOnClickListener(this); portMaskBtns[i].setOnClickListener(this); } } private void setPortLabels() { Resources r = getActivity().getResources(); RAApplication raApp = (RAApplication) getActivity().getApplication(); RAPreferences raPrefs = raApp.raprefs; boolean enabled; String defaultPort = r.getString(R.string.defaultPortName); for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { setPortLabel(i, raPrefs.getRelayLabel(relayNumber, i), defaultPort + (i+1)); enabled = raPrefs.getRelayControlEnabled(relayNumber, i); setControlEnabled(i, enabled); } } private void setPortLabel(int port, String title, String subtitle) { // relay is 0 based // label is text to set Log.d(TAG, relayNumber + " Label: " + port + ", " + title); int id; switch (port) { default: case 0: id = R.id.rowPort1; break; case 1: id = R.id.rowPort2; break; case 2: id = R.id.rowPort3; break; case 3: id = R.id.rowPort4; break; case 4: id = R.id.rowPort5; break; case 5: id = R.id.rowPort6; break; case 6: id = R.id.rowPort7; break; case 7: id = R.id.rowPort8; break; } TableRow tr; tr = (TableRow) getView().findViewById(id); ((TextView) tr.findViewById(R.id.rowTitle)).setText(title); ((TextView) tr.findViewById(R.id.rowSubTitle)).setText(subtitle); } private void updateData() { Log.d(TAG, "updateData"); Uri uri = Uri.parse(StatusProvider.CONTENT_URI + "/" + StatusProvider.PATH_LATEST); Cursor c = getActivity().getContentResolver().query(uri, null, null, null, StatusTable.COL_ID + " DESC"); String updateStatus; short r, ron, roff; if (c.moveToFirst()) { updateStatus = c.getString(c.getColumnIndex(StatusTable.COL_LOGDATE)); r = c.getShort(c.getColumnIndex(getColumnName(COL_R))); ron = c.getShort(c.getColumnIndex(getColumnName(COL_RON))); roff = c.getShort(c.getColumnIndex(getColumnName(COL_ROFF))); } else { updateStatus = getString(R.string.messageNever); r = ron = roff = 0; } c.close(); ((StatusFragment) getParentFragment()).updateDisplayText(updateStatus); updateRelayValues(new Relay(r, ron, roff), ((RAApplication) getActivity().getApplication()).raprefs.isCommunicateController()); } private String getColumnName(int type) { String column = "r"; if (relayNumber > 0) { column += Integer.toString(relayNumber); } switch(type) { case COL_R: column += "data"; break; case COL_RON: column += "onmask"; break; case COL_ROFF: column += "offmask"; break; } return column; } private void updateRelayValues(Relay r, boolean fUseMask) { short status; for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { status = r.getPortStatus(i + 1); portBtns[i].setChecked(r.isPortOn(i + 1, fUseMask)); if (((status == Relay.PORT_ON) || (status == Relay.PORT_STATE_OFF)) && fUseMask) { // masked on or off, show button portMaskBtns[i].setVisibility(View.VISIBLE); } else { portMaskBtns[i].setVisibility(View.INVISIBLE); } } } @Override public void refreshData() { Activity a = getActivity(); if (a == null) { return; } updateData(); } @Override public void onClick(View v) { int box = getBoxNumber(); // inside Log.d, the + is string concatenation // so relayNumber + NUM is actually like doing 1 + 1 == 11 // however, when you get into arithmetic 1 + 1 = 2 and not 11 // The buttons are nested inside a LinearLayout and then inside a // TableRow // The TableRow is the View that contains the row id int port = 1; View parent = (View) v.getParent().getParent(); switch ( parent.getId() ) { default: case R.id.rowPort1: port = 1; break; case R.id.rowPort2: port = 2; break; case R.id.rowPort3: port = 3; break; case R.id.rowPort4: port = 4; break; case R.id.rowPort5: port = 5; break; case R.id.rowPort6: port = 6; break; case R.id.rowPort7: port = 7; break; case R.id.rowPort8: port = 8; break; } if ( v.getId() == R.id.rowOverrideToggle ) { sendRelayClearMaskTask( box + port ); } else if ( v.getId() == R.id.rowToggle ) { sendRelayToggleTask( box + port ); } } private int getBoxNumber ( ) { return relayNumber * 10; } private void sendRelayToggleTask ( int port ) { // port is 1 based Log.d( TAG, "sendRelayToggleTask" ); int p = port - getBoxNumber(); int status = Relay.PORT_STATE_OFF; if ( portBtns[p - 1].isChecked() ) { status = Relay.PORT_STATE_ON; } launchRelayToggleTask( port, status ); } private void sendRelayClearMaskTask ( int port ) { // port is 1 based Log.d( TAG, "sendRelayClearMaskTask" ); // hide ourself and clear the mask int p = port - getBoxNumber(); portMaskBtns[p - 1].setVisibility( View.INVISIBLE ); launchRelayToggleTask( port, Relay.PORT_STATE_AUTO ); } private void launchRelayToggleTask ( int relay, int status ) { // port is 1 based Intent i = new Intent( getActivity(), UpdateService.class ); i.setAction( MessageCommands.TOGGLE_RELAY_INTENT ); i.putExtra( MessageCommands.TOGGLE_RELAY_PORT_INT, relay ); i.putExtra( MessageCommands.TOGGLE_RELAY_MODE_INT, status ); getActivity().startService(i); } }
Fixed button enablement with device To bring it back inline with the main app, disable the buttons when communicating with the Portal. Also changed the order when refreshing the button enablement is called. Removed duplicate calls to refresh enablement. We were looping over all 8 relay buttons each time we set a port label. That was making 8 calls to a function that iterates over all 8 ports when 1 call is sufficient when we are finished updating the labels.
app/src/main/java/info/curtbinder/reefangel/phone/PageRelayFragment.java
Fixed button enablement with device
<ide><path>pp/src/main/java/info/curtbinder/reefangel/phone/PageRelayFragment.java <ide> private View[] portMaskBtns = new View[Controller.MAX_RELAY_PORTS]; <ide> <ide> private boolean[] controlsEnabled = new boolean[Controller.MAX_RELAY_PORTS]; <add> private RAApplication raApp; <ide> <ide> public PageRelayFragment() { <ide> } <ide> Bundle savedInstanceState) { <ide> View rootView = inflater.inflate(R.layout.page_relaybox, container, false); <ide> findViews(rootView); <add> raApp = (RAApplication) getActivity().getApplication(); <ide> getRelayNumber(); <ide> return rootView; <ide> } <ide> @Override <ide> public void onResume() { <ide> super.onResume(); <del> refreshButtonEnablement(); <ide> setOnClickListeners(); <ide> setPortLabels(); <add> refreshButtonEnablement(); <ide> refreshData(); <ide> } <ide> <ide> } <ide> <ide> private boolean isControlEnabled(int port) { <add> // TODO if creating a monitor only mode for the controller, this is where we would alter the code <add> // If we are communicating with the Portal, the buttons are always DISABLED <add> // Otherwise, if we are communicating with a Controller, ENABLE/DISABLE the buttons based <add> // on the user's preferences <add> if (!raApp.raprefs.isCommunicateController()) <add> return false; <ide> return controlsEnabled[port]; <ide> } <ide> <ide> private void setControlEnabled(int port, boolean enabled) { <ide> controlsEnabled[port] = enabled; <del> refreshButtonEnablement(); <ide> } <ide> <ide> private void setClickable(boolean clickable) { <ide> for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { <del> portBtns[i].setClickable(false); <del> portMaskBtns[i].setClickable(false); <add> portBtns[i].setClickable(clickable); <add> portMaskBtns[i].setClickable(clickable); <ide> } <ide> } <ide> <ide> } <ide> <ide> private void setPortLabels() { <del> Resources r = getActivity().getResources(); <del> RAApplication raApp = (RAApplication) getActivity().getApplication(); <ide> RAPreferences raPrefs = raApp.raprefs; <del> boolean enabled; <del> String defaultPort = r.getString(R.string.defaultPortName); <add> String defaultPort = raApp.getString(R.string.defaultPortName); <ide> for (int i = 0; i < Controller.MAX_RELAY_PORTS; i++) { <ide> setPortLabel(i, raPrefs.getRelayLabel(relayNumber, i), defaultPort + (i+1)); <del> enabled = raPrefs.getRelayControlEnabled(relayNumber, i); <del> setControlEnabled(i, enabled); <add> setControlEnabled(i, raPrefs.getRelayControlEnabled(relayNumber, i)); <ide> } <ide> } <ide>
Java
bsd-2-clause
c4878a02ed8cf81c27dccd7d0ac703f21c23cd48
0
scifio/scifio
// // FluoviewReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.IOException; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.tiff.IFD; import loci.formats.tiff.TiffParser; import ome.xml.r201004.enums.Correction; import ome.xml.r201004.enums.DetectorType; import ome.xml.r201004.enums.EnumerationException; import ome.xml.r201004.enums.Immersion; /** * FluoviewReader is the file format reader for * Olympus Fluoview TIFF files AND Andor Bio-imaging Division (ABD) TIFF files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/FluoviewReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/FluoviewReader.java">SVN</a></dd></dl> * * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert linkert at wisc.edu * @author Curtis Rueden ctrueden at wisc.edu */ public class FluoviewReader extends BaseTiffReader { // -- Constants -- /** String identifying a Fluoview file. */ private static final String FLUOVIEW_MAGIC_STRING = "FLUOVIEW"; /** Private TIFF tags */ private static final int MMHEADER = 34361; private static final int MMSTAMP = 34362; /** Date format */ private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss.SSS"; // -- Fields -- /** Pixel dimensions for this file. */ private double voxelX = 1, voxelY = 1, voxelZ = 1, voxelC = 1, voxelT = 1; private String dimensionOrder; private String date = null; private int timeIndex = -1; /** Timestamps for each plane, in seconds. */ private double[][] stamps = null; // hardware settings private String[] gains, voltages, offsets, channelNames, lensNA; private String mag, detectorManufacturer, objectiveManufacturer, comment; // -- Constructor -- /** Constructs a new Fluoview TIFF reader. */ public FluoviewReader() { super("Olympus Fluoview/ABD TIFF", new String[] {"tif", "tiff"}); suffixSufficient = false; domains = new String[] {FormatTools.LM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; String com = ifd.getComment(); if (com == null) com = ""; return com.indexOf(FLUOVIEW_MAGIC_STRING) != -1 && ifd.containsKey(new Integer(MMHEADER)) || ifd.containsKey(new Integer(MMSTAMP)); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { int image = getImageIndex(no); if (getSizeY() == ifds.get(0).getImageLength()) { tiffParser.getSamples(ifds.get(image), buf, x, y, w, h); } else { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); tiffParser.getSamples(ifds.get(0), buf, x, image, w, 1); } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { voxelX = voxelY = voxelZ = voxelC = voxelT = 1; dimensionOrder = null; gains = voltages = offsets = channelNames = lensNA = null; mag = detectorManufacturer = objectiveManufacturer = comment = null; date = null; timeIndex = -1; stamps = null; } } // -- Internal BaseTiffReader API methods -- /* @see loci.formats.BaseTiffReader#initStandardMetadata() */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); // First, we want to determine whether this file is a Fluoview TIFF. // Originally, Andor TIFF had its own reader; however, the two formats are // very similar, so it made more sense to merge the two formats into one // reader. short[] s = ifds.get(0).getIFDShortArray(MMHEADER); if (s == null) { throw new FormatException("Invalid Fluoview/Andor TIFF. Tag " + MMHEADER + " not found."); } byte[] mmheader = shortArrayToBytes(s); RandomAccessInputStream ras = new RandomAccessInputStream(mmheader); ras.order(isLittleEndian()); if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { put("Header Flag", ras.readShort()); put("Image Type", ras.read()); put("Image name", ras.readString(257)); ras.skipBytes(4); // skip pointer to data field put("Number of colors", ras.readInt()); ras.skipBytes(4); // skip pointer to palette field ras.skipBytes(4); // skip pointer to other palette field put("Comment size", ras.readInt()); ras.skipBytes(4); // skip pointer to comment field } else ras.skipBytes(284); // read dimension information String[] names = new String[10]; int[] sizes = new int[10]; double[] resolutions = new double[10]; for (int i=0; i<10; i++) { names[i] = ras.readString(16); sizes[i] = ras.readInt(); double origin = ras.readDouble(); resolutions[i] = ras.readDouble(); put("Dimension " + (i + 1) + " Name", names[i]); put("Dimension " + (i + 1) + " Size", sizes[i]); put("Dimension " + (i + 1) + " Origin", origin); put("Dimension " + (i + 1) + " Resolution", resolutions[i]); put("Dimension " + (i + 1) + " Units", ras.readString(64)); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { ras.skipBytes(4); // skip pointer to spatial position data put("Map type", ras.readShort()); put("Map min", ras.readDouble()); put("Map max", ras.readDouble()); put("Min value", ras.readDouble()); put("Max value", ras.readDouble()); ras.skipBytes(4); // skip pointer to map data put("Gamma", ras.readDouble()); put("Offset", ras.readDouble()); // read gray channel data put("Gray Channel Name", ras.readString(16)); put("Gray Channel Size", ras.readInt()); put("Gray Channel Origin", ras.readDouble()); put("Gray Channel Resolution", ras.readDouble()); put("Gray Channel Units", ras.readString(64)); ras.skipBytes(4); // skip pointer to thumbnail data put("Voice field", ras.readInt()); ras.skipBytes(4); // skip pointer to voice field // now we need to read the MMSTAMP data to determine dimension order readStamps(); } ras.close(); // calculate the dimension order and axis sizes dimensionOrder = "XY"; int seriesCount = 1; core[0].sizeZ = core[0].sizeC = core[0].sizeT = 1; for (int i=0; i<10; i++) { String name = names[i]; int size = sizes[i]; double voxel = resolutions[i]; if (name == null || size == 0) continue; name = name.toLowerCase().trim(); if (name.length() == 0) continue; if (name.equals("x")) { voxelX = voxel; } else if (name.equals("y")) { voxelY = voxel; } else if (name.equals("z") || name.equals("event")) { core[0].sizeZ *= size; if (dimensionOrder.indexOf("Z") == -1) { dimensionOrder += "Z"; } voxelZ = voxel; } else if (name.equals("ch") || name.equals("wavelength")) { core[0].sizeC *= size; if (dimensionOrder.indexOf("C") == -1) { dimensionOrder += "C"; } voxelC = voxel; } else if (name.equals("time") || name.equals("t") || name.equals("animation")) { core[0].sizeT *= size; if (dimensionOrder.indexOf("T") == -1) { dimensionOrder += "T"; } voxelT = voxel; timeIndex = i - 2; } else { if (dimensionOrder.indexOf("S") == -1) dimensionOrder += "S"; seriesCount *= size; } } if (dimensionOrder.indexOf("Z") == -1) dimensionOrder += "Z"; if (dimensionOrder.indexOf("T") == -1) dimensionOrder += "T"; if (dimensionOrder.indexOf("C") == -1) dimensionOrder += "C"; if (dimensionOrder.indexOf("S") == -1) dimensionOrder += "S"; core[0].imageCount = ifds.size() / seriesCount; if (getSizeZ() > getImageCount()) core[0].sizeZ = getImageCount(); if (getSizeT() > getImageCount()) core[0].sizeT = getImageCount(); if (getSizeZ() * getSizeC() * getSizeT() > getImageCount()) { int diff = getSizeZ() * getSizeC() * getSizeT() - getImageCount(); if (diff == getSizeC()) { if (getSizeZ() > 1) core[0].sizeZ--; else if (getSizeT() > 1) core[0].sizeT--; else core[0].sizeC /= getSizeC(); } } if (getImageCount() == 1 && (getSizeT() == getSizeY() || getSizeZ() == getSizeY()) && (getSizeT() > getImageCount() || getSizeZ() > getImageCount())) { core[0].sizeY = 1; core[0].imageCount = getSizeZ() * getSizeC() * getSizeT(); } core[0].dimensionOrder = dimensionOrder.replaceAll("S", ""); if (seriesCount > 1) { CoreMetadata oldCore = core[0]; core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = oldCore; } } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { // cut up the comment, if necessary comment = ifds.get(0).getComment(); gains = new String[getSizeC()]; offsets = new String[getSizeC()]; voltages = new String[getSizeC()]; channelNames = new String[getSizeC()]; lensNA = new String[getSizeC()]; parsePageName(); parseComment(); addGlobalMeta("Comment", comment); } } /* @see loci.formats.in.BaseTiffReader#initMetadataStore() */ protected void initMetadataStore() throws FormatException { super.initMetadataStore(); MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); if (date != null) { store.setImageAcquiredDate(date, 0); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.ALL) { return; } store.setImageDescription(comment, 0); // link Instrument and Image String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); store.setImageInstrumentRef(instrumentID, 0); // populate timing data if (timeIndex >= 0) { for (int s=0; s<getSeriesCount(); s++) { setSeries(s); for (int i=0; i<getImageCount(); i++) { int index = getImageIndex(i); store.setPlaneDeltaT(stamps[timeIndex][index], s, i); } } setSeries(0); } // populate Dimensions store.setPixelsPhysicalSizeX(voxelX, 0); store.setPixelsPhysicalSizeY(voxelY, 0); store.setPixelsPhysicalSizeZ(voxelZ, 0); store.setPixelsTimeIncrement(voxelT, 0); // populate LogicalChannel data for (int i=0; i<getSizeC(); i++) { if (channelNames[i] != null) { store.setChannelName(channelNames[i].trim(), 0, i); } } // populate Detector data for (int i=0; i<getSizeC(); i++) { if (voltages[i] != null) { if (detectorManufacturer != null) { store.setDetectorManufacturer(detectorManufacturer, 0, 0); } store.setDetectorSettingsVoltage(new Double(voltages[i]), 0, i); } if (gains[i] != null) { store.setDetectorSettingsGain(new Double(gains[i]), 0, i); } if (offsets[i] != null) { store.setDetectorSettingsOffset(new Double(offsets[i]), 0, i); } store.setDetectorType(DetectorType.OTHER, 0, i); // link DetectorSettings to an actual Detector String detectorID = MetadataTools.createLSID("Detector", 0, i); store.setDetectorID(detectorID, 0, i); store.setDetectorSettingsID(detectorID, 0, i); } // populate Objective data if (mag != null && mag.toLowerCase().endsWith("x")) { mag = mag.substring(0, mag.length() - 1); } else if (mag == null) mag = "1"; store.setObjectiveCorrection(Correction.OTHER, 0, 0); store.setObjectiveImmersion(Immersion.OTHER, 0, 0); if (objectiveManufacturer != null) { String[] objectiveData = objectiveManufacturer.split(" "); store.setObjectiveModel(objectiveData[0], 0, 0); if (objectiveData.length > 2) { try { store.setObjectiveImmersion( Immersion.fromString(objectiveData[2]), 0, 0); } catch (EnumerationException e) { } } } if (mag != null) { store.setObjectiveCalibratedMagnification(new Double(mag), 0, 0); } for (int i=0; i<getSizeC(); i++) { if (lensNA[i] != null) { store.setObjectiveLensNA(new Double(lensNA[i]), 0, i); } } // link Objective to Image using ObjectiveSettings String objectiveID = MetadataTools.createLSID("Objective", 0, 0); store.setObjectiveID(objectiveID, 0, 0); store.setImageObjectiveSettingsID(objectiveID, 0); } // -- Helper methods -- private int getImageIndex(int no) { // the 'series' axis can be in any position relative to Z, C and T // we need to convert the plane number within the series into an IFD number int[] lengths = new int[4]; int[] pos = getZCTCoords(no); int[] realPos = new int[4]; for (int i=2; i<dimensionOrder.length(); i++) { char axis = dimensionOrder.charAt(i); if (axis == 'Z') { lengths[i - 2] = getSizeZ(); realPos[i - 2] = pos[0]; } else if (axis == 'C') { lengths[i - 2] = getEffectiveSizeC(); realPos[i - 2] = pos[1]; } else if (axis == 'T') { lengths[i - 2] = getSizeT(); realPos[i - 2] = pos[2]; } else if (axis == 'S') { lengths[i - 2] = getSeriesCount(); realPos[i - 2] = getSeries(); } } return FormatTools.positionToRaster(lengths, realPos); } private void readStamps() throws FormatException, IOException { stamps = new double[8][ifds.size()]; for (int i=0; i<ifds.size(); i++) { byte[] stamp = shortArrayToBytes(ifds.get(i).getIFDShortArray(MMSTAMP)); RandomAccessInputStream ras = new RandomAccessInputStream(stamp); ras.order(isLittleEndian()); // each stamp is 8 doubles, representing the position on dimensions 3-10 for (int j=0; j<8; j++) { stamps[j][i] = ras.readDouble() / 1000; // correct for clock skew? int pow = -1; while (Math.pow(2, pow) < stamps[j][i]) { stamps[j][i] -= (0.032 * (Math.pow(2, pow < 0 ? 0 : pow))); pow++; } } ras.close(); } } private byte[] shortArrayToBytes(short[] s) { byte[] b = new byte[s.length]; for (int i=0; i<s.length; i++) { b[i] = (byte) s[i]; if (b[i] < 0) b[i]++; } return b; } private void parsePageName() { String pageName = ifds.get(0).getIFDTextValue(IFD.PAGE_NAME); if (pageName == null) return; String[] lines = pageName.split("\n"); for (String line : lines) { if (line.startsWith("Resolution")) { String[] resolutions = line.split("\t"); if (resolutions.length > 1) { voxelX = Double.parseDouble(resolutions[1].trim()); } if (resolutions.length > 2) { voxelY = Double.parseDouble(resolutions[2].trim()); } break; } } } private void parseComment() { if (comment != null) { // this is an INI-style comment, with one key/value pair per line String[] lines = comment.split("\n"); for (String token : lines) { token = token.trim(); int eq = token.indexOf("="); if (eq != -1) { String key = token.substring(0, eq); String value = token.substring(eq + 1); addGlobalMeta(key, value); if (key.startsWith("Gain Ch")) { for (int i=0; i<gains.length; i++) { if (gains[i] == null) { gains[i] = value; break; } } } else if (key.startsWith("PMT Voltage Ch")) { for (int i=0; i<voltages.length; i++) { if (voltages[i] == null) { voltages[i] = value; break; } } } else if (key.startsWith("Offset Ch")) { for (int i=0; i<offsets.length; i++) { if (offsets[i] == null) { offsets[i] = value; break; } } } else if (key.equals("Magnification")) mag = value; else if (key.equals("System Configuration")) { detectorManufacturer = value; } else if (key.equals("Objective Lens")) objectiveManufacturer = value; else if (key.startsWith("Channel ") && key.endsWith("Dye")) { for (int i=0; i<channelNames.length; i++) { if (channelNames[i] == null) { channelNames[i] = value; break; } } } else if (key.startsWith("Confocal Aperture-Ch")) { for (int i=0; i<lensNA.length; i++) { if (lensNA[i] == null) { lensNA[i] = value.substring(0, value.length() - 2); break; } } } else if (key.equals("Date")) { date = value; } else if (key.equals("Time")) { date += " " + value; } } else if (token.startsWith("Z") && token.indexOf(" um ") != -1) { // looking for "Z - x um in y planes" String z = token.substring(token.indexOf("-") + 1); z = z.replaceAll("\\p{Alpha}", "").trim(); int firstSpace = z.indexOf(" "); double size = Double.parseDouble(z.substring(0, firstSpace)); double nPlanes = Double.parseDouble(z.substring(firstSpace).trim()); voxelZ = size / nPlanes; } } if (date != null) { date = DateTools.formatDate(date.trim(), new String[] {"MM/dd/yyyy hh:mm:ss a", "MM-dd-yyyy hh:mm:ss"}, true); if (timeIndex >= 0 && date != null) { long ms = DateTools.getTime(date, DateTools.ISO8601_FORMAT); int nChars = String.valueOf(getImageCount()).length(); for (int i=0; i<getImageCount(); i++) { int[] zct = getZCTCoords(i); String key = String.format( "Timestamp for Z=%2s, C=%2s, T=%2s", zct[0], zct[1], zct[2]); long stamp = ms + (long) (stamps[timeIndex][i] * 1000); addGlobalMeta(key, DateTools.convertDate(stamp, DateTools.UNIX, DATE_FORMAT)); } } } int start = comment.indexOf("[Version Info]"); int end = comment.indexOf("[Version Info End]"); if (start != -1 && end != -1 && end > start) { comment = comment.substring(start + 14, end).trim(); start = comment.indexOf("=") + 1; end = comment.indexOf("\n"); if (end > start) comment = comment.substring(start, end).trim(); else comment = comment.substring(start).trim(); } else comment = ""; } } }
components/bio-formats/src/loci/formats/in/FluoviewReader.java
// // FluoviewReader.java // /* OME Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.IOException; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.tiff.IFD; import loci.formats.tiff.TiffParser; import ome.xml.r201004.enums.Correction; import ome.xml.r201004.enums.DetectorType; import ome.xml.r201004.enums.EnumerationException; import ome.xml.r201004.enums.Immersion; /** * FluoviewReader is the file format reader for * Olympus Fluoview TIFF files AND Andor Bio-imaging Division (ABD) TIFF files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/bio-formats/src/loci/formats/in/FluoviewReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/bio-formats/src/loci/formats/in/FluoviewReader.java">SVN</a></dd></dl> * * @author Eric Kjellman egkjellman at wisc.edu * @author Melissa Linkert linkert at wisc.edu * @author Curtis Rueden ctrueden at wisc.edu */ public class FluoviewReader extends BaseTiffReader { // -- Constants -- /** String identifying a Fluoview file. */ private static final String FLUOVIEW_MAGIC_STRING = "FLUOVIEW"; /** Private TIFF tags */ private static final int MMHEADER = 34361; private static final int MMSTAMP = 34362; /** Date format */ private static final String DATE_FORMAT = "MM/dd/yyyy HH:mm:ss.SSS"; // -- Fields -- /** Pixel dimensions for this file. */ private double voxelX = 1, voxelY = 1, voxelZ = 1, voxelC = 1, voxelT = 1; private String dimensionOrder; private String date = null; private int timeIndex = -1; /** Timestamps for each plane, in seconds. */ private double[][] stamps = null; // hardware settings private String[] gains, voltages, offsets, channelNames, lensNA; private String mag, detectorManufacturer, objectiveManufacturer, comment; // -- Constructor -- /** Constructs a new Fluoview TIFF reader. */ public FluoviewReader() { super("Olympus Fluoview/ABD TIFF", new String[] {"tif", "tiff"}); suffixSufficient = false; domains = new String[] {FormatTools.LM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { TiffParser tp = new TiffParser(stream); IFD ifd = tp.getFirstIFD(); if (ifd == null) return false; String com = ifd.getComment(); if (com == null) com = ""; return com.indexOf(FLUOVIEW_MAGIC_STRING) != -1 && ifd.containsKey(new Integer(MMHEADER)) || ifd.containsKey(new Integer(MMSTAMP)); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { int image = getImageIndex(no); if (getSizeY() == ifds.get(0).getImageLength()) { tiffParser.getSamples(ifds.get(image), buf, x, y, w, h); } else { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); tiffParser.getSamples(ifds.get(0), buf, x, image, w, 1); } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { voxelX = voxelY = voxelZ = voxelC = voxelT = 1; dimensionOrder = null; gains = voltages = offsets = channelNames = lensNA = null; mag = detectorManufacturer = objectiveManufacturer = comment = null; date = null; timeIndex = -1; stamps = null; } } // -- Internal BaseTiffReader API methods -- /* @see loci.formats.BaseTiffReader#initStandardMetadata() */ protected void initStandardMetadata() throws FormatException, IOException { super.initStandardMetadata(); // First, we want to determine whether this file is a Fluoview TIFF. // Originally, Andor TIFF had its own reader; however, the two formats are // very similar, so it made more sense to merge the two formats into one // reader. short[] s = ifds.get(0).getIFDShortArray(MMHEADER); if (s == null) { throw new FormatException("Invalid Fluoview/Andor TIFF. Tag " + MMHEADER + " not found."); } byte[] mmheader = shortArrayToBytes(s); RandomAccessInputStream ras = new RandomAccessInputStream(mmheader); ras.order(isLittleEndian()); if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { put("Header Flag", ras.readShort()); put("Image Type", ras.read()); put("Image name", ras.readString(257)); ras.skipBytes(4); // skip pointer to data field put("Number of colors", ras.readInt()); ras.skipBytes(4); // skip pointer to palette field ras.skipBytes(4); // skip pointer to other palette field put("Comment size", ras.readInt()); ras.skipBytes(4); // skip pointer to comment field } else ras.skipBytes(284); // read dimension information String[] names = new String[10]; int[] sizes = new int[10]; double[] resolutions = new double[10]; for (int i=0; i<10; i++) { names[i] = ras.readString(16); sizes[i] = ras.readInt(); double origin = ras.readDouble(); resolutions[i] = ras.readDouble(); put("Dimension " + (i + 1) + " Name", names[i]); put("Dimension " + (i + 1) + " Size", sizes[i]); put("Dimension " + (i + 1) + " Origin", origin); put("Dimension " + (i + 1) + " Resolution", resolutions[i]); put("Dimension " + (i + 1) + " Units", ras.readString(64)); } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { ras.skipBytes(4); // skip pointer to spatial position data put("Map type", ras.readShort()); put("Map min", ras.readDouble()); put("Map max", ras.readDouble()); put("Min value", ras.readDouble()); put("Max value", ras.readDouble()); ras.skipBytes(4); // skip pointer to map data put("Gamma", ras.readDouble()); put("Offset", ras.readDouble()); // read gray channel data put("Gray Channel Name", ras.readString(16)); put("Gray Channel Size", ras.readInt()); put("Gray Channel Origin", ras.readDouble()); put("Gray Channel Resolution", ras.readDouble()); put("Gray Channel Units", ras.readString(64)); ras.skipBytes(4); // skip pointer to thumbnail data put("Voice field", ras.readInt()); ras.skipBytes(4); // skip pointer to voice field // now we need to read the MMSTAMP data to determine dimension order readStamps(); } ras.close(); // calculate the dimension order and axis sizes dimensionOrder = "XY"; int seriesCount = 1; core[0].sizeZ = core[0].sizeC = core[0].sizeT = 1; for (int i=0; i<10; i++) { String name = names[i]; int size = sizes[i]; double voxel = resolutions[i]; if (name == null || size == 0) continue; name = name.toLowerCase().trim(); if (name.length() == 0) continue; if (name.equals("x")) { voxelX = voxel; } else if (name.equals("y")) { voxelY = voxel; } else if (name.equals("z") || name.equals("event")) { core[0].sizeZ *= size; if (dimensionOrder.indexOf("Z") == -1) { dimensionOrder += "Z"; } voxelZ = voxel; } else if (name.equals("ch") || name.equals("wavelength")) { core[0].sizeC *= size; if (dimensionOrder.indexOf("C") == -1) { dimensionOrder += "C"; } voxelC = voxel; } else if (name.equals("time") || name.equals("t") || name.equals("animation")) { core[0].sizeT *= size; if (dimensionOrder.indexOf("T") == -1) { dimensionOrder += "T"; } voxelT = voxel; timeIndex = i - 2; } else { if (dimensionOrder.indexOf("S") == -1) dimensionOrder += "S"; seriesCount *= size; } } if (dimensionOrder.indexOf("Z") == -1) dimensionOrder += "Z"; if (dimensionOrder.indexOf("T") == -1) dimensionOrder += "T"; if (dimensionOrder.indexOf("C") == -1) dimensionOrder += "C"; if (dimensionOrder.indexOf("S") == -1) dimensionOrder += "S"; core[0].imageCount = ifds.size() / seriesCount; if (getSizeZ() > getImageCount()) core[0].sizeZ = getImageCount(); if (getSizeT() > getImageCount()) core[0].sizeT = getImageCount(); if (getSizeZ() * getSizeC() * getSizeT() > getImageCount()) { int diff = getSizeZ() * getSizeC() * getSizeT() - getImageCount(); if (diff == getSizeC()) { if (getSizeZ() > 1) core[0].sizeZ--; else if (getSizeT() > 1) core[0].sizeT--; else core[0].sizeC /= getSizeC(); } } if (getImageCount() == 1 && (getSizeT() == getSizeY() || getSizeZ() == getSizeY()) && (getSizeT() > getImageCount() || getSizeZ() > getImageCount())) { core[0].sizeY = 1; core[0].imageCount = getSizeZ() * getSizeC() * getSizeT(); } core[0].dimensionOrder = dimensionOrder.replaceAll("S", ""); if (seriesCount > 1) { CoreMetadata oldCore = core[0]; core = new CoreMetadata[seriesCount]; for (int i=0; i<seriesCount; i++) { core[i] = oldCore; } } if (getMetadataOptions().getMetadataLevel() == MetadataLevel.ALL) { // cut up the comment, if necessary comment = ifds.get(0).getComment(); gains = new String[getSizeC()]; offsets = new String[getSizeC()]; voltages = new String[getSizeC()]; channelNames = new String[getSizeC()]; lensNA = new String[getSizeC()]; parseComment(); addGlobalMeta("Comment", comment); } } /* @see loci.formats.in.BaseTiffReader#initMetadataStore() */ protected void initMetadataStore() throws FormatException { super.initMetadataStore(); MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); if (date != null) { store.setImageAcquiredDate(date, 0); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.ALL) { return; } store.setImageDescription(comment, 0); // link Instrument and Image String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); store.setImageInstrumentRef(instrumentID, 0); // populate timing data if (timeIndex >= 0) { for (int s=0; s<getSeriesCount(); s++) { setSeries(s); for (int i=0; i<getImageCount(); i++) { int index = getImageIndex(i); store.setPlaneDeltaT(stamps[timeIndex][index], s, i); } } setSeries(0); } // populate Dimensions store.setPixelsPhysicalSizeX(voxelX, 0); store.setPixelsPhysicalSizeY(voxelY, 0); store.setPixelsPhysicalSizeZ(voxelZ, 0); store.setPixelsTimeIncrement(voxelT, 0); // populate LogicalChannel data for (int i=0; i<getSizeC(); i++) { if (channelNames[i] != null) { store.setChannelName(channelNames[i].trim(), 0, i); } } // populate Detector data for (int i=0; i<getSizeC(); i++) { if (voltages[i] != null) { if (detectorManufacturer != null) { store.setDetectorManufacturer(detectorManufacturer, 0, 0); } store.setDetectorSettingsVoltage(new Double(voltages[i]), 0, i); } if (gains[i] != null) { store.setDetectorSettingsGain(new Double(gains[i]), 0, i); } if (offsets[i] != null) { store.setDetectorSettingsOffset(new Double(offsets[i]), 0, i); } store.setDetectorType(DetectorType.OTHER, 0, i); // link DetectorSettings to an actual Detector String detectorID = MetadataTools.createLSID("Detector", 0, i); store.setDetectorID(detectorID, 0, i); store.setDetectorSettingsID(detectorID, 0, i); } // populate Objective data if (mag != null && mag.toLowerCase().endsWith("x")) { mag = mag.substring(0, mag.length() - 1); } else if (mag == null) mag = "1"; store.setObjectiveCorrection(Correction.OTHER, 0, 0); store.setObjectiveImmersion(Immersion.OTHER, 0, 0); if (objectiveManufacturer != null) { String[] objectiveData = objectiveManufacturer.split(" "); store.setObjectiveModel(objectiveData[0], 0, 0); if (objectiveData.length > 2) { try { store.setObjectiveImmersion( Immersion.fromString(objectiveData[2]), 0, 0); } catch (EnumerationException e) { } } } if (mag != null) { store.setObjectiveCalibratedMagnification(new Double(mag), 0, 0); } for (int i=0; i<getSizeC(); i++) { if (lensNA[i] != null) { store.setObjectiveLensNA(new Double(lensNA[i]), 0, i); } } // link Objective to Image using ObjectiveSettings String objectiveID = MetadataTools.createLSID("Objective", 0, 0); store.setObjectiveID(objectiveID, 0, 0); store.setImageObjectiveSettingsID(objectiveID, 0); } // -- Helper methods -- private int getImageIndex(int no) { // the 'series' axis can be in any position relative to Z, C and T // we need to convert the plane number within the series into an IFD number int[] lengths = new int[4]; int[] pos = getZCTCoords(no); int[] realPos = new int[4]; for (int i=2; i<dimensionOrder.length(); i++) { char axis = dimensionOrder.charAt(i); if (axis == 'Z') { lengths[i - 2] = getSizeZ(); realPos[i - 2] = pos[0]; } else if (axis == 'C') { lengths[i - 2] = getEffectiveSizeC(); realPos[i - 2] = pos[1]; } else if (axis == 'T') { lengths[i - 2] = getSizeT(); realPos[i - 2] = pos[2]; } else if (axis == 'S') { lengths[i - 2] = getSeriesCount(); realPos[i - 2] = getSeries(); } } return FormatTools.positionToRaster(lengths, realPos); } private void readStamps() throws FormatException, IOException { stamps = new double[8][ifds.size()]; for (int i=0; i<ifds.size(); i++) { byte[] stamp = shortArrayToBytes(ifds.get(i).getIFDShortArray(MMSTAMP)); RandomAccessInputStream ras = new RandomAccessInputStream(stamp); ras.order(isLittleEndian()); // each stamp is 8 doubles, representing the position on dimensions 3-10 for (int j=0; j<8; j++) { stamps[j][i] = ras.readDouble() / 1000; // correct for clock skew? int pow = -1; while (Math.pow(2, pow) < stamps[j][i]) { stamps[j][i] -= (0.032 * (Math.pow(2, pow < 0 ? 0 : pow))); pow++; } } ras.close(); } } private byte[] shortArrayToBytes(short[] s) { byte[] b = new byte[s.length]; for (int i=0; i<s.length; i++) { b[i] = (byte) s[i]; if (b[i] < 0) b[i]++; } return b; } private void parseComment() { if (comment != null) { // this is an INI-style comment, with one key/value pair per line String[] lines = comment.split("\n"); for (String token : lines) { token = token.trim(); int eq = token.indexOf("="); if (eq != -1) { String key = token.substring(0, eq); String value = token.substring(eq + 1); addGlobalMeta(key, value); if (key.startsWith("Gain Ch")) { for (int i=0; i<gains.length; i++) { if (gains[i] == null) { gains[i] = value; break; } } } else if (key.startsWith("PMT Voltage Ch")) { for (int i=0; i<voltages.length; i++) { if (voltages[i] == null) { voltages[i] = value; break; } } } else if (key.startsWith("Offset Ch")) { for (int i=0; i<offsets.length; i++) { if (offsets[i] == null) { offsets[i] = value; break; } } } else if (key.equals("Magnification")) mag = value; else if (key.equals("System Configuration")) { detectorManufacturer = value; } else if (key.equals("Objective Lens")) objectiveManufacturer = value; else if (key.startsWith("Channel ") && key.endsWith("Dye")) { for (int i=0; i<channelNames.length; i++) { if (channelNames[i] == null) { channelNames[i] = value; break; } } } else if (key.startsWith("Confocal Aperture-Ch")) { for (int i=0; i<lensNA.length; i++) { if (lensNA[i] == null) { lensNA[i] = value.substring(0, value.length() - 2); break; } } } else if (key.equals("Date")) { date = value; } else if (key.equals("Time")) { date += " " + value; } } else if (token.startsWith("Z") && token.indexOf(" um ") != -1) { // looking for "Z - x um in y planes" String z = token.substring(token.indexOf("-") + 1); z = z.replaceAll("\\p{Alpha}", "").trim(); int firstSpace = z.indexOf(" "); double size = Double.parseDouble(z.substring(0, firstSpace)); double nPlanes = Double.parseDouble(z.substring(firstSpace).trim()); voxelZ = size / nPlanes; } } if (date != null) { date = DateTools.formatDate(date.trim(), new String[] {"MM/dd/yyyy hh:mm:ss a", "MM-dd-yyyy hh:mm:ss"}, true); if (timeIndex >= 0 && date != null) { long ms = DateTools.getTime(date, DateTools.ISO8601_FORMAT); int nChars = String.valueOf(getImageCount()).length(); for (int i=0; i<getImageCount(); i++) { int[] zct = getZCTCoords(i); String key = String.format( "Timestamp for Z=%2s, C=%2s, T=%2s", zct[0], zct[1], zct[2]); long stamp = ms + (long) (stamps[timeIndex][i] * 1000); addGlobalMeta(key, DateTools.convertDate(stamp, DateTools.UNIX, DATE_FORMAT)); } } } int start = comment.indexOf("[Version Info]"); int end = comment.indexOf("[Version Info End]"); if (start != -1 && end != -1 && end > start) { comment = comment.substring(start + 14, end).trim(); start = comment.indexOf("=") + 1; end = comment.indexOf("\n"); if (end > start) comment = comment.substring(start, end).trim(); else comment = comment.substring(start).trim(); } else comment = ""; } } }
Parse XY dimensions from IFD.PAGE_NAME entry, if present.
components/bio-formats/src/loci/formats/in/FluoviewReader.java
Parse XY dimensions from IFD.PAGE_NAME entry, if present.
<ide><path>omponents/bio-formats/src/loci/formats/in/FluoviewReader.java <ide> channelNames = new String[getSizeC()]; <ide> lensNA = new String[getSizeC()]; <ide> <add> parsePageName(); <ide> parseComment(); <ide> addGlobalMeta("Comment", comment); <ide> } <ide> if (b[i] < 0) b[i]++; <ide> } <ide> return b; <add> } <add> <add> private void parsePageName() { <add> String pageName = ifds.get(0).getIFDTextValue(IFD.PAGE_NAME); <add> if (pageName == null) return; <add> String[] lines = pageName.split("\n"); <add> for (String line : lines) { <add> if (line.startsWith("Resolution")) { <add> String[] resolutions = line.split("\t"); <add> if (resolutions.length > 1) { <add> voxelX = Double.parseDouble(resolutions[1].trim()); <add> } <add> if (resolutions.length > 2) { <add> voxelY = Double.parseDouble(resolutions[2].trim()); <add> } <add> <add> break; <add> } <add> } <ide> } <ide> <ide> private void parseComment() {
Java
bsd-3-clause
763d301e9229536e70863a959d4d556cb9bce16c
0
exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent,exponentjs/exponent,exponentjs/exponent,exponent/exponent,exponent/exponent,exponent/exponent
package versioned.host.exp.exponent.modules.api; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.provider.MediaStore; import android.util.Base64; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableMap; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.utils.IoUtils; import com.theartofdev.edmodo.cropper.CropImage; import host.exp.exponent.ActivityResultListener; import host.exp.exponent.utils.ExpFileUtils; import host.exp.exponent.utils.ScopedContext; import host.exp.expoview.Exponent; import versioned.host.exp.exponent.ReadableObjectUtils; public class ImagePickerModule extends ReactContextBaseJavaModule implements ActivityResultListener { static final int REQUEST_LAUNCH_CAMERA = 1; static final int REQUEST_LAUNCH_IMAGE_LIBRARY = 2; private Uri mCameraCaptureURI; private Promise mPromise; private Boolean mLaunchedCropper = false; final String OPTION_QUALITY = "quality"; final String OPTION_ALLOWS_EDITING = "allowsEditing"; final String OPTION_ASPECT = "aspect"; final String OPTION_BASE64 = "base64"; private int quality = 100; private Boolean allowsEditing = false; private ReadableArray forceAspect = null; private Boolean base64 = false; private ScopedContext mScopedContext; public ImagePickerModule(ReactApplicationContext reactContext, ScopedContext scopedContext) { super(reactContext); mScopedContext = scopedContext; Exponent.getInstance().addActivityResultListener(this); } @Override public String getName() { return "ExponentImagePicker"; } private boolean readOptions(final ReadableMap options, final Promise promise) { if (options.hasKey(OPTION_QUALITY)) { quality = (int) (options.getDouble(OPTION_QUALITY) * 100); } if (options.hasKey(OPTION_ALLOWS_EDITING)) { allowsEditing = options.getBoolean(OPTION_ALLOWS_EDITING); } if (options.hasKey(OPTION_ASPECT)) { forceAspect = options.getArray(OPTION_ASPECT); if (forceAspect.size() != 2 || forceAspect.getType(0) != ReadableType.Number || forceAspect.getType(1) != ReadableType.Number) { promise.reject(new IllegalArgumentException("'aspect option must be of form [Number, Number]")); return false; } } if (options.hasKey(OPTION_BASE64)) { base64 = options.getBoolean(OPTION_BASE64); } return true; } // NOTE: Currently not reentrant / doesn't support concurrent requests @ReactMethod public void launchCameraAsync(final ReadableMap options, final Promise promise) { if (!readOptions(options, promise)) { return; } final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(Exponent.getInstance().getApplication().getPackageManager()) == null) { promise.reject(new IllegalStateException("Error resolving activity")); return; } Exponent.getInstance().getPermissions(new Exponent.PermissionsListener() { @Override public void permissionsGranted() { launchCameraWithPermissionsGranted(promise, cameraIntent); } @Override public void permissionsDenied() { promise.reject(new SecurityException("User rejected permissions")); } }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}); } private void launchCameraWithPermissionsGranted(Promise promise, Intent cameraIntent) { File imageFile; try { imageFile = File.createTempFile("exponent_capture_", ".jpg", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)); } catch (IOException e) { e.printStackTrace(); return; } if (imageFile == null) { promise.reject(new IOException("Could not create temporary image file.")); return; } cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, ExpFileUtils.uriFromFile(imageFile)); mCameraCaptureURI = ExpFileUtils.uriFromFile(imageFile); mPromise = promise; Exponent.getInstance().getCurrentActivity().startActivityForResult(cameraIntent, REQUEST_LAUNCH_CAMERA); } // NOTE: Currently not reentrant / doesn't support concurrent requests @ReactMethod public void launchImageLibraryAsync(final ReadableMap options, final Promise promise) { if (!readOptions(options, promise)) { return; } Exponent.getInstance().getPermissions(new Exponent.PermissionsListener() { @Override public void permissionsGranted() { launchImageLibraryWithPermissionsGranted(promise); } @Override public void permissionsDenied() { promise.reject(new SecurityException("User rejected permissions.")); } }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}); } private void launchImageLibraryWithPermissionsGranted(Promise promise) { Intent libraryIntent = new Intent(); libraryIntent.setType("image/*"); libraryIntent.setAction(Intent.ACTION_GET_CONTENT); mPromise = promise; Exponent.getInstance().getCurrentActivity().startActivityForResult(libraryIntent, REQUEST_LAUNCH_IMAGE_LIBRARY); } public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { if (mLaunchedCropper) { mLaunchedCropper = false; final Promise promise = mPromise; mPromise = null; if (promise == null) { return; } if (resultCode != Activity.RESULT_OK) { WritableMap response = Arguments.createMap(); response.putBoolean("cancelled", true); promise.resolve(response); return; } CropImage.ActivityResult result = CropImage.getActivityResult(intent); WritableMap response = Arguments.createMap(); response.putString("uri", result.getUri().toString()); int rot = result.getRotation() % 360; if (rot < 0) { rot += 360; } if (rot == 0 || rot == 180) { // Rotation is right-angled only response.putInt("width", result.getCropRect().width()); response.putInt("height", result.getCropRect().height()); } else { response.putInt("width", result.getCropRect().height()); response.putInt("height", result.getCropRect().width()); } if (base64) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { // `CropImage` nullifies the `result.getBitmap()` after it writes out to a file, so // we have to read back... InputStream in = new FileInputStream(result.getUri().getPath()); IoUtils.copyStream(in, out, null); response.putString("base64", Base64.encodeToString(out.toByteArray(), Base64.DEFAULT)); } catch(IOException e) { promise.reject(e); } } response.putBoolean("cancelled", false); promise.resolve(response); } return; } if (mPromise == null || (mCameraCaptureURI == null && requestCode == REQUEST_LAUNCH_CAMERA) || (requestCode != REQUEST_LAUNCH_CAMERA && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY)) { return; } final Promise promise = mPromise; mPromise = null; // User cancel if (resultCode != Activity.RESULT_OK) { WritableMap response = Arguments.createMap(); response.putBoolean("cancelled", true); promise.resolve(response); return; } AsyncTask.execute(new Runnable() { @Override public void run() { try { Uri uri = requestCode == REQUEST_LAUNCH_CAMERA ? mCameraCaptureURI : intent.getData(); if (allowsEditing) { mLaunchedCropper = true; mPromise = promise; // Need promise again later CropImage.ActivityBuilder cropImage = CropImage.activity(uri); if (forceAspect != null) { cropImage .setAspectRatio(forceAspect.getInt(0), forceAspect.getInt(1)) .setFixAspectRatio(true) .setInitialCropWindowPaddingRatio(0); } cropImage .setOutputUri(ExpFileUtils.uriFromFile(new File(generateOutputPath()))) .setOutputCompressQuality(quality) .start(Exponent.getInstance().getCurrentActivity()); } else { // On some devices this has worked without decoding the URI and on some it has worked // with decoding, so we try both... // The `.cacheOnDisk(true)` and `.considerExifParams(true)` is to reflect EXIF rotation // metadata. // See https://github.com/nostra13/Android-Universal-Image-Loader/issues/630#issuecomment-204338289 String beforeDecode = uri.toString(); String afterDecode = Uri.decode(beforeDecode); Bitmap bmp = null; try { bmp = ImageLoader.getInstance().loadImageSync(afterDecode, new DisplayImageOptions.Builder() .cacheOnDisk(true) .considerExifParams(true) .build()); } catch (Throwable e) {} if (bmp == null) { try { bmp = ImageLoader.getInstance().loadImageSync(beforeDecode, new DisplayImageOptions.Builder() .cacheOnDisk(true) .considerExifParams(true) .build()); } catch (Throwable e) {} } if (bmp == null) { promise.reject(new IllegalStateException("Image decoding failed.")); return; } String path = writeImage(bmp); WritableMap response = Arguments.createMap(); response.putString("uri", ExpFileUtils.uriFromFile(new File(path)).toString()); if (base64) { ByteArrayOutputStream out = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, quality, out); response.putString("base64", Base64.encodeToString(out.toByteArray(), Base64.DEFAULT)); } response.putInt("width", bmp.getWidth()); response.putInt("height", bmp.getHeight()); response.putBoolean("cancelled", false); promise.resolve(response); } } catch (Exception e) { e.printStackTrace(); } } }); } private String generateOutputPath() throws IOException { String filename = UUID.randomUUID().toString(); WritableMap options = Arguments.createMap(); options.putBoolean("cache", true); File directory = new File(mScopedContext.toScopedPath("ImagePicker", ReadableObjectUtils.readableToJson(options))); ExpFileUtils.ensureDirExists(directory); return directory + File.separator + filename + ".jpg"; } private String writeImage(Bitmap image) { FileOutputStream out = null; String path = null; try { path = generateOutputPath(); out = new FileOutputStream(path); image.compress(Bitmap.CompressFormat.JPEG, quality, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return path; } }
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/ImagePickerModule.java
package versioned.host.exp.exponent.modules.api; import android.Manifest; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Environment; import android.provider.MediaStore; import android.util.Base64; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableMap; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.utils.IoUtils; import com.theartofdev.edmodo.cropper.CropImage; import host.exp.exponent.ActivityResultListener; import host.exp.exponent.utils.ExpFileUtils; import host.exp.exponent.utils.ScopedContext; import host.exp.expoview.Exponent; import versioned.host.exp.exponent.ReadableObjectUtils; public class ImagePickerModule extends ReactContextBaseJavaModule implements ActivityResultListener { static final int REQUEST_LAUNCH_CAMERA = 1; static final int REQUEST_LAUNCH_IMAGE_LIBRARY = 2; private Uri mCameraCaptureURI; private Promise mPromise; private Boolean mLaunchedCropper = false; final String OPTION_QUALITY = "quality"; final String OPTION_ALLOWS_EDITING = "allowsEditing"; final String OPTION_ASPECT = "aspect"; final String OPTION_BASE64 = "base64"; private int quality = 100; private Boolean allowsEditing = false; private ReadableArray forceAspect = null; private Boolean base64 = false; private ScopedContext mScopedContext; public ImagePickerModule(ReactApplicationContext reactContext, ScopedContext scopedContext) { super(reactContext); mScopedContext = scopedContext; Exponent.getInstance().addActivityResultListener(this); } @Override public String getName() { return "ExponentImagePicker"; } private boolean readOptions(final ReadableMap options, final Promise promise) { if (options.hasKey(OPTION_QUALITY)) { quality = (int) (options.getDouble(OPTION_QUALITY) * 100); } if (options.hasKey(OPTION_ALLOWS_EDITING)) { allowsEditing = options.getBoolean(OPTION_ALLOWS_EDITING); } if (options.hasKey(OPTION_ASPECT)) { forceAspect = options.getArray(OPTION_ASPECT); if (forceAspect.size() != 2 || forceAspect.getType(0) != ReadableType.Number || forceAspect.getType(1) != ReadableType.Number) { promise.reject(new IllegalArgumentException("'aspect option must be of form [Number, Number]")); return false; } } if (options.hasKey(OPTION_BASE64)) { base64 = options.getBoolean(OPTION_BASE64); } return true; } // NOTE: Currently not reentrant / doesn't support concurrent requests @ReactMethod public void launchCameraAsync(final ReadableMap options, final Promise promise) { if (!readOptions(options, promise)) { return; } final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(Exponent.getInstance().getApplication().getPackageManager()) == null) { promise.reject(new IllegalStateException("Error resolving activity")); return; } Exponent.getInstance().getPermissions(new Exponent.PermissionsListener() { @Override public void permissionsGranted() { launchCameraWithPermissionsGranted(promise, cameraIntent); } @Override public void permissionsDenied() { promise.reject(new SecurityException("User rejected permissions")); } }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}); } private void launchCameraWithPermissionsGranted(Promise promise, Intent cameraIntent) { File imageFile; try { imageFile = File.createTempFile("exponent_capture_", ".jpg", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)); } catch (IOException e) { e.printStackTrace(); return; } if (imageFile == null) { promise.reject(new IOException("Could not create temporary image file.")); return; } cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, ExpFileUtils.uriFromFile(imageFile)); mCameraCaptureURI = ExpFileUtils.uriFromFile(imageFile); mPromise = promise; Exponent.getInstance().getCurrentActivity().startActivityForResult(cameraIntent, REQUEST_LAUNCH_CAMERA); } // NOTE: Currently not reentrant / doesn't support concurrent requests @ReactMethod public void launchImageLibraryAsync(final ReadableMap options, final Promise promise) { if (!readOptions(options, promise)) { return; } Exponent.getInstance().getPermissions(new Exponent.PermissionsListener() { @Override public void permissionsGranted() { launchImageLibraryWithPermissionsGranted(promise); } @Override public void permissionsDenied() { promise.reject(new SecurityException("User rejected permissions.")); } }, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}); } private void launchImageLibraryWithPermissionsGranted(Promise promise) { Intent libraryIntent = new Intent(); libraryIntent.setType("image/*"); libraryIntent.setAction(Intent.ACTION_GET_CONTENT); mPromise = promise; Exponent.getInstance().getCurrentActivity().startActivityForResult(libraryIntent, REQUEST_LAUNCH_IMAGE_LIBRARY); } public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) { if (mLaunchedCropper) { mLaunchedCropper = false; final Promise promise = mPromise; mPromise = null; if (promise == null) { return; } if (resultCode != Activity.RESULT_OK) { WritableMap response = Arguments.createMap(); response.putBoolean("cancelled", true); promise.resolve(response); return; } CropImage.ActivityResult result = CropImage.getActivityResult(intent); WritableMap response = Arguments.createMap(); response.putString("uri", result.getUri().toString()); int rot = result.getRotation() % 360; if (rot < 0) { rot += 360; } if (rot == 0 || rot == 180) { // Rotation is right-angled only response.putInt("width", result.getCropRect().width()); response.putInt("height", result.getCropRect().height()); } else { response.putInt("width", result.getCropRect().height()); response.putInt("height", result.getCropRect().width()); } if (base64) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { // `CropImage` nullifies the `result.getBitmap()` after it writes out to a file, so // we have to read back... InputStream in = new FileInputStream(result.getUri().getPath()); IoUtils.copyStream(in, out, null); response.putString("base64", Base64.encodeToString(out.toByteArray(), Base64.DEFAULT)); } catch(IOException e) { promise.reject(e); } } response.putBoolean("cancelled", false); promise.resolve(response); } return; } if (mPromise == null || (mCameraCaptureURI == null && requestCode == REQUEST_LAUNCH_CAMERA) || (requestCode != REQUEST_LAUNCH_CAMERA && requestCode != REQUEST_LAUNCH_IMAGE_LIBRARY)) { return; } final Promise promise = mPromise; mPromise = null; // User cancel if (resultCode != Activity.RESULT_OK) { WritableMap response = Arguments.createMap(); response.putBoolean("cancelled", true); promise.resolve(response); return; } AsyncTask.execute(new Runnable() { @Override public void run() { try { Uri uri = requestCode == REQUEST_LAUNCH_CAMERA ? mCameraCaptureURI : intent.getData(); if (allowsEditing) { mLaunchedCropper = true; mPromise = promise; // Need promise again later CropImage.ActivityBuilder cropImage = CropImage.activity(uri); if (forceAspect != null) { cropImage .setAspectRatio(forceAspect.getInt(0), forceAspect.getInt(1)) .setFixAspectRatio(true) .setInitialCropWindowPaddingRatio(0); } cropImage .setOutputUri(ExpFileUtils.uriFromFile(new File(generateOutputPath()))) .start(Exponent.getInstance().getCurrentActivity()); } else { // On some devices this has worked without decoding the URI and on some it has worked // with decoding, so we try both... // The `.cacheOnDisk(true)` and `.considerExifParams(true)` is to reflect EXIF rotation // metadata. // See https://github.com/nostra13/Android-Universal-Image-Loader/issues/630#issuecomment-204338289 String beforeDecode = uri.toString(); String afterDecode = Uri.decode(beforeDecode); Bitmap bmp = null; try { bmp = ImageLoader.getInstance().loadImageSync(afterDecode, new DisplayImageOptions.Builder() .cacheOnDisk(true) .considerExifParams(true) .build()); } catch (Throwable e) {} if (bmp == null) { try { bmp = ImageLoader.getInstance().loadImageSync(beforeDecode, new DisplayImageOptions.Builder() .cacheOnDisk(true) .considerExifParams(true) .build()); } catch (Throwable e) {} } if (bmp == null) { promise.reject(new IllegalStateException("Image decoding failed.")); return; } String path = writeImage(bmp); WritableMap response = Arguments.createMap(); response.putString("uri", ExpFileUtils.uriFromFile(new File(path)).toString()); if (base64) { ByteArrayOutputStream out = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.JPEG, quality, out); response.putString("base64", Base64.encodeToString(out.toByteArray(), Base64.DEFAULT)); } response.putInt("width", bmp.getWidth()); response.putInt("height", bmp.getHeight()); response.putBoolean("cancelled", false); promise.resolve(response); } } catch (Exception e) { e.printStackTrace(); } } }); } private String generateOutputPath() throws IOException { String filename = UUID.randomUUID().toString(); WritableMap options = Arguments.createMap(); options.putBoolean("cache", true); File directory = new File(mScopedContext.toScopedPath("ImagePicker", ReadableObjectUtils.readableToJson(options))); ExpFileUtils.ensureDirExists(directory); return directory + File.separator + filename + ".jpg"; } private String writeImage(Bitmap image) { FileOutputStream out = null; String path = null; try { path = generateOutputPath(); out = new FileOutputStream(path); image.compress(Bitmap.CompressFormat.JPEG, quality, out); } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return path; } }
`ImagePickerModule`: `quality` when `allowsEditing: true` fbshipit-source-id: 205a7be
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/ImagePickerModule.java
`ImagePickerModule`: `quality` when `allowsEditing: true`
<ide><path>ndroid/expoview/src/main/java/versioned/host/exp/exponent/modules/api/ImagePickerModule.java <ide> } <ide> cropImage <ide> .setOutputUri(ExpFileUtils.uriFromFile(new File(generateOutputPath()))) <add> .setOutputCompressQuality(quality) <ide> .start(Exponent.getInstance().getCurrentActivity()); <ide> } else { <ide> // On some devices this has worked without decoding the URI and on some it has worked
JavaScript
mit
ebda9555d31695c9878cf7d2b621a693ff8f4cbf
0
kpgarrod/angular-storage
(function() { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Grunt angular.module('angular-storage', [ 'angular-storage.store' ]); angular.module('angular-storage.internalStore', ['angular-storage.storage']) .factory('InternalStore', ["storage", function(storage) { function InternalStore(namespace, delimiter) { this.namespace = namespace || null; this.delimiter = delimiter || '.'; this.inMemoryCache = {}; } InternalStore.prototype.getNamespacedKey = function(key) { if (!this.namespace) { return key; } else { return [this.namespace, key].join(this.delimiter); } } InternalStore.prototype.set = function(name, elem) { this.inMemoryCache[name] = elem; storage.set(this.getNamespacedKey(name), JSON.stringify(elem)); }; InternalStore.prototype.get = function(name) { if (name in this.inMemoryCache) { return this.inMemoryCache[name]; } var saved = storage.get(this.getNamespacedKey(name)); var obj = saved ? JSON.parse(saved) : null; this.inMemoryCache[name] = obj; return obj; }; InternalStore.prototype.remove = function(name) { this.inMemoryCache[name] = null; storage.remove(this.getNamespacedKey(name)); } return InternalStore; }]); angular.module('angular-storage.storage', []) .service('storage', ["$window", function($window) { if ($window.localStorage) { this.set = function(what, value) { return $window.localStorage.setItem(what, value); }; this.get = function(what) { return $window.localStorage.getItem(what); }; this.remove = function(what) { return $window.localStorage.removeItem(what); }; } else { var $cookieStore = $injector.get('$cookieStore'); this.set = function(what, value) { return (!what || !value) ? null : $cookieStore.put(what, value); }; this.get = function(what) { return $cookieStore.get(what); }; this.remove = function(what) { return $cookieStore.remove(what); }; } }]); angular.module('angular-storage.store', ['angular-storage.internalStore']) .factory('store', ["InternalStore", function(InternalStore) { var store = new InternalStore(); store.getNamespacedStore = function(namespace, key) { return new InternalStore(namespace, key); } return store; }]); }());
dist/angular-storage.js
(function() { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Grunt angular.module('angular-storage', [ 'angular-storage.store' ]); angular.module('angular-storage.internalStore', ['angular-storage.storage']) .factory('InternalStore', ["storage", function(storage) { function InternalStore(namespace, delimiter) { this.namespace = namespace || null; this.delimiter = delimiter || '.'; this.inMemoryCache = {}; } InternalStore.prototype.getNamespacedKey = function(key) { if (!this.namespace) { return key; } else { return [this.namespace, key].join(this.delimiter); } } InternalStore.prototype.set = function(name, elem) { this.inMemoryCache[name] = elem; storage.set(this.getNamespacedKey(name), JSON.stringify(elem)); }; InternalStore.prototype.get = function(name) { if (name in this.inMemoryCache) { return this.inMemoryCache[name]; } var saved = storage.get(this.getNamespacedKey(name)); var obj = saved ? JSON.parse(saved) : null; this.inMemoryCache[name] = obj; return obj; }; InternalStore.prototype.remove = function(name) { this.inMemoryCache[name] = null; storage.remove(this.getNamespacedKey(name)); } return InternalStore; }]); angular.module('angular-storage.storage', []) .service('storage', ["$window", function($window) { if ($window.localStorage) { this.set = function(what, value) { return $window.localStorage.setItem(what, value); }; this.get = function(what) { return $window.localStorage.getItem(what); }; this.remove = function(what) { return $window.localStorage.removeItem(what); }; } else { var $cookieStore = $injector.get('$cookieStore'); this.set = function(what, value) { return $cookieStore.put(what, value); }; this.get = function(what) { return $cookieStore.get(what); }; this.remove = function(what) { return $cookieStore.remove(what); }; } }]); angular.module('angular-storage.store', ['angular-storage.internalStore']) .factory('store', ["InternalStore", function(InternalStore) { var store = new InternalStore(); store.getNamespacedStore = function(namespace, key) { return new InternalStore(namespace, key); } return store; }]); }());
Update angular-storage.js
dist/angular-storage.js
Update angular-storage.js
<ide><path>ist/angular-storage.js <ide> } else { <ide> var $cookieStore = $injector.get('$cookieStore'); <ide> this.set = function(what, value) { <del> return $cookieStore.put(what, value); <add> return (!what || !value) ? null : $cookieStore.put(what, value); <ide> }; <ide> this.get = function(what) { <ide> return $cookieStore.get(what);
Java
apache-2.0
6676dee90a7d3d450e17b6c1235f452db52eaa5a
0
asedunov/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,youdonghai/intellij-community,kool79/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,ahb0327/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,samthor/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,robovm/robovm-studio,dslomov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,robovm/robovm-studio,xfournet/intellij-community,holmes/intellij-community,da1z/intellij-community,fitermay/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,hurricup/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,da1z/intellij-community,adedayo/intellij-community,kdwink/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,apixandru/intellij-community,fnouama/intellij-community,ibinti/intellij-community,FHannes/intellij-community,FHannes/intellij-community,petteyg/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,blademainer/intellij-community,holmes/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,samthor/intellij-community,asedunov/intellij-community,fnouama/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,jagguli/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,vladmm/intellij-community,asedunov/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,allotria/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,amith01994/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,slisson/intellij-community,adedayo/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,FHannes/intellij-community,slisson/intellij-community,holmes/intellij-community,izonder/intellij-community,da1z/intellij-community,gnuhub/intellij-community,kool79/intellij-community,asedunov/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,kool79/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,petteyg/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,holmes/intellij-community,retomerz/intellij-community,semonte/intellij-community,hurricup/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,amith01994/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,semonte/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,clumsy/intellij-community,semonte/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,slisson/intellij-community,amith01994/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,apixandru/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,blademainer/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,kool79/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,wreckJ/intellij-community,slisson/intellij-community,youdonghai/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,adedayo/intellij-community,allotria/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,fitermay/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,dslomov/intellij-community,adedayo/intellij-community,asedunov/intellij-community,allotria/intellij-community,caot/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,clumsy/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,TangHao1987/intellij-community,tmpgit/intellij-community,caot/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,jagguli/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,fitermay/intellij-community,da1z/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,signed/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,samthor/intellij-community,izonder/intellij-community,apixandru/intellij-community,holmes/intellij-community,supersven/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,izonder/intellij-community,amith01994/intellij-community,da1z/intellij-community,retomerz/intellij-community,supersven/intellij-community,jagguli/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,signed/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,diorcety/intellij-community,apixandru/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,samthor/intellij-community,kdwink/intellij-community,petteyg/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,caot/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,FHannes/intellij-community,asedunov/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,hurricup/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,caot/intellij-community,robovm/robovm-studio,vladmm/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,supersven/intellij-community,diorcety/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,clumsy/intellij-community,diorcety/intellij-community,holmes/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,slisson/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,allotria/intellij-community,signed/intellij-community,tmpgit/intellij-community,slisson/intellij-community,ryano144/intellij-community,clumsy/intellij-community,FHannes/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,petteyg/intellij-community,vladmm/intellij-community,caot/intellij-community,signed/intellij-community,retomerz/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,retomerz/intellij-community,allotria/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,izonder/intellij-community,kdwink/intellij-community,petteyg/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,signed/intellij-community,caot/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,da1z/intellij-community,fnouama/intellij-community,retomerz/intellij-community,da1z/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,kool79/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,semonte/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,signed/intellij-community,ibinti/intellij-community,izonder/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,jagguli/intellij-community,signed/intellij-community,vladmm/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,apixandru/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,diorcety/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,izonder/intellij-community,semonte/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,kdwink/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,hurricup/intellij-community,semonte/intellij-community,signed/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,supersven/intellij-community,diorcety/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,diorcety/intellij-community,semonte/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ibinti/intellij-community,ibinti/intellij-community,retomerz/intellij-community,slisson/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,clumsy/intellij-community,amith01994/intellij-community,fnouama/intellij-community,supersven/intellij-community,signed/intellij-community,holmes/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,FHannes/intellij-community,fitermay/intellij-community,petteyg/intellij-community,caot/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,supersven/intellij-community,semonte/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,adedayo/intellij-community,FHannes/intellij-community,da1z/intellij-community
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package com.intellij.openapi.editor.markup; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.DefaultJDOMExternalizer; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizerUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.containers.StripedLockConcurrentHashMap; import org.intellij.lang.annotations.JdkConstants; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.concurrent.ConcurrentMap; public class AttributesFlyweight { private static final ConcurrentMap<FlyweightKey, AttributesFlyweight> entries = new StripedLockConcurrentHashMap<FlyweightKey, AttributesFlyweight>(); private static final ThreadLocal<FlyweightKey> ourKey = new ThreadLocal<FlyweightKey>(); private final int myHashCode; private final Color myForeground; private final Color myBackground; @JdkConstants.FontStyle private final int myFontType; private final Color myEffectColor; private final EffectType myEffectType; private final Color myErrorStripeColor; private static class FlyweightKey implements Cloneable { private Color foreground; private Color background; @JdkConstants.FontStyle private int fontType; private Color effectColor; private EffectType effectType; private Color errorStripeColor; private FlyweightKey() { } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof FlyweightKey)) return false; FlyweightKey key = (FlyweightKey)o; if (fontType != key.fontType) return false; if (background != null ? !background.equals(key.background) : key.background != null) return false; if (effectColor != null ? !effectColor.equals(key.effectColor) : key.effectColor != null) return false; if (effectType != key.effectType) return false; if (errorStripeColor != null ? !errorStripeColor.equals(key.errorStripeColor) : key.errorStripeColor != null) return false; if (foreground != null ? !foreground.equals(key.foreground) : key.foreground != null) return false; return true; } @Override public int hashCode() { return calcHashCode(foreground, background, fontType, effectColor, effectType, errorStripeColor); } @Override protected FlyweightKey clone() { try { return (FlyweightKey)super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } } @NotNull public static AttributesFlyweight create(Color foreground, Color background, @JdkConstants.FontStyle int fontType, Color effectColor, EffectType effectType, Color errorStripeColor) { FlyweightKey key = ourKey.get(); if (key == null) { ourKey.set(key = new FlyweightKey()); } key.foreground = foreground; key.background = background; key.fontType = fontType; key.effectColor = effectColor; key.effectType = effectType; key.errorStripeColor = errorStripeColor; AttributesFlyweight flyweight = entries.get(key); if (flyweight != null) { return flyweight; } AttributesFlyweight newValue = new AttributesFlyweight(foreground, background, fontType, effectColor, effectType, errorStripeColor); return ConcurrencyUtil.cacheOrGet(entries, key.clone(), newValue); } private AttributesFlyweight(Color foreground, Color background, @JdkConstants.FontStyle int fontType, Color effectColor, EffectType effectType, Color errorStripeColor) { myForeground = foreground; myBackground = background; myFontType = fontType; myEffectColor = effectColor; myEffectType = effectType; myErrorStripeColor = errorStripeColor; myHashCode = calcHashCode(foreground, background, fontType, effectColor, effectType, errorStripeColor); } @NotNull public static AttributesFlyweight create(@NotNull Element element) throws InvalidDataException { Color FOREGROUND = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "FOREGROUND")); Color BACKGROUND = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "BACKGROUND")); Color EFFECT_COLOR = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "EFFECT_COLOR")); Color ERROR_STRIPE_COLOR = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "ERROR_STRIPE_COLOR")); int fontType = DefaultJDOMExternalizer.toInt(JDOMExternalizerUtil.readField(element, "FONT_TYPE", "0")); if (fontType < 0 || fontType > 3) { fontType = 0; } int FONT_TYPE = fontType; int EFFECT_TYPE = DefaultJDOMExternalizer.toInt(JDOMExternalizerUtil.readField(element, "EFFECT_TYPE", "0")); return create(FOREGROUND, BACKGROUND, FONT_TYPE, EFFECT_COLOR, toEffectType(EFFECT_TYPE), ERROR_STRIPE_COLOR); } private static void writeColor(Element element, String fieldName, Color color) { if (color != null) { String string = Integer.toString(color.getRGB() & 0xFFFFFF, 16); JDOMExternalizerUtil.writeField(element, fieldName, string); } } void writeExternal(@NotNull Element element) { writeColor(element, "FOREGROUND", getForeground()); writeColor(element, "BACKGROUND", getBackground()); int fontType = getFontType(); if (fontType != 0) { JDOMExternalizerUtil.writeField(element, "FONT_TYPE", String.valueOf(fontType)); } writeColor(element, "EFFECT_COLOR", getEffectColor()); writeColor(element, "ERROR_STRIPE_COLOR", getErrorStripeColor()); JDOMExternalizerUtil.writeField(element, "EFFECT_TYPE", String.valueOf(fromEffectType(getEffectType()))); } private static final int EFFECT_BORDER = 0; private static final int EFFECT_LINE = 1; private static final int EFFECT_WAVE = 2; private static final int EFFECT_STRIKEOUT = 3; private static final int EFFECT_BOLD_LINE = 4; private static final int EFFECT_BOLD_DOTTED_LINE = 5; private static int fromEffectType(EffectType effectType) { int EFFECT_TYPE; if (effectType == EffectType.BOXED) { EFFECT_TYPE = EFFECT_BORDER; } else if (effectType == EffectType.LINE_UNDERSCORE) { EFFECT_TYPE = EFFECT_LINE; } else if (effectType == EffectType.BOLD_LINE_UNDERSCORE) { EFFECT_TYPE = EFFECT_BOLD_LINE; } else if (effectType == EffectType.STRIKEOUT) { EFFECT_TYPE = EFFECT_STRIKEOUT; } else if (effectType == EffectType.WAVE_UNDERSCORE) { EFFECT_TYPE = EFFECT_WAVE; } else if (effectType == EffectType.BOLD_DOTTED_LINE) { EFFECT_TYPE = EFFECT_BOLD_DOTTED_LINE; } else { EFFECT_TYPE = -1; } return EFFECT_TYPE; } private static EffectType toEffectType(int effectType) { switch (effectType) { case EFFECT_BORDER: return EffectType.BOXED; case EFFECT_BOLD_LINE: return EffectType.BOLD_LINE_UNDERSCORE; case EFFECT_LINE: return EffectType.LINE_UNDERSCORE; case EFFECT_STRIKEOUT: return EffectType.STRIKEOUT; case EFFECT_WAVE: return EffectType.WAVE_UNDERSCORE; case EFFECT_BOLD_DOTTED_LINE: return EffectType.BOLD_DOTTED_LINE; default: return null; } } private static int calcHashCode(Color foreground, Color background, int fontType, Color effectColor, EffectType effectType, Color errorStripeColor) { int result = foreground != null ? foreground.hashCode() : 0; result = 31 * result + (background != null ? background.hashCode() : 0); result = 31 * result + fontType; result = 31 * result + (effectColor != null ? effectColor.hashCode() : 0); result = 31 * result + (effectType != null ? effectType.hashCode() : 0); result = 31 * result + (errorStripeColor != null ? errorStripeColor.hashCode() : 0); return result; } public Color getForeground() { return myForeground; } public Color getBackground() { return myBackground; } @JdkConstants.FontStyle public int getFontType() { return myFontType; } public Color getEffectColor() { return myEffectColor; } public EffectType getEffectType() { return myEffectType; } public Color getErrorStripeColor() { return myErrorStripeColor; } @NotNull public AttributesFlyweight withForeground(Color foreground) { return Comparing.equal(foreground, myForeground) ? this : create(foreground, myBackground, myFontType, myEffectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withBackground(Color background) { return Comparing.equal(background, myBackground) ? this : create(myForeground, background, myFontType, myEffectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withFontType(@JdkConstants.FontStyle int fontType) { return fontType == myFontType ? this : create(myForeground, myBackground, fontType, myEffectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withEffectColor(Color effectColor) { return Comparing.equal(effectColor, myEffectColor) ? this : create(myForeground, myBackground, myFontType, effectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withEffectType(EffectType effectType) { return Comparing.equal(effectType, myEffectType) ? this : create(myForeground, myBackground, myFontType, myEffectColor, effectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withErrorStripeColor(Color stripeColor) { return Comparing.equal(stripeColor, myErrorStripeColor) ? this : create(myForeground, myBackground, myFontType, myEffectColor, myEffectType, stripeColor); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AttributesFlyweight that = (AttributesFlyweight)o; if (myFontType != that.myFontType) return false; if (myBackground != null ? !myBackground.equals(that.myBackground) : that.myBackground != null) return false; if (myEffectColor != null ? !myEffectColor.equals(that.myEffectColor) : that.myEffectColor != null) return false; if (myEffectType != that.myEffectType) return false; if (myErrorStripeColor != null ? !myErrorStripeColor.equals(that.myErrorStripeColor) : that.myErrorStripeColor != null) return false; if (myForeground != null ? !myForeground.equals(that.myForeground) : that.myForeground != null) return false; return true; } @Override public int hashCode() { return myHashCode; } @NonNls @Override public String toString() { return "AttributesFlyweight{myForeground=" + myForeground + ", myBackground=" + myBackground + ", myFontType=" + myFontType + ", myEffectColor=" + myEffectColor + ", myEffectType=" + myEffectType + ", myErrorStripeColor=" + myErrorStripeColor + '}'; } }
platform/core-api/src/com/intellij/openapi/editor/markup/AttributesFlyweight.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package com.intellij.openapi.editor.markup; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.DefaultJDOMExternalizer; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizerUtil; import com.intellij.util.ConcurrencyUtil; import com.intellij.util.containers.StripedLockConcurrentHashMap; import org.intellij.lang.annotations.JdkConstants; import org.jdom.Element; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.awt.*; import java.util.concurrent.ConcurrentMap; public class AttributesFlyweight { private static final ConcurrentMap<FlyweightKey, AttributesFlyweight> entries = new StripedLockConcurrentHashMap<FlyweightKey, AttributesFlyweight>(); private static final ThreadLocal<FlyweightKey> ourKey = new ThreadLocal<FlyweightKey>(); private final int myHashCode; private final Color myForeground; private final Color myBackground; @JdkConstants.FontStyle private final int myFontType; private final Color myEffectColor; private final EffectType myEffectType; private final Color myErrorStripeColor; private static class FlyweightKey implements Cloneable { private Color foreground; private Color background; @JdkConstants.FontStyle private int fontType; private Color effectColor; private EffectType effectType; private Color errorStripeColor; private FlyweightKey() { } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof FlyweightKey)) return false; FlyweightKey key = (FlyweightKey)o; if (fontType != key.fontType) return false; if (background != null ? !background.equals(key.background) : key.background != null) return false; if (effectColor != null ? !effectColor.equals(key.effectColor) : key.effectColor != null) return false; if (effectType != key.effectType) return false; if (errorStripeColor != null ? !errorStripeColor.equals(key.errorStripeColor) : key.errorStripeColor != null) return false; if (foreground != null ? !foreground.equals(key.foreground) : key.foreground != null) return false; return true; } @Override public int hashCode() { return calcHashCode(foreground, background, fontType, effectColor, effectType, errorStripeColor); } @Override protected FlyweightKey clone() { try { return (FlyweightKey)super.clone(); } catch (CloneNotSupportedException e) { throw new RuntimeException(e); } } } @NotNull public static AttributesFlyweight create(Color foreground, Color background, @JdkConstants.FontStyle int fontType, Color effectColor, EffectType effectType, Color errorStripeColor) { FlyweightKey key = ourKey.get(); if (key == null) { ourKey.set(key = new FlyweightKey()); } key.foreground = foreground; key.background = background; key.fontType = fontType; key.effectColor = effectColor; key.effectType = effectType; key.errorStripeColor = errorStripeColor; AttributesFlyweight flyweight = entries.get(key); if (flyweight != null) { return flyweight; } AttributesFlyweight newValue = new AttributesFlyweight(foreground, background, fontType, effectColor, effectType, errorStripeColor); return ConcurrencyUtil.cacheOrGet(entries, key.clone(), newValue); } private AttributesFlyweight(Color foreground, Color background, @JdkConstants.FontStyle int fontType, Color effectColor, EffectType effectType, Color errorStripeColor) { myForeground = foreground; myBackground = background; myFontType = fontType; myEffectColor = effectColor; myEffectType = effectType; myErrorStripeColor = errorStripeColor; myHashCode = calcHashCode(foreground, background, fontType, effectColor, effectType, errorStripeColor); } @NotNull public static AttributesFlyweight create(@NotNull Element element) throws InvalidDataException { Color FOREGROUND = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "FOREGROUND")); Color BACKGROUND = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "BACKGROUND")); Color EFFECT_COLOR = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "EFFECT_COLOR")); Color ERROR_STRIPE_COLOR = DefaultJDOMExternalizer.toColor(JDOMExternalizerUtil.readField(element, "ERROR_STRIPE_COLOR")); int fontType = DefaultJDOMExternalizer.toInt(JDOMExternalizerUtil.readField(element, "FONT_TYPE", "0")); if (fontType < 0 || fontType > 3) { fontType = 0; } int FONT_TYPE = fontType; int EFFECT_TYPE = DefaultJDOMExternalizer.toInt(JDOMExternalizerUtil.readField(element, "EFFECT_TYPE", "0")); return new AttributesFlyweight(FOREGROUND, BACKGROUND, FONT_TYPE, EFFECT_COLOR, toEffectType(EFFECT_TYPE), ERROR_STRIPE_COLOR); } private static void writeColor(Element element, String fieldName, Color color) { if (color != null) { String string = Integer.toString(color.getRGB() & 0xFFFFFF, 16); JDOMExternalizerUtil.writeField(element, fieldName, string); } } void writeExternal(@NotNull Element element) { writeColor(element, "FOREGROUND", getForeground()); writeColor(element, "BACKGROUND", getBackground()); int fontType = getFontType(); if (fontType != 0) { JDOMExternalizerUtil.writeField(element, "FONT_TYPE", String.valueOf(fontType)); } writeColor(element, "EFFECT_COLOR", getEffectColor()); writeColor(element, "ERROR_STRIPE_COLOR", getErrorStripeColor()); JDOMExternalizerUtil.writeField(element, "EFFECT_TYPE", String.valueOf(fromEffectType(getEffectType()))); } private static final int EFFECT_BORDER = 0; private static final int EFFECT_LINE = 1; private static final int EFFECT_WAVE = 2; private static final int EFFECT_STRIKEOUT = 3; private static final int EFFECT_BOLD_LINE = 4; private static final int EFFECT_BOLD_DOTTED_LINE = 5; private static int fromEffectType(EffectType effectType) { int EFFECT_TYPE; if (effectType == EffectType.BOXED) { EFFECT_TYPE = EFFECT_BORDER; } else if (effectType == EffectType.LINE_UNDERSCORE) { EFFECT_TYPE = EFFECT_LINE; } else if (effectType == EffectType.BOLD_LINE_UNDERSCORE) { EFFECT_TYPE = EFFECT_BOLD_LINE; } else if (effectType == EffectType.STRIKEOUT) { EFFECT_TYPE = EFFECT_STRIKEOUT; } else if (effectType == EffectType.WAVE_UNDERSCORE) { EFFECT_TYPE = EFFECT_WAVE; } else if (effectType == EffectType.BOLD_DOTTED_LINE) { EFFECT_TYPE = EFFECT_BOLD_DOTTED_LINE; } else { EFFECT_TYPE = -1; } return EFFECT_TYPE; } private static EffectType toEffectType(int effectType) { switch (effectType) { case EFFECT_BORDER: return EffectType.BOXED; case EFFECT_BOLD_LINE: return EffectType.BOLD_LINE_UNDERSCORE; case EFFECT_LINE: return EffectType.LINE_UNDERSCORE; case EFFECT_STRIKEOUT: return EffectType.STRIKEOUT; case EFFECT_WAVE: return EffectType.WAVE_UNDERSCORE; case EFFECT_BOLD_DOTTED_LINE: return EffectType.BOLD_DOTTED_LINE; default: return null; } } private static int calcHashCode(Color foreground, Color background, int fontType, Color effectColor, EffectType effectType, Color errorStripeColor) { int result = foreground != null ? foreground.hashCode() : 0; result = 31 * result + (background != null ? background.hashCode() : 0); result = 31 * result + fontType; result = 31 * result + (effectColor != null ? effectColor.hashCode() : 0); result = 31 * result + (effectType != null ? effectType.hashCode() : 0); result = 31 * result + (errorStripeColor != null ? errorStripeColor.hashCode() : 0); return result; } public Color getForeground() { return myForeground; } public Color getBackground() { return myBackground; } @JdkConstants.FontStyle public int getFontType() { return myFontType; } public Color getEffectColor() { return myEffectColor; } public EffectType getEffectType() { return myEffectType; } public Color getErrorStripeColor() { return myErrorStripeColor; } @NotNull public AttributesFlyweight withForeground(Color foreground) { return Comparing.equal(foreground, myForeground) ? this : create(foreground, myBackground, myFontType, myEffectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withBackground(Color background) { return Comparing.equal(background, myBackground) ? this : create(myForeground, background, myFontType, myEffectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withFontType(@JdkConstants.FontStyle int fontType) { return fontType == myFontType ? this : create(myForeground, myBackground, fontType, myEffectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withEffectColor(Color effectColor) { return Comparing.equal(effectColor, myEffectColor) ? this : create(myForeground, myBackground, myFontType, effectColor, myEffectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withEffectType(EffectType effectType) { return Comparing.equal(effectType, myEffectType) ? this : create(myForeground, myBackground, myFontType, myEffectColor, effectType, myErrorStripeColor); } @NotNull public AttributesFlyweight withErrorStripeColor(Color stripeColor) { return Comparing.equal(stripeColor, myErrorStripeColor) ? this : create(myForeground, myBackground, myFontType, myEffectColor, myEffectType, stripeColor); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AttributesFlyweight that = (AttributesFlyweight)o; if (myFontType != that.myFontType) return false; if (myBackground != null ? !myBackground.equals(that.myBackground) : that.myBackground != null) return false; if (myEffectColor != null ? !myEffectColor.equals(that.myEffectColor) : that.myEffectColor != null) return false; if (myEffectType != that.myEffectType) return false; if (myErrorStripeColor != null ? !myErrorStripeColor.equals(that.myErrorStripeColor) : that.myErrorStripeColor != null) return false; if (myForeground != null ? !myForeground.equals(that.myForeground) : that.myForeground != null) return false; return true; } @Override public int hashCode() { return myHashCode; } @NonNls @Override public String toString() { return "AttributesFlyweight{myForeground=" + myForeground + ", myBackground=" + myBackground + ", myFontType=" + myFontType + ", myEffectColor=" + myEffectColor + ", myEffectType=" + myEffectType + ", myErrorStripeColor=" + myErrorStripeColor + '}'; } }
there should be only one call to constructor and it should be done from static create method
platform/core-api/src/com/intellij/openapi/editor/markup/AttributesFlyweight.java
there should be only one call to constructor and it should be done from static create method
<ide><path>latform/core-api/src/com/intellij/openapi/editor/markup/AttributesFlyweight.java <ide> /* <del> * Copyright 2000-2013 JetBrains s.r.o. <add> * Copyright 2000-2014 JetBrains s.r.o. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> int FONT_TYPE = fontType; <ide> int EFFECT_TYPE = DefaultJDOMExternalizer.toInt(JDOMExternalizerUtil.readField(element, "EFFECT_TYPE", "0")); <ide> <del> return new AttributesFlyweight(FOREGROUND, BACKGROUND, FONT_TYPE, EFFECT_COLOR, toEffectType(EFFECT_TYPE), ERROR_STRIPE_COLOR); <add> return create(FOREGROUND, BACKGROUND, FONT_TYPE, EFFECT_COLOR, toEffectType(EFFECT_TYPE), ERROR_STRIPE_COLOR); <ide> } <ide> <ide> private static void writeColor(Element element, String fieldName, Color color) {
JavaScript
mit
53a647177c79301859c0442f741251de56870138
0
TukekeSoft/enchant.js,wise9/enchant.js,shellkana/enchant.js,TukekeSoft/enchant.js,shellkana/enchant.js,li0t/enchant.js,wendelas/enchant.js,wise9/enchant.js,Gunbard/enchant.js,wendelas/enchant.js,Gunbard/enchant.js,li0t/enchant.js
/* [lang:ja] * gl.enchant.js * @version 0.3.6 * @require enchant.js v0.4.5+ * @require gl-matrix.js 1.3.7+ * @author Ubiquitous Entertainment Inc. * * @description * WebGLを用いた描画ライブラリ * enchant.js と組み合わせることで高度な3D描画と、2D描画を組み合わせることができる * * @detail * ベクトル・行列演算にgl-matrix.jsを使用しています. * gl-matrix.js: * https://github.com/toji/gl-matrix/ * [/lang] [lang:en] * gl.enchant.js * @version 0.3.6 * @require enchant.js v0.4.5+ * @require gl-matrix.js 1.3.7+ * @author Ubiquitous Entertainment Inc. * * @description * Drawing library using WebGL * By combining with enchant.js, high quality 3D drawing and combination with 2D drawing is possible * * @detail * Uses gl-matrix.js in vector, matrix operation. * gl-matrix.js: * https://github.com/toji/gl-matrix/ * [/lang] */ /** [lang:ja] * enchantにgl.enchant.jsのクラスをエクスポートする. [/lang] [lang:en] * Exports gl.enchant.js class to enchant. [/lang] */ enchant.gl = {}; (function() { var CONTEXT_NAME = 'experimental-webgl'; var parentModule = null; (function() { enchant(); if (enchant.nineleap != undefined) { if (enchant.nineleap.memory != undefined && Object.getPrototypeOf(enchant.nineleap.memory) == Object.prototype) { parentModule = enchant.nineleap.memory; } else if (enchant.nineleap != undefined && Object.getPrototypeOf(enchant.nineleap) == Object.prototype) { parentModule = enchant.nineleap; } } else { parentModule = enchant; } })(); enchant.gl.Game = enchant.Class.create(parentModule.Game, { initialize: function(width, height) { parentModule.Game.call(this, width, height); this.GL = new GLUtil(); this.currentScene3D = null; this.addEventListener('enterframe', function(e) { if (!this.currentScene3D) { return; } var nodes = this.currentScene3D.childNodes.slice(); var push = Array.prototype.push; while (nodes.length) { var node = nodes.pop(); node.dispatchEvent(e); node.age++; if (node.childNodes) { push.apply(nodes, node.childNodes); } } }); }, debug: function() { this.GL._enableDebugContext(); this._debug = true; this.addEventListener("enterframe", function(time) { this._actualFps = (1000 / time.elapsed); }); this.start(); } }); var GLUtil = enchant.Class.create({ initialize: function() { var game = enchant.Game.instance; if (typeof game.GL != 'undefined') { return game.GL; } this._canvas; this._gl; this._createStage(game.width, game.height, game.scale); this._prepare(); this.textureManager = new TextureManager(); this.detectColorManager = new DetectColorManager(); this.detectFrameBuffer = new enchant.gl.FrameBuffer(game.width, game.height); this.currentProgram; this.defaultProgram = new enchant.gl.Shader(DEFAULT_VERTEX_SHADER_SOURCE, DEFAULT_FRAGMENT_SHADER_SOURCE); this.setDefaultProgram(); }, setDefaultProgram: function() { this.setProgram(this.defaultProgram); }, setProgram: function(program) { program.use(); this.currentProgram = program; }, _prepare: function() { var width = this._canvas.width; var height = this._canvas.height; gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.viewport(0, 0, width, height); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); }, _createStage: function(width, height, scale) { var div = createParentDiv(); var that = this; var stage = document.getElementById('enchant-stage'); var cvs = this._canvas = createGLCanvas(width, height, scale); var detect = new enchant.Sprite(width, height); var game = enchant.Game.instance; (function() { var color = new Uint8Array(4); var touching = null; var sprite; detect.addEventListener('touchstart', function(e) { var scene = game.currentScene3D; var x = parseInt(e.x); var y = parseInt(this.height - e.y); that.detectFrameBuffer.bind(); scene._draw('detect'); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, color); sprite = that.detectColorManager.getSpriteByColor(color); if (sprite) { touching = sprite; touching.dispatchEvent(e); } that.detectFrameBuffer.unbind(); }); detect.addEventListener('touchmove', function(e) { if (touching != null) { touching.dispatchEvent(e); } }); detect.addEventListener('touchend', function(e) { if (touching != null) { touching.dispatchEvent(e); } touching = null; }); })(); window['gl'] = this._gl = this._getContext(cvs); div.appendChild(cvs); stage.insertBefore(div, game.rootScene._element); game.rootScene.addChild(detect); }, _getContext: function(canvas, debug) { var ctx = canvas.getContext(CONTEXT_NAME); if (!ctx) { alert('could not initialized WebGL'); throw new Error('could not initialized WebGL'); } if (debug) { ctx = createDebugContext(ctx); } return ctx; }, _enableDebugContext: function() { window['gl'] = this._gl = createDebugContext(this._gl); }, parseColor: function(string) { return parseColor(string); }, renderElements: function(buffer, offset, length, attributes, uniforms) { if (attributes) { this.currentProgram.setAttributes(attributes); } if (uniforms) { this.currentProgram.setUniforms(uniforms); } buffer.bind(); gl.drawElements(gl.TRIANGLES, length, gl.UNSIGNED_SHORT, offset); buffer.unbind(); } }); var parseColor = function(string) { var color = []; if (typeof string == 'string') { if (string.match(/#/)) { string.match(/[0-9a-fA-F]{2}/g).forEach(function(n) { color[color.length] = ('0x' + n - 0) / 255; }); color[color.length] = 1.0; } else if (string.match(/rgba/)) { string.match(/[0-9]{1,3},/g).forEach(function(n) { color[color.length] = parseInt(n, 10) / 255; }); color[color.length] = parseFloat(string.match(/[0-9]\.[0-9]{1,}/)[0]); } else if (string.match(/rgb/)) { string.match(/[0-9]{1,3},/g).forEach(function(n) { color[color.length] = parseInt(n, 10) / 255; }); color[color.length] = 1.0; } } else if (string instanceof Array) { color = string; } return color; }; var createDebugContext = function(context) { var ctx = {}; var names = {}; var type = ''; var val; for (var prop in context) if(context.hasOwnProperty(prop)) { type = typeof context[prop]; val = context[prop]; if (type == 'function') { ctx[prop] = (function(context, prop) { return function() { var value, error; value = context[prop].apply(context, arguments); error = context.getError(); if (error) { console.log(names[error] + '(' + error + ')' + ': ' + prop); console.log(arguments); } return value; } })(context, prop); } else if (type == 'number') { names[val] = prop; ctx[prop] = val; } else { ctx[prop] = val; } } ctx.getNameById = function(i) { return names[i]; }; return ctx; }; var createParentDiv = function() { var div = document.createElement('div'); div.style['position'] = 'absolute'; div.style['z-index'] = -1; div.style[enchant.ENV.VENDOR_PREFIX + 'TransformOrigin'] = '0 0'; return div; }; var createGLCanvas = function(width, height, scale) { var cvs = document.createElement('canvas'); cvs.width = width; cvs.height = height; cvs.style['position'] = 'absolute'; cvs.style['z-index'] = -1; cvs.style[enchant.ENV.VENDOR_PREFIX + 'Transform'] = 'scale(' + scale + ')'; cvs.style[enchant.ENV.VENDOR_PREFIX + 'TransformOrigin'] = '0 0'; return cvs; }; var TextureManager = enchant.Class.create({ initialize: function() { this.storage = {}; }, hasTexture: function(src) { return src in this.storage; }, getWebGLTexture: function(image, flip, wrap, mipmap) { var ret; if (this.hasTexture(image.src)) { ret = this.storage[image.src]; } else { ret = this.createWebGLTexture(image, flip, wrap, mipmap); } return ret; }, isPowerOfTwo: function(n) { return (n > 0) && ((n & (n - 1)) == 0); }, setTextureParameter: function(power, target, wrap, mipmap) { var filter; if (mipmap) { filter = gl.LINEAR_MIPMAP_LINEAR; } else { filter = gl.NEAREST; } if (!power) { wrap = gl.CLAMP_TO_EDGE; } gl.texParameteri(target, gl.TEXTURE_WRAP_S, wrap); gl.texParameteri(target, gl.TEXTURE_WRAP_T, wrap); gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filter); gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filter); }, _texImage: function(image, target) { gl.texImage2D(target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); }, _writeWebGLTexture: function(image, target, wrap, mipmap) { var power = this.isPowerOfTwo(image.width) && this.isPowerOfTwo(image.height); if (typeof target == 'undefined') { target = gl.TEXTURE_2D; } if (typeof wrap == 'undefined') { wrap = gl.REPEAT; } this.setTextureParameter(power, target, wrap, mipmap); this._texImage(image, target); if (mipmap) { gl.generateMipmap(target); } }, createWebGLTexture: function(image, flip, wrap, mipmap) { var tex = gl.createTexture(); var target = gl.TEXTURE_2D; gl.bindTexture(target, tex); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flip); this._writeWebGLTexture(image, target, wrap, mipmap); gl.bindTexture(target, null); this.storage[image.src] = tex; return tex; }, createWebGLCubeMapTexture: function(images, wrap, mipmap) { var faceTargets = [ gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ]; var tex = gl.createTexture(); var target, image; gl.bindTexture(gl.TEXTURE_CUBE_MAP, tex); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); for (var i = 0, l = images.length; i < l; i++) { target = faceTargets[i]; image = images[i]; this._writeWebGLTexture(image, target, wrap, mipmap); } gl.bindTexture(gl.TEXTURE_CUBE_MAP, null); return tex; } }); var DetectColorManager = enchant.Class.create({ initialize: function() { this.reference = new Array(); this.detectColorNum = 0; }, attachDetectColor: function(sprite) { this.detectColorNum += 1; this.reference[this.detectColorNum] = sprite; return this._createNewColor(); }, _createNewColor: function() { var n = this.detectColorNum; return [ parseInt(n / 65536) / 255, parseInt(n / 256) / 255, parseInt(n % 256) / 255, 1.0 ]; }, _decodeDetectColor: function(color) { return ~~(color[0] * 65536) + ~~(color[1] * 256) + ~~(color[2]); }, getSpriteByColor: function(color) { return this.reference[this._decodeDetectColor(color)]; } }); /** [lang:ja] * @scope enchant.gl.FrameBuffer.prototype [/lang] [lang:en] * @scope enchant.gl.Framebuffer.prototype [/lang] */ enchant.gl.FrameBuffer = enchant.Class.create({ /** [lang:ja] * WebGLのフレームバッファを管理するクラス. * @param {String} width フレームバッファの横幅 * @param {String} height フレームバッファの縦幅 * @constructs [/lang] [lang:en] * Class for controlling WebGL frame buffers * @param {String} width Frame buffer width * @param {String} height Frame buffer height * @constructs [/lang] */ initialize: function(width, height) { var game = enchant.Game.instance; if (typeof width == 'undefined') { width = game.width; } if (typeof height == 'undefined') { height = game.height; } this.framebuffer = gl.createFramebuffer(); this.colorbuffer = gl.createRenderbuffer(); this.depthbuffer = gl.createRenderbuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); gl.bindRenderbuffer(gl.RENDERBUFFER, this.colorbuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, width, height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, this.colorbuffer); gl.bindRenderbuffer(gl.RENDERBUFFER, this.depthbuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.depthbuffer); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); }, /** [lang:ja] * フレームバッファをバインドする. [/lang] [lang:en] * Bind frame buffer. [/lang] */ bind: function() { gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); }, /** [lang:ja] * フレームバッファをアンバインドする. [/lang] [lang:en] * Unbind frame buffer. [/lang] */ unbind: function() { gl.bindFramebuffer(gl.FRAMEBUFFER, null); }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { gl.deleteFramebuffer(this.framebuffer); gl.deleteFramebuffer(this.colorbuffer); gl.deleteFramebuffer(this.depthbuffer); delete this; } }); /** [lang:ja] * @scope enchant.gl.Shader.prototype [/lang] [lang:en] * @scope enchant.gl.Shader.prototype [/lang] */ enchant.gl.Shader = enchant.Class.create({ /** [lang:ja] * WebGLのシェーダプログラムを管理するクラス. * バーテックスシェーダのソースとフラグメントシェーダのソースを渡すことでシェーダプログラムが作成される. * @param {String} vshader バーテックスシェーダのソース * @param {String} fshader フラグメントシェーダのソース * @constructs [/lang] [lang:en] * Class to control WebGL shader program. * A shader program will be created by delivering the vertex shader source and fragment shader source. * @param {String} vshader Vertex shader source * @param {String} fshader Fragment shader source * @constructs [/lang] */ initialize: function(vshader, fshader) { this._vShaderSource = ''; this._fShaderSource = ''; this._updatedVShaderSource = false; this._updatedFShaderSource = false; this._vShaderProgram = null; this._fShaderProgram = null; this._program = null; this._uniforms = {}; this._attributes = {}; this._attribLocs = {}; this._samplersNum = 0; if (typeof vshader == 'string') { this.vShaderSource = vshader; } if (typeof fshader == 'string') { this.fShaderSource = fshader; } if (this._updatedVShaderSource && this._updatedFShaderSource) { this.compile(); } }, /** [lang:ja] * バーテックスシェーダのソース * @type String [/lang] [lang:en] * Vertex shader source * @type String [/lang] */ vShaderSource: { get: function() { return this._vShaderSource; }, set: function(string) { this._vShaderSource = string; this._updatedVShaderSource = true; } }, /** [lang:ja] * フラグメントシェーダのソース * @type String [/lang] [lang:en] * Fragment shader source * @type String [/lang] */ fShaderSource: { get: function() { return this._fShaderSource; }, set: function(string) { this._fShaderSource = string; this._updatedFShaderSource = true; } }, /** [lang:ja] * シェーダプログラムをコンパイルする. * コンストラクタからシェーダソースを渡した場合は自動的にコンパイルされる. * @example * var shader = new Shader(); * // シェーダプログラムのソースを渡す. * shader.vShaderSource = vert; * shader.fShaderSource = frag; * // コンパイル. * shader.compile(); [/lang] [lang:en] * Compile shader program. * Will be automatically compiled when shader source is delivered from constructor. * @example * var shader = new Shader(); * // Deliver shader program source. * shader.vShaderSource = vert; * shader.fShaderSource = frag; * // Compile. * shader.compile(); [/lang] */ compile: function() { if (this._updatedVShaderSource) { this._prepareVShader(); } if (this._updatedFShaderSource) { this._prepareFShader(); } if (this._program == null) { this._program = gl.createProgram(); } else { gl.detachShader(this._program, this._vShaderProgram); gl.detachShader(this._program, this._fShaderProgram); } gl.attachShader(this._program, this._vShaderProgram); gl.attachShader(this._program, this._fShaderProgram); gl.linkProgram(this._program); if (!gl.getProgramParameter(this._program, gl.LINK_STATUS)) { this._logShadersInfo(); throw 'could not compile shader'; } this._getAttributesProperties(); this._getUniformsProperties(); }, /** [lang:ja] * シェーダプログラムを使用するように設定する. [/lang] [lang:en] * Set shader program to be used. [/lang] */ use: function() { gl.useProgram(this._program); }, /** [lang:ja] * シェーダプログラムにattribute変数をセットする. * enchant.gl.Sprite3Dの内部などで使用される. * @param {*} 値 * @example * var shader = new Shader(vert, frag); * shader.setAttributes({ * aVertexPosition: indices, * aNormal: normals * }); [/lang] [lang:en] * Sets attribute variables to shader program. * Used in enchant.gl.Sprite3D contents and elsewhere. * @param {*} params Level * @example * var shader = new Shader(vert, frag); * shader.setAttributes({ * aVertexPosition: indices, * aNormal: normals * }); [/lang] */ setAttributes: function(params) { for (var prop in params) if(params.hasOwnProperty(prop)) { this._attributes[prop] = params[prop]; } }, /** [lang:ja] * シェーダプログラムにuniform変数をセットする. * enchant.gl.Sprite3Dの内部などで使用される. * @param {*} params 値 * @example * var shader = new Shader(vert, frag); * shader.setUniforms({ * uDiffuse: diffuse, * uLightColor: lightColor * }); [/lang] [lang:en] * Set uniform variables to shader program. * Used in enchant.gl.Sprite3D and elsewhere. * @param {*} params Level * @example * var shader = new Shader(vert, frag); * shader.setUniforms({ * uDiffuse: diffuse, * uLightColor: lightColor * }); [/lang] */ setUniforms: function(params) { for (prop in params) if(params.hasOwnProperty(prop)) { this._uniforms[prop] = params[prop]; } }, _prepareVShader: function() { if (this._vShaderProgram == null) { this._vShaderProgram = gl.createShader(gl.VERTEX_SHADER); } gl.shaderSource(this._vShaderProgram, this._vShaderSource); gl.compileShader(this._vShaderProgram); this._updatedVShaderSource = false; }, _prepareFShader: function() { if (this._fShaderProgram == null) { this._fShaderProgram = gl.createShader(gl.FRAGMENT_SHADER); } gl.shaderSource(this._fShaderProgram, this._fShaderSource); gl.compileShader(this._fShaderProgram); this._updatedFShaderSource = false; }, _logShadersInfo: function() { console.log(gl.getShaderInfoLog(this._vShaderProgram)); console.log(gl.getShaderInfoLog(this._fShaderProgram)); }, _getAttributesProperties: function() { var n; n = gl.getProgramParameter(this._program, gl.ACTIVE_ATTRIBUTES); for (var i = 0; i < n; i++) { var info = gl.getActiveAttrib(this._program, i); this._attribLocs[info.name] = i; addAttributesProperty(this, info); } }, _getUniformsProperties: function() { var n; n = gl.getProgramParameter(this._program, gl.ACTIVE_UNIFORMS); for (var i = 0; i < n; i++) { var info = gl.getActiveUniform(this._program, i); this._uniforms[info.name]; addUniformsProperty(this, info); } }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { gl.deleteProgram(this._vShaderProgram); gl.deleteProgram(this._fShaderProgram); gl.deleteProgram(this._program); delete this; } }); var addAttributesProperty = function(program, info) { var name = info.name; var loc = program._attribLocs[name]; var desc = { get: function() { return 'attrib'; }, set: (function(loc) { return function(buf) { gl.enableVertexAttribArray(loc); buf._setToAttrib(loc); }; })(loc) }; Object.defineProperty(program._attributes, name, desc); }; var addUniformsProperty = function(program, info) { var name = info.name; var loc = gl.getUniformLocation(program._program, info.name); var suffix; var sampler = false; var matrix = false; var desc = { get: function() { return 'uniform'; } }; switch (info.type) { case gl.FLOAT: suffix = '1f'; break; case gl.FLOAT_MAT2: matrix = true; case gl.FLOAT_VEC2: suffix = '2fv'; break; case gl.FLOAT_MAT3: matrix = true; case gl.FLOAT_VEC3: suffix = '3fv'; break; case gl.FLOAT_MAT4: matrix = true; case gl.FLOAT_VEC4: suffix = '4fv'; break; case gl.SAMPLER_2D: case gl.SAMPLER_CUBE: sampler = true; case gl.INT: case gl.BOOL: suffix = '1i'; break; case gl.INT_VEC2: case gl.BOOL_VEC2: suffix = '2iv'; break; case gl.INT_VEC3: case gl.BOOL_VEC3: suffix = '3iv'; break; case gl.INT_VEC4: case gl.BOOL_VEC4: suffix = '4iv'; break; default: throw new Error('no match'); } if (matrix) { desc.set = (function(loc, suffix) { return function(value) { gl['uniformMatrix' + suffix](loc, false, value); }; })(loc, suffix); } else if (sampler) { desc.set = (function(loc, suffix, samplersNum) { return function(texture) { gl.activeTexture(gl.TEXTURE0 + samplersNum); gl.bindTexture(gl.TEXTURE_2D, texture._glTexture); gl['uniform' + suffix](loc, samplersNum); }; })(loc, suffix, program._samplersNum); program._samplersNum++; } else { desc.set = (function(loc, suffix) { return function(value) { gl['uniform' + suffix](loc, value); }; })(loc, suffix); } Object.defineProperty(program._uniforms, name, desc); }; /** [lang:ja] * @scope enchant.gl.Quat.prototype [/lang] [lang:en] * @scope enchant.gl.Quat.prototype [/lang] */ enchant.gl.Quat = enchant.Class.create({ /** [lang:ja] * クォータニオンを簡単に使用するクラス. * @param {Number} x * @param {Number} y * @param {Number} z * @param {Number} rad * @constructs [/lang] [lang:en] * Class that easily uses quaternions. * @param {Number} x * @param {Number} y * @param {Number} z * @param {Number} rad * @constructs [/lang] */ initialize: function(x, y, z, rad) { var l = Math.sqrt(x * x + y * y + z * z); if (l) { x /= l; y /= l; z /= l; } var s = Math.sin(rad / 2); var w = Math.cos(rad / 2); this._quat = quat4.create([x * s, y * s, z * s, w]); }, /** [lang:ja] * クォータニオン同士で球面線形補間を行う. * 自身ともう一つのクォータニオンの間の回転移動を補完したクォータニオンを計算する. * 回転の度合いは0から1の値で表される. 0が自身側, 1がもう一つ側. * 新しいインスタンスが返される. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] [lang:en] * Performs spherical linear interpolation between quarternions. * Calculates quarternion that supplements rotation between this quarternion and another. * Degree of rotation will be expressed in levels from 0 to 1. 0 is the side of this quarternion, 1 is the side of its counterpart. * New instance will be returned. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] */ slerp: function(another, ratio) { var q = new Quat(0, 0, 0, 0); quat4.slerp(this._quat, another._quat, ratio, q._quat); return q; }, /** [lang:ja] * クォータニオン同士で球面線形補間を行う. * 自身ともう一つのクォータニオンの間の回転移動を補完したクォータニオンを計算する. * 回転の度合いは0から1の値で表される. 0が自身側, 1がもう一つ側. * 自身の値が上書きされる. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] [lang:en] * Performs spherical linear interpolation between quarternions. * Calculates quarternion that supplements rotation between this quarternion and another. * Degree of rotation will be expressed in levels from 0 to 1. 0 is the side of this quarternion, 1 is the side of its counterpart. * This side's value will be overwritten. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] */ slerpApply: function(another, ratio) { quat4.slerp(this._quat, another._quat, ratio); return this; }, /** [lang:ja] * クォータニオンを回転行列に変換する. * @param {Number[]} matrix * @return {Number[]} [/lang] [lang:en] * Convert quarternion to rotation matrix. * @param {Number[]} matrix * @return {Number[]} [/lang] */ toMat4: function(matrix) { quat4.toMat4(this._quat, matrix); return matrix; }, /** [lang:ja] * クォータニオンをベクトルに適用する. * @param {Number[]} vector * @return {Number[]} [/lang] [lang:en] * Apply quarternion to vector. * @param {Number[]} vector * @return {Number[]} [/lang] */ multiplyVec3: function(vector) { quat4.multiplyVec3(this._quat, vector); return vector; } }); /** [lang:ja] * @scope enchant.gl.Light3D.prototype [/lang] [lang:en] * @scope enchant.gl.Light3D.prototype [/lang] */ enchant.gl.Light3D = enchant.Class.create(enchant.EventTarget, { /** [lang:ja] * 光源クラスの親となるクラス. * * @constructs * @extends enchant.EventTarget [/lang] [lang:en] * Light source class parent class. * * @constructs * @extends enchant.EventTarget [/lang] */ initialize: function() { this._changedColor = true; this._color = [0.8, 0.8, 0.8]; }, /** [lang:ja] * 光源の光の色 * @type Number[] [/lang] [lang:en] * Light source light color * @type Number[] [/lang] */ color: { set: function(array) { this._color = array; this._changedColor = true; }, get: function() { return this._color; } } }); /** [lang:ja] * @scope enchant.gl.DirectionalLight.prototype [/lang] [lang:en] * @scope enchant.gl.DirectionalLight.prototype [/lang] */ enchant.gl.DirectionalLight = enchant.Class.create(enchant.gl.Light3D, { /** [lang:ja] * 3Dシーンでの光源を設定するクラス. * 位置を持たない方向光源. * @example * var scene = new Scene3D(); * var light = new DirectionalLight(); * light.color = [1.0, 1.0, 0.0]; * light.directionY = 10; * scene.setDirectionalLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] [lang:en] * Class for setting light source in 3D scene. * Directioned light source without position. * @example * var scene = new Scene3D(); * var light = new DirectionalLight(); * light.color = [1.0, 1.0, 0.0]; * light.directionY = 10; * scene.setDirectionalLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] */ initialize: function() { enchant.gl.Light3D.call(this); this._directionX = 0.5; this._directionY = 0.5; this._directionZ = 1.0; this._changedDirection = true; } }); /** [lang:ja] * 光源の照射方向のx成分 * @type Number [/lang] [lang:en] * Light source exposure direction x component * @type Number [/lang] */ enchant.gl.DirectionalLight.prototype.directionX = 0.5; /** [lang:ja] * 光源の照射方向のy成分 * @type Number [/lang] [lang:en] * Light source exposure direction y component * @type Number [/lang] */ enchant.gl.DirectionalLight.prototype.directionY = 0.5; /** [lang:ja] * 光源の照射方向のz成分 * @type Number [/lang] [lang:en] * Light source exposure direction z component * @type Number [/lang] */ enchant.gl.DirectionalLight.prototype.directionZ = 1.0; /** [lang:ja] * 光源の照射方向 * @type {Number} [/lang] [lang:en] * Light source exposure direction * @type {Number} [/lang] */ 'directionX directionY directionZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.DirectionalLight.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedDirection = true; } }); enchant.gl.DirectionalLight.prototype[prop] = 0; }); /** [lang:ja] * @scope enchant.gl.PointLight.prototype [/lang] [lang:en] * @scope enchant.gl.PointLight.prototype [/lang] */ enchant.gl.PointLight = enchant.Class.create(enchant.gl.Light3D, { /** [lang:ja] * 3Dシーンでの光源を設定するクラス. * 方向を持たない点光源. * 現在, シーンに追加しても適用されない. * @example * var scene = new Scene3D(); * var light = new PointLight(); * light.color = [1.0, 1.0, 0.0]; * light.y = 10; * scene.addLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] [lang:en] * Class that sets 3D scene light source. * Directionless positional light source. * At present, will not be applied even if added to scene. * @example * var scene = new Scene3D(); * var light = new PointLight(); * light.color = [1.0, 1.0, 0.0]; * light.y = 10; * scene.addLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] */ initialize: function() { enchant.gl.Light3D.call(this); this._x = 0; this._y = 0; this._z = 0; this._changedPosition = true; } }); /** [lang:ja] * 光源のx座標 * @type Number [/lang] [lang:en] * Light source x axis * @type Number [/lang] */ enchant.gl.PointLight.prototype.x = 0; /** [lang:ja] * 光源のy座標 * @type Number [/lang] [lang:en] * Light source y axis * @type Number [/lang] */ enchant.gl.PointLight.prototype.y = 0; /** [lang:ja] * 光源のz座標 * @type Number [/lang] [lang:en] * Light source z axis * @type Number [/lang] */ enchant.gl.PointLight.prototype.z = 0; 'x y z'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.PointLight.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedPosition = true; } }); enchant.gl.PointLight.prototype[prop] = 0; }); /** [lang:ja] * @scope enchant.gl.Texture.prototype [/lang] [lang:en] * @scope enchant.gl.Texture.prototype [/lang] */ enchant.gl.Texture = enchant.Class.create({ /** [lang:ja] * テクスチャ情報を格納するクラス. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "http://example.com/texture.png"; * // 以下のようにも宣言できる. * // var texture = new Texture("http://example.com/texture.png"); * sprite.texture = texture; * @constructs [/lang] [lang:en] * Class to store Sprite3D texture information. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "http://example.com/texture.png"; * // Can also be declared as below. * // var texture = new Texture("http://example.com/texture.png"); * sprite.texture = texture; * @constructs [/lang] */ initialize: function(src, opt) { /** [lang:ja] * 環境光のパラメータ * @type Number[] [/lang] [lang:en] * Ambient light parameter * @type Number[] [/lang] */ this.ambient = [ 0.1, 0.1, 0.1, 1.0 ]; /** [lang:ja] * 拡散光のパラメータ * @type Number[] [/lang] [lang:en] * Light scattering parameter * @type Number[] [/lang] */ this.diffuse = [ 1.0, 1.0, 1.0, 1.0]; /** [lang:ja] * 光の反射量 * @type Number[] [/lang] [lang:en] * Amount of light reflection * @type Number[] [/lang] */ this.specular = [ 1.0, 1.0, 1.0, 1.0 ]; /** [lang:ja] * 光の発光量 * @type Number[] [/lang] [lang:en] * Amount of luminescence * @type Number[] [/lang] */ this.emission = [ 0.0, 0.0, 0.0, 1.0 ]; /** [lang:ja] * 鏡面計数 * @type Number [/lang] [lang:en] * Specular figures * @type Number [/lang] */ this.shininess = 20; this._glTexture = null; this._image = null; this._wrap = 10497; this._mipmap = false; this._flipY = true; if (opt) { var valid = ['flipY', 'wrap', 'mipmap']; for (var prop in opt) if(opt.hasOwnProperty(prop)) { if (valid.indexOf(prop) != -1) { this['_' + prop] = opt[prop]; } } } if (src) { this.src = src; } }, _write: function() { gl.bindTexture(gl.TEXTURE_2D, this._glTexture); enchant.Game.instance.GL.textureManager._writeWebGLTexture(this._image, gl.TEXTURE_2D, this._wrap, this._mipmap); gl.bindTexture(gl.TEXTURE_2D, null); }, /** [lang:ja] * テクスチャ画像のソース. * URLかgame.assets内のデータを指定できる. * @type String * @type enchant.Surface [/lang] [lang:en] * Texture image source. * You can set URL or game.assets data. * @type String * @type enchant.Surface [/lang] */ src: { get: function() { return this._src; }, set: function(source) { if (typeof source == 'undefined' || source == null) { return; } var that = this; var game = enchant.Game.instance; var onload = (function(that) { return function() { that._glTexture = game.GL.textureManager.getWebGLTexture(that._image, that._flipY, that._wrap, that._mipmap); }; })(that); if (source instanceof Image) { this._image = source; onload(); } else if (source instanceof Surface) { this._image = source._element; onload(); } else if (typeof source == 'string') { this._image = new Image(); this._image.onload = onload; this._image.src = source; } else { this._image = source; this._image.src = "c" + Math.random(); onload(); } } } }); /** [lang:ja] * @scope enchant.gl.Buffer.prototype [/lang] [lang:en] * @scope enchant.gl.Buffer.prototype [/lang] */ enchant.gl.Buffer = enchant.Class.create({ /** [lang:ja] * 頂点などの配列情報を管理する. * enchant.gl.Meshのプロパティとして使用される. * @param {*} params parameter * @param {Number[]} array * * @example * var index = [ 0, 1, 2, 2, 3, 0 ]; * var indices = new Buffer(Buffer.INDICES, index); * * @constructs [/lang] [lang:en] * Controls peak and other array information. * Used as enchant.gl.Mesh property. * @param {*} params parameter * @param {Number[]} array * * @example * var index = [ 0, 1, 2, 2, 3, 0 ]; * var indices = new Buffer(Buffer.INDICES, index); * * @constructs [/lang] */ initialize: function(params, array) { this._setParams(params); if (typeof array != 'undefined') { this._array = array; } else { this._array = new Array(); } this._buffer = null; }, /** [lang:ja] * バッファをバインドする. [/lang] [lang:en] * Bind buffer. [/lang] */ bind: function() { gl.bindBuffer(this.btype, this._buffer); }, /** [lang:ja] * バッファをアンバインドする. [/lang] [lang:en] * Unbind buffer. [/lang] */ unbind: function() { gl.bindBuffer(this.btype, null); }, _setParams: function(params) { for (prop in params) if(params.hasOwnProperty(prop)) { this[prop] = params[prop]; } }, _create: function() { this._buffer = gl.createBuffer(); }, _delete: function() { gl.deleteBuffer(this._buffer); }, _bufferData: function() { this.bind(); gl.bufferData(this.btype, new this.Atype(this._array), gl.STATIC_DRAW); this.unbind(); }, _bufferDataFast: function() { this.bind(); gl.bufferData(this.btype, this._array, gl.STATIC_DRAW); this.unbind(); }, _setToAttrib: function(loc) { this.bind(); gl.vertexAttribPointer(loc, this.size, this.type, this.norm, this.stride, this.offset); this.unbind(); }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { this._delete(); delete this; } }); var bufferProto = Object.getPrototypeOf(enchant.gl.Buffer); bufferProto.VERTICES = bufferProto.NORMALS = { size: 3, type: 5126, norm: false, stride: 0, offset: 0, btype: 34962, Atype: Float32Array }; bufferProto.TEXCOORDS = { size: 2, type: 5126, normed: false, stride: 0, ptr: 0, btype: 34962, Atype: Float32Array }; bufferProto.COLORS = { size: 4, type: 5126, normed: false, stride: 0, ptr: 0, btype: 34962, Atype: Float32Array }; bufferProto.INDICES = { size: 3, type: 5123, normed: false, stride: 0, offset: 0, btype: 34963, Atype: Uint16Array }; /** [lang:ja] * @scope enchant.gl.Mesh.prototype [/lang] [lang:en] * @scope enchant.gl.Mesh.prototype [/lang] */ enchant.gl.Mesh = enchant.Class.create({ /** [lang:ja] * 頂点配列やテクスチャを格納するクラス. * enchant.gl.Sprite3Dのプロパティとして使用される. * @constructs [/lang] [lang:en] * Class to store peak arrays and textures. * Used as a sprite property. * @constructs [/lang] */ initialize: function() { this.__count = 0; this._appear = false; this._vertices = new enchant.gl.Buffer(enchant.gl.Buffer.VERTICES); this._normals = new enchant.gl.Buffer(enchant.gl.Buffer.NORMALS); this._colors = new enchant.gl.Buffer(enchant.gl.Buffer.COLORS); this._texCoords = new enchant.gl.Buffer(enchant.gl.Buffer.TEXCOORDS); this._indices = new enchant.gl.Buffer(enchant.gl.Buffer.INDICES); this.texture = new Texture(); }, /** [lang:ja] * Meshの色を変更する. * Mesh.colorsを指定した色の頂点配列にする. * @param {Number[]|String} color z z軸方向の平行移動量 * @example * var sprite = new Sprite3D(); * //紫色に設定. どれも同じ結果が得られる. * sprite.mesh.setBaseColor([1.0, 0.0, 1.0, 0.0]); * sprite.mesh.setBaseColor('#ff00ff'); * sprite.mesh.setBaseColor('rgb(255, 0, 255'); * sprite.mesh.setBaseColor('rgba(255, 0, 255, 1.0'); [/lang] [lang:en] * Change Mesh color. * Becomes peak array for Mesh.colors set color. * @param {Number[]|String} color z Amount of parallel displacement on z axis * @example * var sprite = new Sprite3D(); * //Sets to purple. All yield the same result. * sprite.mesh.setBaseColor([1.0, 0.0, 1.0, 0.0]); * sprite.mesh.setBaseColor('#ff00ff'); * sprite.mesh.setBaseColor('rgb(255, 0, 255'); * sprite.mesh.setBaseColor('rgba(255, 0, 255, 1.0'); [/lang] */ setBaseColor: function(color) { var c = enchant.Game.instance.GL.parseColor(color); var newColors = []; for (var i = 0, l = this.vertices.length / 3; i < l; i++) { Array.prototype.push.apply(newColors, c); } this.colors = newColors; }, /** [lang:ja] * メッシュの面の向きと法線の向きを反転させる. [/lang] [lang:en] * Reverse direction of the mesh surface and the normal vector. [/lang] */ reverse: function() { var norm = this.normals; var idx = this.indices; var t, i, l; for (i = 0, l = norm.length; i < l; i++) { norm[i] *= -1; } for (i = 0, l = idx.length; i < l; i += 3) { t = idx[i + 1]; idx[i + 1] = idx[i + 2]; idx[i + 2] = t; } this._normals._bufferData(); this._indices._bufferData(); }, _createBuffer: function() { for (var prop in this) if(this.hasOwnProperty(prop)) { if (this[prop] instanceof enchant.gl.Buffer) { this[prop]._create(); this[prop]._bufferData(); } } }, _deleteBuffer: function() { for (var prop in this) if(this.hasOwnProperty(prop)) { if (this[prop] instanceof enchant.gl.Buffer) { this[prop]._delete(); } } }, _controlBuffer: function() { if (this._appear) { if (this.__count <= 0) { this._appear = false; this._deleteBuffer(); } } else { if (this.__count > 0) { this._appear = true; this._createBuffer(); } } }, _count: { get: function() { return this.__count; }, set: function(c) { this.__count = c; this._controlBuffer(); } }, _join: function(another, ox, oy, oz) { var triangles = this.vertices.length / 3, vertices = this.vertices.slice(0), i, l; for (i = 0, l = another.vertices.length; i < l; i += 3) { vertices.push(another.vertices[i] + ox); vertices.push(another.vertices[i + 1] + oy); vertices.push(another.vertices[i + 2] + oz); } this.vertices = vertices; this.normals = this.normals.concat(another.normals); this.texCoords = this.texCoords.concat(another.texCoords); this.colors = this.colors.concat(another.colors); var indices = this.indices.slice(0); for (i = 0, l = another.indices.length; i < l; i++) { indices.push(another.indices[i] + triangles); } this.indices = indices; }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { this._deleteBuffer(); delete this; } }); /** [lang:ja] * Meshの頂点配列. * 3つの要素を一組として頂点を指定する. 全体の要素数は, 頂点の個数nに対して3nとなる. * 3n, 3n+1, 3n+2番目の要素はそれぞれ, n番目の頂点のx, y, z座標である. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] [lang:en] * Mesh peak array. * Sets 3 elements together at peak. The complete number of elements becomes 3n corresponding to the quantity of the peak. * The 3n, 3n+1, and 3n+2 elements become, respectively, the n peak x, y, and z coordinates. * @example * var sprite = new Sprite3D(); * //Substitute peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] */ enchant.gl.Mesh.prototype.vertices; /** [lang:ja] * Meshの頂点法線ベクトル配列. * 3つの要素を一組として法線ベクトルを指定する. 全体の要素数は, 法線ベクトルの個数nに対して3nとなる. * 3n, 3n+1, 3n+2番目の要素はそれぞれ, n番目の頂点の法線ベクトルのx, y, z成分である. * 法線ベクトルはライティングの影の計算に利用される. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //法線ベクトル配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.normals = [ * 0.0, 0.0, 0.0, //0番目の頂点の法線ベクトル(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点の法線ベクトル(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点の法線ベクトル(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点の法線ベクトル(0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#texCoords [/lang] [lang:en] * Mesh peak normal vector array. * Sets 3 elements as one in normal vector. The complete element number becomes 3n for normal vector quantity n. * 3n, 3n+1, and 3n+2 elements are the n level peak x, y, and z elements of the normal vector. * The normal vector is used in calculations for lighting and shadow. * @example * var sprite = new Sprite3D(); * //Substitutes peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes normal vector array * //Data is a stored in an order of x, y, z, x, y, z... * sprite.normals = [ * 0.0, 0.0, 0.0, //0 level peak normal vector (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 level peak normal vector (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 level peak normal vector (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 level peak normal vector (0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#texCoords [/lang] */ enchant.gl.Mesh.prototype.normals; /** [lang:ja] * Meshのテクスチャマッピング配列. * 2つの要素を一組としてuv座標を指定する. 全体の要素数は, 頂点の個数nに対して2nとなる. * 2n, 2n+1番目の要素はそれぞれ, n番目の頂点のテクスチャのu, v座標である. * それぞれの座標のとりうる値は0<=u,v<=1である. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "texture.png"; * sprite.mesh.texture = texture; * * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //uv座標配列を代入 * //データはu, v, u, v...の順に格納する * sprite.mesh.texCoords = [ * 0.0, 0.0, //0番目の頂点のuv座標(0.0, 0.0) * 1.0, 0.0, //1番目の頂点のuv座標(1.0, 0.0) * 1.0, 1.0, //2番目の頂点のuv座標(1.0, 1.0) * 0.0, 1.0 //3番目の頂点のuv座標(0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texture# [/lang] [lang:en] * Mesh texture mapping array. * Sets two elements as one in uv coordinates. The total number of elements becomes 2n in response to the peak quantity. * 2n, 2n+1 level elements correspond to n level peak texture u, v coordinates. * The coordinates that can be acquired for each coordinate correspond to 0<=u, v<=1. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "texture.png"; * sprite.mesh.texture = texture; * * //Substitutes peak level * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes uv coordinate array * //Data is stored in an order of u, v, u, v... * sprite.texCoords = [ * 0.0, 0.0, //0番目の頂点のuv座標(0.0, 0.0) * 1.0, 0.0, //1番目の頂点のuv座標(1.0, 0.0) * 1.0, 1.0, //2番目の頂点のuv座標(1.0, 1.0) * 0.0, 1.0 //3番目の頂点のuv座標(0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texture# [/lang] */ enchant.gl.Mesh.prototype.texCoords; /** [lang:ja] * Meshの頂点インデックス配列. * 3つの要素を一組として三角形を指定する.全体の要素数は, 三角形の個数nに対して3nとなる. * インデックスの値は, {@link enchant.gl.Mesh#vertices}で指定した頂点の番号である. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //頂点インデックスを代入 * //3要素一組として, 三角形を描画する * //この例では(0,0,0), (1,0,0), (1,1,0)の三角形と * //(1,1,0), (0,1,0), (0,0,0)の三角形の計二つを描画する * sprite.indices = [ * 0, 1, 2, * 2, 3, 0 * ]; * var scene = new Scene3D(); * scene.addChild(sprite); * @type Integer[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] [lang:en] * Sprite3D peak index array. * 3 elements are set as one in a triangle. The total number of elements becomes 3n corresponding to the triangle's total quantity n. * Index level is the peak number designated in {@link enchant.gl.Sprite3D#vertices}. * @example * var sprite = new Sprite3D(); * //Substitutes peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes peak index * //Draws triangle with 3 elements as one * //In this example the two triangles (0,0,0), (1,0,0), (1,1,0) and * //(1,1,0), (0,1,0), (0,0,0) are drawn. * sprite.indices = [ * 0, 1, 2, * 2, 3, 0 * ]; * var scene = new Scene3D(); * scene.addChild(sprite); * @type Integer[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] */ enchant.gl.Mesh.prototype.indices; /** [lang:ja] * Meshの頂点色配列. * 4つの要素を一組として頂点色を指定する. 全体の要素数は, 頂点の個数nに対して4nとなる. * 4n, 4n+1, 4n+2, 4n+3番目の要素はそれぞれ, n番目の頂点の色のr, g, b, a成分である. * 頂点色はMeshのtextureにテクスチャが割り当てられていない場合の描画に使用される. * {@link enchant.gl.Mesh#setBaseColor}で一括して変更することができる. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //頂点色配列を代入 * //データはr, g, b, ,a, r, g, b, a...の順に格納する * sprite.mesh.normals = [ * 0.0, 0.0, 1.0, 1.0, //0番目の頂点の色(0.0, 0.0, 1.0, 1.0) * 0.0, 1.0, 0.0, 1.0, //1番目の頂点の色(0.0, 1.0, 0.0, 1.0) * 0.0, 1.0, 1.0, 1.0, //2番目の頂点の色(0.0, 1.0, 1.0, 1.0) * 1.0, 0.0, 0.0, 1.0 //3番目の頂点の色(1.0, 0.0, 0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#setBaseColor [/lang] [lang:en] * Mesh peak color array. * The 4 elements are set as one peak color. The entire number of elements becomes 4n corresponding to the peak quantity n. * The 4n, 4n+1, 4n+2, and 4n+3 elements are the n level peak colors r, g, b, a. * Peak color is used for drawing when Texture is not assigned to Sprite3D Texture. * {@link enchant.gl.Mesh#setBaseColor} can be used to bundle together and change. * @example * var sprite = new Sprite3D(); * //Substitutes peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes peak level array * //Data is stored in an order of r, g, b, a, r, g, b, a... * sprite.normals = [ * 0.0, 0.0, 1.0, 1.0, //0 peak color (0.0, 0.0, 1.0, 1.0) * 0.0, 1.0, 0.0, 1.0, //1 peak color (0.0, 1.0, 0.0, 1.0) * 0.0, 1.0, 1.0, 1.0, //2 peak color (0.0, 1.0, 1.0, 1.0) * 1.0, 0.0, 0.0, 1.0 //3 peak color (1.0, 0.0, 0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#setBaseColor [/lang] */ enchant.gl.Mesh.prototype.colors; 'vertices normals colors texCoords indices'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Mesh.prototype, prop, { get: function() { return this['_' + prop]._array; }, set: function(array) { this['_' + prop]._array = array; if (this._appear) { this['_' + prop]._bufferData(); } } }); }); /** [lang:ja] * @scope enchant.gl.Sprite3D.prototype [/lang] [lang:en] * @scope enchant.gl.Sprite3D.prototype [/lang] */ enchant.gl.Sprite3D = enchant.Class.create(enchant.EventTarget, { /** [lang:ja] * Sprite3D表示機能を持ったクラス. * <p>{@link enchant.gl.Scene3D}のインスタンスに追加することで, 画面上に表示することができる. * {@link enchant.gl.Sprite3D#vertices}, {@link enchant.gl.Sprite3D#indices}, * {@link enchant.gl.Sprite3D#normals}などを変更することで, 任意のSprite3Dを描画することもでき, * テクスチャなども貼付けることができる.</p> * <p>また, Sprite3Dを子として追加することも可能で, 子は全て親を基準とした座標系で描画される.</p> * @example * //シーンの初期化 * var scene = new Scene3D(); * //Sprite3Dの初期化 * var sprite = new Sprite3D(); * //Sprite3Dをシーンに追加 * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] [lang:en] * Class with Sprite3D display function. * <p>By adding {@link enchant.gl.Scene3D} instance, you can display atop an image. * By changing {@link enchant.gl.Sprite3D#vertices}, {@link enchant.gl.Sprite3D#indices}, * {@link enchant.gl.Sprite3D#normals} and others, you can freely draw Sprite3D, * as well as pasting texture and more.</p> * <p>In addition, it is also possible to add Sprite3D as a child, and all child classes will be drawn with coordinates based on their parents.</p> * @example * //Scene initialization * var scene = new Scene3D(); * //Sprite3D initialization * var sprite = new Sprite3D(); * //Add Sprite3D to scene * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] */ initialize: function() { enchant.EventTarget.call(this); /** [lang:ja] * 子Sprite3D要素の配列. * この要素に子として追加されているSprite3Dの一覧を取得できる. * 子を追加したり削除したりする場合には, この配列を直接操作せずに, * {@link enchant.gl.Sprite3D#addChild}や{@link enchant.gl.Sprite3D#removeChild}を利用する. * @type enchant.gl.Sprite3D[] * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#removeChild [/lang] [lang:en] * Array for child Sprite 3D element. * Can acquire list of Sprite3Ds added as child classes to this element. * When adding or subtracting child classes, without directly operating this array, * {@link enchant.gl.Sprite3D#addChild} or {@link enchant.gl.Sprite3D#removeChild} is used. * @type enchant.gl.Sprite3D[] * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#removeChild [/lang] */ this.childNodes = []; /** [lang:ja] * このSprite3Dが現在追加されているシーンオブジェクト. * どのシーンにも追加されていないときにはnull. * @type enchant.gl.Scene3D * @see enchant.gl.Scene3D#addChild [/lang] [lang:en] * The scene object currently added by this Sprite3D. * When no scene is added this is null. * @type enchant.gl.Scene3D * @see enchant.gl.Scene3D#addChild [/lang] */ this.scene = null; /** [lang:ja] * Sprite3Dの親要素. * 親が存在しない場合にはnull. * @type enchant.gl.Sprite3D|enchant.gl.Scene3D [/lang] [lang:en] * Sprite3D parent element. * When no parent exists this is null. * @type enchant.gl.Sprite3D|enchant.gl.Scene3D [/lang] */ this.parentNode = null; /** [lang:ja] * Sprite3Dに適用されるメッシュオブジェクト. * @type enchant.gl.Mesh * @example * var sprite = new Sprite3D(); * sprite.mesh = new Mesh(); [/lang] [lang:en] * Mesh object applied to Sprite3D. * @type enchant.gl.Mesh * @example * var sprite = new Sprite3D(); * sprite.mesh = new Mesh(); [/lang] */ this._mesh = null; this.program = null; this.bounding = new BS(); this.bounding.parent = this; this.age = 0; this._x = 0; this._y = 0; this._z = 0; this._scaleX = 1; this._scaleY = 1; this._scaleZ = 1; this._changedTranslation = true; this._changedRotation = true; this._changedScale = true; this._touchable = true; this._global = vec3.create(); this.globalX = 0; this.globalY = 0; this.globalZ = 0; this._matrix = mat4.identity(); this.tmpMat = mat4.identity(); this.modelMat = mat4.identity(); this._rotation = mat4.identity(); this._normMat = mat3.identity(); var game = enchant.Game.instance; this.detectColor = game.GL.detectColorManager.attachDetectColor(this); var parentEvent = function(e) { if (this.parentNode instanceof Sprite3D) { this.parentNode.dispatchEvent(e); } } this.addEventListener('touchstart', parentEvent); this.addEventListener('touchmove', parentEvent); this.addEventListener('touchend', parentEvent); var added = function(e) { if (this.mesh != null) { this.mesh._count++; } if (this.childNodes.length) { for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i].scene = this.scene; this.childNodes[i].dispatchEvent(e); } } }; this.addEventListener('addedtoscene', added); var removed = function(e) { if (this.mesh != null) { this.mesh._count--; } if (this.childNodes.length) { for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i].scene = null; this.childNodes[i].dispatchEvent(e); } } }; this.addEventListener('removedfromscene', removed); }, /** [lang:ja] * Sprite3Dの複製を作成する. * 位置,回転行列などがコピーされた新しいインスタンスが返される. * @example * var sp = new Sprite3D(); * sp.x = 15; * var sp2 = sp.clone(); * //sp2.x = 15; * @return {enchant.gl.Sprite3D} [/lang] [lang:en] * Executes the reproduction of Sprite3D. * Position, rotation line, and others will be returned to a copied, new instance. * @example * var sp = new Sprite3D(); * sp.x = 15; * var sp2 = sp.clone(); * //sp2.x = 15; * @return {enchant.gl.Sprite3D} [/lang] */ clone: function() { var clone = new Sprite3D(); for (prop in this) { if (typeof this[prop] == 'number' || typeof this[prop] == 'string') { clone[prop] = this[prop]; } else if (this[prop] instanceof WebGLBuffer) { clone[prop] = this[prop]; } else if (this[prop] instanceof Float32Array) { clone[prop] = new Float32Array(this[prop]); } else if (this[prop] instanceof Array && prop != 'childNodes' && prop != 'detectColor') { clone[prop] = this[prop].slice(0); } } if (this.mesh != null) { clone.mesh = this.mesh; } if (this.childNodes) { for (var i = 0, l = this.childNodes.length; i < l; i++) { clone.addChild(this.childNodes[i].clone()); } } return clone; }, /** [lang:ja] * 他のSprite3Dの状態をセットする. * Colladaファイルを読み込んだassetsに対して使用できる. * @example * var sp = new Sprite3D(); * sp.set(game.assets['sample.dae']); * //sample.daeのモデル情報を持ったSprite3Dになる * [/lang] [lang:en] * Sets condition of other Sprite3D. * Can be used corresponding Collada file's loaded assets. * @example * var sp = new Sprite3D(); * sp.set(game.assets['sample.dae']); * //Becomes Sprite3D with sample.dae model information * [/lang] */ set: function(sprite) { for (prop in sprite) { if (typeof sprite[prop] == 'number' || typeof sprite[prop] == 'string') { this[prop] = sprite[prop]; } else if (sprite[prop] instanceof WebGLBuffer) { this[prop] = sprite[prop]; } else if (sprite[prop] instanceof Float32Array) { this[prop] = new Float32Array(sprite[prop]); } else if (sprite[prop] instanceof Array && prop != 'childNodes' && prop != 'detectColor') { this[prop] = sprite[prop].filter(function() { return true; }); } } if (sprite.mesh != null) { this.mesh = sprite.mesh; } if (sprite.childNodes) { for (var i = 0, l = sprite.childNodes.length; i < l; i++) { this.addChild(sprite.childNodes[i].clone()); } } }, /** [lang:ja] * 子Sprite3Dを追加する. * 追加が完了すると, 子Sprite3Dに対してaddedイベントが発生する. * 親が既にシーンに追加されていた場合には, そのシーンに追加され, * addedtosceneイベントが発生する. * @param {enchant.gl.Sprite3D} sprite 追加する子Sprite3D. * @example * var parent = new Sprite3D(); * var child = new Sprite3D(); * //Sprite3Dを別のSprite3Dに子として追加 * parent.addChild(child); * @see enchant.gl.Sprite3D#removeChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] [lang:en] * Add child Sprite3D. * When it is added, an "added" event will be created for child Sprite3D. * When a parent is already added to scene, it will be added to scene, * and an "addedtoscene" event will be created. * Child Sprite3D for adding @param {enchant.gl.Sprite3D} sprite. * @example * var parent = new Sprite3D(); * var child = new Sprite3D(); * //Add Sprite3D as child to another Sprite3D * parent.addChild(child); * @see enchant.gl.Sprite3D#removeChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] */ addChild: function(sprite) { this.childNodes.push(sprite); sprite.parentNode = this; sprite.dispatchEvent(new enchant.Event('added')); if (this.scene) { sprite.scene = this.scene; sprite.dispatchEvent(new enchant.Event('addedtoscene')); } }, /** [lang:ja] * 指定された子Sprite3Dを削除する. * 削除が完了すると, 子Sprite3Dに対してremovedイベントが発生する. * シーンに追加されていた場合には, そのシーンからも削除され, * removedfromsceneイベントが発生する. * @param {enchant.gl.Sprite3D} sprite 削除する子Sprite3D. * @example * var scene = new Scene3D(); * //sceneの一番目の子を削除 * scene.removeChild(scene.childNodes[0]); * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] [lang:en] * Deletes designated child Sprite3D. * When deletion is complete, a "removed" event will be created for child Sprite3D. * When added to scene, it will be deleted from that scene, * and a "removedfromscene" event will be created. * Child Sprite3D for deleting @param {enchant.gl.Sprite3D} sprite. * @example * var scene = new Scene3D(); * //Deletes scene's first child * scene.removeChild(scene.childNodes[0]); * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] */ removeChild: function(sprite) { var i; if ((i = this.childNodes.indexOf(sprite)) != -1) { this.childNodes.splice(i, 1); } sprite.parentNode = null; sprite.dispatchEvent(new enchant.Event('removed')); if (this.scene) { sprite.scene = null; sprite.dispatchEvent(new enchant.Event('removedfromscene')); } }, /** [lang:ja] * 他のオブジェクトとの衝突判定. * 衝突判定オブジェクトか, x, y, zプロパティを持っているオブジェクトとの衝突を判定することができる. * @param {enchant.gl.Sprite3D} bounding 対象のオブジェクト * @return {Boolean} [/lang] [lang:en] * Other object collison detection. * Can detect collisions with collision detection objects with x, y, z properties. * @param {enchant.gl.Sprite3D} bounding Target object * @return {Boolean} [/lang] */ intersect: function(another) { return this.bounding.intersect(another.bounding); }, /** [lang:ja] * Sprite3Dを平行移動する. * 現在表示されている位置から, 各軸に対して指定された分だけ平行移動をする. * @param {Number} x x軸方向の平行移動量 * @param {Number} y y軸方向の平行移動量 * @param {Number} z z軸方向の平行移動量 * @example * var sprite = new Sprite3D(); * //x軸方向に10, y軸方向に3, z軸方向に-20平行移動 * sprite.translate(10, 3, -20); * @see enchant.gl.Sprite3D#x * @see enchant.gl.Sprite3D#y * @see enchant.gl.Sprite3D#z * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Parallel displacement of Sprite3D. * Displaces each coordinate a designated amount from its current location. * @param {Number} x Parallel displacement of x axis * @param {Number} y Parallel displacement of y axis * @param {Number} z Parallel displacement of z axis * @example * var sprite = new Sprite3D(); * //Parallel displacement by 10 along the x axis, 3 along the y axis, and -20 along the z axis * sprite.translate(10, 3, -20); * @see enchant.gl.Sprite3D#x * @see enchant.gl.Sprite3D#y * @see enchant.gl.Sprite3D#z * @see enchant.gl.Sprite3D#scale [/lang] */ translate: function(x, y, z) { this._x += x; this._y += y; this._z += z; this._changedTranslation = true; }, /** [lang:ja] * Sprite3DをローカルのZ軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves forward Sprite3D. * @param {Number} speed [/lang] */ forward: function(speed) { var x = this._rotation[8] * speed; var y = this._rotation[9] * speed; var z = this._rotation[10] * speed; this.translate(x, y, z); }, /** [lang:ja] * Sprite3DをローカルのX軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves side Sprite3D. * @param {Number} speed [/lang] */ sidestep: function(speed) { var x = this._rotation[0] * speed; var y = this._rotation[1] * speed; var z = this._rotation[2] * speed; this.translate(x, y, z); }, /** [lang:ja] * Sprite3DをローカルのY軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves up Sprite3D. * @param {Number} speed [/lang] */ altitude: function(speed) { var x = this._rotation[4] * speed; var y = this._rotation[5] * speed; var z = this._rotation[6] * speed; this.translate(x, y, z); }, /** [lang:ja] * Sprite3Dを拡大縮小する. * 現在の拡大率から, 各軸に対して指定された倍率分だけ拡大縮小をする. * @param {Number} x x軸方向の拡大率 * @param {Number} y y軸方向の拡大率 * @param {Number} z z軸方向の拡大率 * @example * var sprite = new Sprite3D(); * //x軸方向に2.0倍, y軸方向に3.0倍, z軸方向に0.5倍に拡大する * sprite.scale(2,0, 3.0, 0.5); * @see enchant.gl.Sprite3D#scaleX * @see enchant.gl.Sprite3D#scaleY * @see enchant.gl.Sprite3D#scaleZ * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Expand or contract Sprite3D. * Expands each axis by a designated expansion rate. * @param {Number} x x axis expansion rate * @param {Number} y y axis expansion rate * @param {Number} z z axis expansion rate * @example * var sprite = new Sprite3D(); * //Expand x axis by 2.0 times, y axis by 3.0 times, and z axis by 0.5 times * sprite.scale(2,0, 3.0, 0.5); * @see enchant.gl.Sprite3D#scaleX * @see enchant.gl.Sprite3D#scaleY * @see enchant.gl.Sprite3D#scaleZ * @see enchant.gl.Sprite3D#translate [/lang] */ scale: function(x, y, z) { this._scaleX *= x; this._scaleY *= y; this._scaleZ *= z; this._changedScale = true; }, /** [lang:ja] * Sprite3Dの名前 * @type String [/lang] [lang:en] * Sprite3D name * @type String [/lang] */ name: { get: function() { return this._name; }, set: function(name) { this._name = name; } }, /** [lang:ja] * Sprite3Dの回転行列. * 配列は長さ16の一次元配列であり, 行優先の4x4行列として解釈される. * @example * var sprite = new Sprite3D(); * //x軸周りに45度回転 * var rotX = Math.PI() / 4; * sprite.rotation = [ * 1, 0, 0, 0, * 0, Math.cos(rotX), -Math.sin(rotX), 0, * 0, Math.sin(rotX), Math.cos(rotX), 0, * 0, 0, 0, 1 * ]; * @type Number[] [/lang] [lang:en] * Sprite3D rotation line. * Array is a one-dimensional array of length 16, interpreted as the 4x4 line destination. * @example * var sprite = new Sprite3D(); * //45 degree rotation along the x axis * var rotX = Math.PI() / 4; * sprite.rotation = [ * 1, 0, 0, 0, * 0, Math.cos(rotX), -Math.sin(rotX), 0, * 0, Math.sin(rotX), Math.cos(rotX), 0, * 0, 0, 0, 1 * ]; * @type Number[] [/lang] */ rotation: { get: function() { return this._rotation; }, set: function(rotation) { this._rotation = rotation; this._changedRotation = true; } }, /** [lang:ja] * 回転行列にクォータニオンから得られる回転行列をセットする. * @param {enchant.gl.Quat} quat [/lang] [lang:en] * Sets rotation line in rotation line received from quarterion. * @param {enchant.gl.Quat} quat [/lang] */ rotationSet: function(quat) { quat.toMat4(this._rotation); this._changedRotation = true; }, /** [lang:ja] * 回転行列にクォータニオンから得られる回転行列を適用する. * @param {enchant.gl.Quat} quat [/lang] [lang:en] * Applies rotation line in rotation line received from quarterion. * @type {enchant.gl.Quat} quat [/lang] */ rotationApply: function(quat) { quat.toMat4(this.tmpMat); mat4.multiply(this._rotation, this.tmpMat); this._changedRotation = true; }, /** [lang:ja] * Sprite3DのローカルのZ軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Sprite3D in local Z acxis. * @param {Number} radius [/lang] */ rotateRoll: function(rad) { this.rotationApply(new Quat(0, 0, 1, rad)); this._changedRotation = true; }, /** [lang:ja] * Sprite3DのローカルのX軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Sprite3D in local X acxis. * @param {Number} radius [/lang] */ rotatePitch: function(rad) { this.rotationApply(new Quat(1, 0, 0, rad)); this._changedRotation = true; }, /** [lang:ja] * Sprite3DのローカルのY軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Sprite3D in local Y acxis. * @param {Number} radius [/lang] */ rotateYaw: function(rad) { this.rotationApply(new Quat(0, 1, 0, rad)); this._changedRotation = true; }, mesh: { get: function() { return this._mesh; }, set: function(mesh) { if (this.scene != null) { this._mesh._count -= 1; mesh._count += 1; } this._mesh = mesh; } }, /** [lang:ja] * Sprite3Dに適用する変換行列. * @deprecated * @type Number[] [/lang] [lang:en] * Conversion line applied to Sprite3D. * @deprecated * @type Number[] [/lang] */ matrix: { get: function() { return this._matrix; }, set: function(matrix) { this._matrix = matrix; } }, /** [lang:ja] * Sprite3Dの当たり判定に利用されるオブジェクト. * @type enchant.gl.Bounding | enchant.gl.BS | enchant.gl.AABB [/lang] [lang:en] * Object used in Sprite3D collision detection. * @type enchant.gl.Bounding | enchant.gl.BS | enchant.gl.AABB [/lang] */ bounding: { get: function() { return this._bounding; }, set: function(bounding) { this._bounding = bounding; this._bounding.parent = this; } }, /** [lang:ja] * Sprite3Dをタッチ可能にするか決定する. * falseに設定するとタッチ判定の際無視される. * @type bool [/lang] [lang:en] * Determine whether to make Sprite3D touch compatible. * If set to false, will be ignored each time touch detection occurs. * @type bool [/lang] */ touchable: { get: function() { return this._touchable; }, set: function(bool) { this._touchable = bool; if (this._touchable) { this.detectColor[3] = 1.0; } else { this.detectColor[3] = 0.0; } } }, _transform: function(baseMatrix) { if (this._changedTranslation || this._changedRotation || this._changedScale) { mat4.identity(this.modelMat); mat4.translate(this.modelMat, [this._x, this._y, this._z]); mat4.multiply(this.modelMat, this._rotation, this.modelMat) mat4.scale(this.modelMat, [this._scaleX, this._scaleY, this._scaleZ]); mat4.multiply(this.modelMat, this._matrix, this.modelMat); this._changedTranslation = false; this._changedRotation = false; this._changedScale = false; } mat4.multiply(baseMatrix, this.modelMat, this.tmpMat); this._global[0] = this._x; this._global[1] = this._y; this._global[2] = this._z; mat4.multiplyVec3(this.tmpMat, this._global); this.globalX = this._global[0]; this.globalY = this._global[1]; this.globalZ = this._global[2]; }, _render: function() { var useTexture = this.mesh.texture._image ? 1.0 : 0.0; mat4.toInverseMat3(this.tmpMat, this._normMat); mat3.transpose(this._normMat); var attributes = { aVertexPosition: this.mesh._vertices, aVertexColor: this.mesh._colors, aNormal: this.mesh._normals, aTextureCoord: this.mesh._texCoords }; var uniforms = { uModelMat: this.tmpMat, uDetectColor: this.detectColor, uSpecular: this.mesh.texture.specular, uDiffuse: this.mesh.texture.diffuse, uEmission: this.mesh.texture.emission, uAmbient: this.mesh.texture.ambient, uShininess: this.mesh.texture.shininess, uNormMat: this._normMat, uSampler: this.mesh.texture, uUseTexture: useTexture }; var length = this.mesh.indices.length; enchant.Game.instance.GL.renderElements(this.mesh._indices, 0, length, attributes, uniforms); }, _draw: function(scene, hoge, baseMatrix) { this._transform(baseMatrix); if (this.childNodes.length) { for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i]._draw(scene, hoge, this.tmpMat); } } this.dispatchEvent(new enchant.Event('prerender')); if (this.mesh != null) { if (this.program != null) { enchant.Game.instance.GL.setProgram(this.program); this._render(); enchant.Game.instance.GL.setDefaultProgram(); } else { this._render(); } } this.dispatchEvent(new enchant.Event('render')); } }); /** [lang:ja] * Sprite3Dのx座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D x coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.x = 0; /** [lang:ja] * Sprite3Dのy座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D y coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.y = 0; /** [lang:ja] * Sprite3Dのz座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D z coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.z = 0; 'x y z'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Sprite3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedTranslation = true; } }); }); /** [lang:ja] * Sprite3Dのx軸方向に対する拡大率 * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Sprite3D x axis direction expansion rate * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] */ enchant.gl.Sprite3D.prototype.scaleX = 1; /** [lang:ja] * Sprite3Dのy軸方向に対する拡大率 * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Sprite3D y axis direction expansion rate * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] */ enchant.gl.Sprite3D.prototype.scaleY = 1; /** [lang:ja] * Sprite3Dのz軸方向に対する拡大率 * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Sprite3D z axis direction expansion rate * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] */ enchant.gl.Sprite3D.prototype.scaleZ = 1; 'scaleX scaleY scaleZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Sprite3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(scale) { this['_' + prop] = scale; this._changedScale = true; } }); }); /** [lang:ja] * Sprite3Dのグローバルのx座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D global x coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.globalX = 0; /** [lang:ja] * Sprite3Dのグローバルのy座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite 3D global y coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.globalY = 0; /** [lang:ja] * Sprite3Dのグローバルのz座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D global 3D coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.globalZ = 0; /** [lang:ja] * @scope enchant.gl.Camera3D.prototype [/lang] [lang:en] * @scope enchant.gl.Camera3D.prototype [/lang] */ enchant.gl.Camera3D = enchant.Class.create({ /** [lang:ja] * 3Dシーンのカメラを設定するクラス * @example * var scene = new Scene3D(); * var camera = new Camera3D(); * camera.x = 0; * camera.y = 0; * camera.z = 10; * scene.setCamera(camera); * @constructs [/lang] [lang:en] * Class to set 3D scene camera * @example * var scene = new Scene3D(); * var camera = new Camera3D(); * camera.x = 0; * camera.y = 0; * camera.z = 10; * scene.setCamera(camera); * @constructs [/lang] */ initialize: function() { var game = enchant.Game.instance; this.mat = mat4.identity(); this.invMat = mat4.identity(); this.invMatY = mat4.identity(); this._projMat = mat4.create(); mat4.perspective(20, game.width / game.height, 1.0, 1000.0, this._projMat); this._changedPosition = false; this._changedCenter = false; this._changedUpVector = false; this._changedProjection = false; this._x = 0; this._y = 0; this._z = 10; this._centerX = 0; this._centerY = 0; this._centerZ = 0; this._upVectorX = 0; this._upVectorY = 1; this._upVectorZ = 0; this._focus; this._focusing = function() { }; }, projMat: { get: function() { return this._projMat; }, set: function(mat) { this._projMat = mat; this._changedProjection = true; } }, /** [lang:ja] * カメラの注視点をSprite3Dの位置に合わせる. * @param {enchant.gl.Sprite3D} sprite 注視するSprite3D [/lang] [lang:en] * Fit camera perspective to Sprite3D position. * @param {enchant.gl.Sprite3D} sprite Sprite3D being focused on [/lang] */ lookAt: function(sprite) { if (sprite instanceof Sprite3D) { this._centerX = sprite.x; this._centerY = sprite.y; this._centerZ = sprite.z; this._changedCenter = true; } }, /** [lang:ja] * カメラの位置をSprite3Dに近づける. * @param {enchant.gl.Sprite3D} sprite 対象のSprite3D * @param {Number} position 対象との距離 * @param {Number} speed 対象に近づく速度 * @example * var sp = new Sprite3D(); * var camera = new Camera3D(); * // spを注視しながら後ろ10にカメラの位置を近づけ続ける. * sp.addEventListener('enterframe', function() { * camera.lookAt(sp); * camera.chase(sp, -10, 20); * }); [/lang] [lang:en] * Bring camera position closer to that of Sprite3D. * @param {enchant.gl.Sprite3D} sprite Target Sprite3D * @param {Number} position Distance from target * @param {Number} speed Speed of approach to target * @example * var sp = new Sprite3D(); * var camera = new Camera3D(); * // Continue approaching camera position from 10 behind while focusing on sp * sp.addEventListener('enterframe', function() { * camera.lookAt(sp); * camera.chase(sp, -10, 20); * }); [/lang] */ chase: function(sprite, position, speed) { if (sprite instanceof Sprite3D) { var vx = sprite.x + sprite.rotation[8] * position; var vy = sprite.y + sprite.rotation[9] * position; var vz = sprite.z + sprite.rotation[10] * position; this._x += (vx - this._x) / speed; this._y += (vy - this._y) / speed; this._z += (vz - this._z) / speed; this._changedPosition = true; } }, _getForwardVec: function() { var x = this._centerX - this._x; var y = this._centerY - this._y; var z = this._centerZ - this._z; return vec3.normalize([x, y, z]); }, _getSideVec: function() { var f = this._getForwardVec(); var u = this._getUpVec(); return vec3.cross(u, f); }, _getUpVec: function() { var x = this._upVectorX; var y = this._upVectorY; var z = this._upVectorZ; return [x, y, z]; }, _move: function(v, s) { v[0] *= s; v[1] *= s; v[2] *= s; this._x += v[0]; this._y += v[1]; this._z += v[2]; this._centerX += v[0]; this._centerY += v[1]; this._centerZ += v[2]; }, /** [lang:ja] * Camera3DをローカルのZ軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves forward Camera3D. * @param {Number} speed [/lang] */ forward: function(s) { var v = this._getForwardVec(); this._move(v, s); }, /** [lang:ja] * Camera3DをローカルのX軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves side Camera3D. * @param {Number} speed [/lang] */ sidestep: function(s) { var v = this._getSideVec(); this._move(v, s); }, /** [lang:ja] * Camera3DをローカルのY軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves up Camera3D. * @param {Number} speed [/lang] */ altitude: function(s) { var v = this._getUpVec(); this._move(v, s); }, /** [lang:ja] * Camera3DのローカルのZ軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Camera3D in local Z acxis. * @param {Number} radius [/lang] */ rotateRoll: function(rad) { var u = this._getUpVec(); var f = this._getForwardVec(); var x = f[0]; var y = f[1]; var z = f[2]; var quat = new Quat(x, y, z, -rad); var vec = quat.multiplyVec3(u); this._upVectorX = vec[0]; this._upVectorY = vec[1]; this._upVectorZ = vec[2]; this._changedUpVector = true; }, /** [lang:ja] * Camera3DのローカルのX軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Camera3D in local X acxis. * @param {Number} radius [/lang] */ rotatePitch: function(rad) { var u = this._getUpVec(); var f = this._getForwardVec(); var s = this._getSideVec(); var sx = s[0]; var sy = s[1]; var sz = s[2]; var quat = new Quat(sx, sy, sz, -rad); var vec = quat.multiplyVec3(f); this._centerX = this._x + vec[0]; this._centerY = this._y + vec[1]; this._centerZ = this._z + vec[2]; vec = vec3.normalize(quat.multiplyVec3(u)); this._upVectorX = vec[0]; this._upVectorY = vec[1]; this._upVectorZ = vec[2]; this._changedCenter = true; this._changedUpVector = true; }, /** [lang:ja] * Camera3DのローカルのY軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Camera3D in local Y acxis. * @param {Number} radius [/lang] */ rotateYaw: function(rad) { var u = this._getUpVec(); var ux = u[0]; var uy = u[1]; var uz = u[2]; var f = this._getForwardVec() var quat = new Quat(ux, uy, uz, -rad); var vec = quat.multiplyVec3(f); this._centerX = this._x + vec[0]; this._centerY = this._y + vec[1]; this._centerZ = this._z + vec[2]; this._changedCenter = true; }, _updateMatrix: function() { this.mat; this.invMat; this.invMatY; mat4.lookAt( [this._x, this._y, this._z], [this._centerX, this._centerY, this._centerZ], [this._upVectorX, this._upVectorY, this._upVectorZ], this.mat); mat4.lookAt( [0, 0, 0], [-this._x + this._centerX, -this._y + this._centerY, -this._z + this._centerZ], [this._upVectorX, this._upVectorY, this._upVectorZ], this.invMat); mat4.inverse(this.invMat); mat4.lookAt( [0, 0, 0], [-this._x + this._centerX, 0, -this._z + this._centerZ], [this._upVectorX, this._upVectorY, this._upVectorZ], this.invMatY); mat4.inverse(this.invMatY); } }); /** [lang:ja] * カメラのx座標 * @type Number [/lang] [lang:en] * Camera x coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.x = 0; /** [lang:ja] * カメラのy座標 * @type Number [/lang] [lang:en] * Camera y coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.y = 0; /** [lang:ja] * カメラのz座標 * @type Number [/lang] [lang:en] * Camera z coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.z = 0; 'x y z'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Camera3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedPosition = true; } }); }); /** [lang:ja] * カメラの視点のx座標 * @type Number [/lang] [lang:en] * Camera perspective x coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.centerX = 0; /** [lang:ja] * カメラの視点のy座標 * @type Number [/lang] [lang:en] * Camera perspective y coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.centerY = 0; /** [lang:ja] * カメラの視点のz座標 * @type Number [/lang] [lang:en] * Camera perspective z coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.centerZ = 0; 'centerX centerY centerZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Camera3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedCenter = true; } }); }); /** [lang:ja] * カメラの上方向ベクトルのx成分 * @type Number [/lang] [lang:en] * Camera upper vector x component * @type Number [/lang] */ enchant.gl.Camera3D.prototype.upVectorX = 0; /** [lang:ja] * カメラの上方向ベクトルのy成分 * @type Number [/lang] [lang:en] * Camera upper vector y component * @type Number [/lang] */ enchant.gl.Camera3D.prototype.upVectorY = 1; /** [lang:ja] * カメラの上方向ベクトルのz成分 * @type Number [/lang] [lang:en] * Camera upper vector z component * @type Number [/lang] */ enchant.gl.Camera3D.prototype.upVectorZ = 0; 'upVectorX upVectorY upVectorZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Camera3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedUpVector = true; } }); }); /** [lang:ja] * @scope enchant.gl.Scene3D.prototype [/lang] [lang:en] * @scope enchant.gl.Scene3D.prototype [/lang] */ enchant.gl.Scene3D = enchant.Class.create(enchant.EventTarget, { /** [lang:ja] * 表示Sprite3Dツリーのルートになるクラス. * 現在, 複数定義することは出来ず, 最初に定義したScene3Dが返される. * * @example * var scene = new Scene3D(); * var sprite = new Sprite3D(); * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] [lang:en] * Class for displayed Sprite3D tree route. * Currently, multiple definitions are impossible, and the Scene3D defined first will be returned. * * @example * var scene = new Scene3D(); * var sprite = new Sprite3D(); * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] */ initialize: function() { var game = enchant.Game.instance; if (game.currentScene3D) { return game.currentScene3D; } enchant.EventTarget.call(this); /** [lang:ja] * 子要素の配列. * このシーンに子として追加されているSprite3Dの一覧を取得できる. * 子を追加したり削除したりする場合には, この配列を直接操作せずに, * {@link enchant.gl.Scene3D#addChild}や{@link enchant.gl.Scene3D#removeChild}を利用する. * @type enchant.gl.Sprite3D[] [/lang] [lang:en] * Child element array. * A list of Sprite3D added as child classes in this scene can be acquired. * When adding or subtracting child classes, without directly operating this array, * {@link enchant.gl.Scene3D#addChild} or {@link enchant.gl.Scene3D#removeChild} is used. * @type enchant.gl.Sprite3D[] [/lang] */ this.childNodes = []; /** [lang:ja] * 照明の配列. * 現在, シーンに適用される光源は0番目のみ. * このシーンに追加されている光源の一覧を取得する. * 照明を追加したり削除したりする場合には, この配列を直接操作せずに, * {@link enchant.gl.Scene3D#addLight}や{@link enchant.gl.Scene3D#removeLight}を利用する. * @type enchant.gl.PointLight[] [/lang] [lang:en] * Lighting array. * At present, the only light source active in the scene is 0. * Acquires a list of light sources acquired in this scene. * When lighting is added or deleted, without directly operating this array, * {@link enchant.gl.Scene3D#addLight} or {@link enchant.gl.Scene3D#removeLight} is used. * @type enchant.gl.PointLight[] [/lang] */ this.lights = []; this.identityMat = mat4.identity(); this._backgroundColor = [0.0, 0.0, 0.0, 1.0]; var listener = function(e) { for (var i = 0, len = this.childNodes.length; i < len; i++) { var sprite = this.childNodes[i]; sprite.dispatchEvent(e); } }; this.addEventListener('added', listener); this.addEventListener('removed', listener); this.addEventListener('addedtoscene', listener); this.addEventListener('removedfromscene', listener); var that = this; var func = function() { that._draw(); }; game.addEventListener('enterframe', func); var uniforms = {}; uniforms['uUseCamera'] = 0.0; gl.activeTexture(gl.TEXTURE0); game.GL.defaultProgram.setUniforms(uniforms); if (game.currentScene3D == null) { game.currentScene3D = this; } this.setDirectionalLight(new DirectionalLight()); this.setCamera(new Camera3D()); }, /** [lang:ja] * Scene3Dの背景色 * @type Number[] [/lang] [lang:en] * Scene3D background color * @type Number[] [/lang] */ backgroundColor: { get: function() { return this._backgroundColor; }, set: function(arg) { var c = enchant.Game.instance.GL.parseColor(arg); this._backgroundColor = c; gl.clearColor(c[0], c[1], c[2], c[3]); } }, /** [lang:ja] * シーンにSprite3Dを追加する. * 引数に渡されたSprite3Dと, その子を全てシーンに追加する. * シーンに追加されると自動的にSprite3Dは画面上に表示される. * 一度追加したオブジェクトを削除するには{@link enchant.gl.Scene3D#removeChild}を利用する. * @param {enchant.gl.Sprite3D} sprite 追加するSprite3D * @see enchant.gl.Scene3D#removeChild * @see enchant.gl.Scene3D#childNodes [/lang] [lang:en] * Add Sprite3D to scene. * Adds Sprite3D delivered to argument and child classes to scene. * Sprite3D will automatically be displayed on screen if added to scene. * Use {@link enchant.gl.Scene3D#removeChild} to delete object added once. * @param {enchant.gl.Sprite3D} sprite Sprite3D to be added * @see enchant.gl.Scene3D#removeChild * @see enchant.gl.Scene3D#childNodes [/lang] */ addChild: function(sprite) { this.childNodes.push(sprite); sprite.parentNode = sprite.scene = this; sprite.dispatchEvent(new enchant.Event('added')); sprite.dispatchEvent(new enchant.Event('addedtoscene')); sprite.dispatchEvent(new enchant.Event('render')); }, /** [lang:ja] * シーンからSprite3Dを削除する. * シーンから指定されたSprite3Dを削除する. * 削除されたSprite3Dは画面上に表示されなくなる. * Sprite3Dを追加するには{@link enchant.gl.Scene3D#addChild}を利用する. * @param {enchant.gl.Sprite3D} sprite 削除するSprite3D * @see enchant.gl.Scene3D#addChild * @see enchant.gl.Scene3D#childNodes [/lang] [lang:en] * Delete Sprite3D from scene. * Deletes designated Sprite3D from scene. * The deleted Sprite3D will no longer be displayed on the screen. * Use {@link enchant.gl.Scene3D#addChild} to add Sprite3D. * @param {enchant.gl.Sprite3D} sprite Sprite3D to delete * @see enchant.gl.Scene3D#addChild * @see enchant.gl.Scene3D#childNodes [/lang] */ removeChild: function(sprite) { var i; if ((i = this.childNodes.indexOf(sprite)) != -1) { this.childNodes.splice(i, 1); } sprite.parentNode = sprite.scene = null; sprite.dispatchEvent(new enchant.Event('removed')); sprite.dispatchEvent(new enchant.Event('removedfromscene')); }, /** [lang:ja] * シーンのカメラ位置をセットする. * @param {enchant.gl.Camera3D} camera セットするカメラ * @see enchant.gl.Camera3D [/lang] [lang:en] * Sets scene's camera postion. * @param {enchant.gl.Camera3D} camera Camera to set * @see enchant.gl.Camera3D [/lang] */ setCamera: function(camera) { camera._changedPosition = true; camera._changedCenter = true; camera._changedUpVector = true; camera._changedProjection = true; this._camera = camera; enchant.Game.instance.GL.defaultProgram.setUniforms({ uUseCamera: 1.0 }); }, /** [lang:ja] * シーンに設定されているカメラを取得する. * @see enchant.gl.Camera3D * @return {enchant.gl.Camera} [/lang] [lang:en] * Gets camera source in scene. * @see enchant.gl.Camera3D * @return {enchant.gl.Camera} [/lang] */ getCamera: function() { return this._camera; }, /** [lang:ja] * シーンに平行光源を設定する. * @param {enchant.gl.DirectionalLight} light 設定する照明 * @see enchant.gl.DirectionalLight [/lang] [lang:en] * Sets directional light source in scene. * @param {enchant.gl.DirectionalLight} light Lighting to set * @see enchant.gl.DirectionalLight [/lang] */ setDirectionalLight: function(light) { this.directionalLight = light; this.useDirectionalLight = true; enchant.Game.instance.GL.defaultProgram.setUniforms({ uUseDirectionalLight: 1.0 }); }, /** [lang:ja] * シーンに設定されている平行光源を取得する. * @see enchant.gl.DirectionalLight * @return {enchant.gl.DirectionalLight} [/lang] [lang:en] * Gets directional light source in scene. * @see enchant.gl.DirectionalLight * @return {enchant.gl.DirectionalLight} [/lang] */ getDirectionalLight: function() { return this.directionalLight; }, /** [lang:ja] * シーンに照明を追加する. * 現在, シーンに追加しても適用されない. * @param {enchant.gl.PointLight} light 追加する照明 * @see enchant.gl.PointLight [/lang] [lang:en] * Add lighting to scene. * Currently, will not be used even if added to scene. * @param {enchant.gl.PointLight} light Lighting to add * @see enchant.gl.PointLight [/lang] */ addLight: function(light) { this.lights.push(light); this.usePointLight = true; }, /** [lang:ja] * シーンから照明を削除する * @param {enchant.gl.PointLight} light 削除する照明 * @see enchant.gl.PointLight. [/lang] [lang:en] * Delete lighting from scene * @param {enchant.gl.PointLight} light Lighting to delete * @see enchant.gl.PointLight. [/lang] */ removeLight: function(light) { var i; if ((i = this.lights.indexOf(light)) != -1) { this.lights.splice(i, 1); } }, _draw: function(detectTouch) { var game = enchant.Game.instance; var program = game.GL.defaultProgram; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var detect = (detectTouch == 'detect') ? 1.0 : 0.0; var uniforms = { uDetectTouch: detect }; if (this.useDirectionalLight) { if (this.directionalLight._changedDirection) { uniforms['uLightDirection'] = [ this.directionalLight.directionX, this.directionalLight.directionY, this.directionalLight.directionZ ]; this.directionalLight._changedDirection = false; } if (this.directionalLight._changedColor) { uniforms['uLightColor'] = this.directionalLight.color; this.directionalLight._changedColor = false; } } if (this._camera) { if (this._camera._changedPosition || this._camera._changedCenter || this._camera._changedUpVector || this._camera._changedProjection) { this._camera._updateMatrix(); uniforms['uCameraMat'] = this._camera.mat; uniforms['uProjMat'] = this._camera._projMat; uniforms['uLookVec'] = [ this._camera._centerX - this._camera._x, this._camera._centerY - this._camera._y, this._camera._centerZ - this._camera._z ]; } } program.setUniforms(uniforms); mat4.identity(this.identityMat); for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i]._draw(this, detectTouch, this.identityMat); } } }); enchant.gl.collision = {}; var point2point = function(p1, p2) { var vx = p1.x + p1.parent.x - p2.x - p2.parent.x; var vy = p1.y + p1.parent.y - p2.y - p2.parent.y; var vz = p1.z + p1.parent.z - p2.z - p2.parent.z; return (vx * vx + vy * vy + vz * vz); }; var point2BS = function(p, bs) { return (point2point(p, bs) - bs.radius * bs.radius); }; var point2AABB = function(p, aabb) { var ppx = p.x + p.parent.x; var ppy = p.y + p.parent.y; var ppz = p.z + p.parent.z; var px = aabb.parent.x + aabb.x + aabb.scale; var py = aabb.parent.y + aabb.y + aabb.scale; var pz = aabb.parent.z + aabb.z + aabb.scale; var nx = aabb.parent.x + (aabb.x - aabb.scale); var ny = aabb.parent.y + (aabb.y - aabb.scale); var nz = aabb.parent.z + (aabb.z - aabb.scale); var dist = 0; if (ppx < nx) { dist += (ppx - nx) * (ppx - nx); } else if (px < ppx) { dist += (ppx - px) * (ppx - px); } if (ppy < ny) { dist += (ppy - ny) * (ppy - ny); } else if (py < ppy) { dist += (ppy - py) * (ppy - py); } if (ppz < nz) { dist += (ppz - nz) * (ppz - nz); } else if (pz < ppz) { dist += (ppz - pz) * (ppz - pz); } return dist; }; var point2OBB = function(p, obb) { return 1; }; var BS2BS = function(bs1, bs2) { return (point2point(bs1, bs2) - (bs1.radius + bs2.radius) * (bs1.radius + bs2.radius)); }; var BS2AABB = function(bs, aabb) { return (point2AABB(bs, aabb) - bs.radius * bs.radius); }; var BS2OBB = function(bs, obb) { return 1; }; var AABB2AABB = function(aabb1, aabb2) { var px1 = aabb1.parent.x + aabb1.x + aabb1.scale; var py1 = aabb1.parent.y + aabb1.y + aabb1.scale; var pz1 = aabb1.parent.z + aabb1.z + aabb1.scale; var nx1 = aabb1.parent.x + (aabb1.x - aabb1.scale); var ny1 = aabb1.parent.y + (aabb1.y - aabb1.scale); var nz1 = aabb1.parent.z + (aabb1.z - aabb1.scale); var px2 = aabb2.parent.x + aabb2.x + aabb2.scale; var py2 = aabb2.parent.y + aabb2.y + aabb2.scale; var pz2 = aabb2.parent.z + aabb2.z + aabb2.scale; var nx2 = aabb2.parent.x + (aabb2.x - aabb2.scale); var ny2 = aabb2.parent.y + (aabb2.y - aabb2.scale); var nz2 = aabb2.parent.z + (aabb2.z - aabb2.scale); return ((nx2 <= px1) && (nx1 <= px2) && (ny2 <= py1) && (ny1 <= py2) && (nz2 <= pz1) && (nz1 <= pz2)) ? 0.0 : 1.0; }; var AABB2OBB = function(aabb, obb) { return 1; }; var OBB2OBB = function(obb1, obb2) { return 1; }; /** [lang:ja] * @scope enchant.gl.collision.Bounding.prototype [/lang] [lang:en] * @scope enchant.gl.collision.Bounding.prototype [/lang] */ enchant.gl.collision.Bounding = enchant.Class.create({ /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 点として定義されている. * enchant.gl.collision.Boundingを継承したクラスとして, * {@link enchant.gl.collision.BS}, {@link enchant.gl.collision.AABB}, * {@link enchant.gl.collision.OBB}, がある. * 現在, OBBはサポートされていない. * @constructs [/lang] [lang:en] * Class to set Sprite3D collision detection. * Defined as a point. * {@link enchant.gl.collision.BS}, {@link enchant.gl.collision.AABB}, * {@link enchant.gl.collision.OBB} exist as * inherited classes of enchant.gl.collision.Bounding * Currently, OBB is not supported. * @constructs [/lang] */ initialize: function() { this.type = 'point'; this.threshold = 0.0001; this.x = 0; this.y = 0; this.z = 0; this.parent = { x: 0, y: 0, z: 0 }; }, /** [lang:ja] * 点との距離を計算する. * @param {enchant.gl.collision.Bounding} bounding 衝突点オブジェクト * @return {Number} [/lang] [lang:en] * Calculates distance between points. * @param {enchant.gl.collision.Bounding} bounding Collision point object * @return {Number} [/lang] */ toBounding: function(another) { return point2point(this, another); }, /** [lang:ja] * 球との距離を計算する. * @param {enchant.gl.collision.BS} boudning 衝突球オブジェクト * @return {Number} [/lang] [lang:en] * Calculates distance between balls. * @param {enchant.gl.collision.BS} boudning Collision ball object * @return {Number} [/lang] */ toBS: function(another) { return point2BS(this, another); }, /** [lang:ja] * 回転しない立方体との距離を計算する. * 現在, 衝突していなければ1, 衝突していれば0が返される. * @param {enchant.gl.collision.AABB} bounding AABB * @return {Number} [/lang] [lang:en] * Calculates distance from non-rotating cube. * Currently, 0 will be returned with or without collision. * @param {enchant.gl.collision.AABB} bounding AABB * @return {Number} [/lang] */ toAABB: function(another) { return point2AABB(this, another); }, /** [lang:ja] * 回転する直方体との距離を計算する. * 現在, サポートされていない. * @param {enchant.gl.collision.OBB} bounding OBB * @return {Number} [/lang] [lang:en] * Calculates distance from rotating cuboid. * Not currently supported. * @param {enchant.gl.collision.OBB} bounding OBB * @return {Number} [/lang] */ toOBB: function(another) { return point2OBB(this, another); }, /** [lang:ja] * 他の衝突判定オブジェクトとの衝突判定. * 衝突判定オブジェクトか, x, y, zプロパティを持っているオブジェクトとの衝突を判定することができる. * @param {enchant.gl.collision.Bounding|enchant.gl.collision.BS|enchant.gl.collision.AABB|enchant.gl.collision.OBB} bounding 衝突判定オブジェクト * @return {Boolean} [/lang] [lang:en] * Collision detection with other collision detection object. * A collision detection object can detect collision with an object with x, y, z properties. * @param {enchant.gl.collision.Bounding|enchant.gl.collision.BS|enchant.gl.collision.AABB|enchant.gl.collision.OBB} bounding Collision detection object * @return {Boolean} [/lang] */ intersect: function(another) { switch (another.type) { case 'point': return (this.toBounding(another) < this.threshold); case 'BS': return (this.toBS(another) < this.threshold); case 'AABB': return (this.toAABB(another) < this.threshold); case 'OBB': return (this.toOBB(another) < this.threshold); default: return false; } } }); /** [lang:ja] * @scope enchant.gl.collision.BS.prototype [/lang] [lang:en] * @scope enchant.gl.collision.BS.prototype [/lang] */ enchant.gl.collision.BS = enchant.Class.create(enchant.gl.collision.Bounding, { /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 球として定義されている. * @constructs * @see enchant.gl.collision.Bounding [/lang] [lang:en] * Class that sets Sprite3D collision detection. * Defined as a ball. * @constructs * @see enchant.gl.collision.Bounding [/lang] */ initialize: function() { enchant.gl.collision.Bounding.call(this); this.type = 'BS'; this.radius = 0.5; }, toBounding: function(another) { return point2BS(another, this); }, toBS: function(another) { return BS2BS(this, another); }, toAABB: function(another) { return BS2AABB(this, another); }, toOBB: function(another) { return BS2OBB(this, another); } }); /** [lang:ja] * @scope enchant.gl.collision.AABB.prototype [/lang] [lang:en] * @scope enchant.gl.collision.AABB.prototype [/lang] */ enchant.gl.collision.AABB = enchant.Class.create(enchant.gl.collision.Bounding, { /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 回転しない立方体として定義されている. * @constructs * @see enchant.gl.collision.Bounding [/lang] [lang:en] * Class that sets Sprite3D collision detection. * Defined as non-rotating cube. * @constructs * @see enchant.gl.collision.Bounding [/lang] */ initialize: function() { enchant.gl.collision.Bounding.call(this); this.type = 'AABB'; this.scale = 0.5; }, toBounding: function(another) { return point2AABB(another, this); }, toBS: function(another) { return BS2AABB(another, this); }, toAABB: function(another) { return AABB2AABB(this, another); }, toOBB: function(another) { return AABB2OBB(this, another); } }); /** [lang:ja] * @scope enchant.gl.collision.OBB.prototype [/lang] [lang:en] * @scope enchant.gl.collision.OBB.prototype [/lang] */ enchant.gl.collision.OBB = enchant.Class.create(enchant.gl.collision.Bounding, { /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 回転するとして定義されている. * @constructs * @see enchant.gl.collision.Bounding [/lang] [lang:en] * Class that sets Sprite3D collision detection. * Defined as rotating. * @constructs * @see enchant.gl.collision.Bounding [/lang] */ initialize: function() { enchant.gl.collision.Bounding.call(this); this.type = 'OBB'; }, toBounding: function(another) { return point2OBB(another, this); }, toBS: function(another) { return BS2OBB(another, this); }, toAABB: function(another) { return AABB2OBB(another, this); }, toOBB: function(another) { return OBB2OBB(this, another); } }); var DEFAULT_VERTEX_SHADER_SOURCE = '\n\ attribute vec3 aVertexPosition;\n\ attribute vec4 aVertexColor;\n\ \n\ attribute vec3 aNormal;\n\ attribute vec2 aTextureCoord;\n\ \n\ uniform mat4 uModelMat;\n\ uniform mat4 uRotMat;\n\ uniform mat4 uCameraMat;\n\ uniform mat4 uProjMat;\n\ uniform mat3 uNormMat;\n\ uniform float uUseCamera;\n\ \n\ varying vec2 vTextureCoord;\n\ varying vec4 vColor;\n\ varying vec3 vNormal;\n\ \n\ void main() {\n\ vec4 p = uModelMat * vec4(aVertexPosition, 1.0);\n\ gl_Position = uProjMat * (uCameraMat * uUseCamera) * p + uProjMat * p * (1.0 - uUseCamera);\n\ vTextureCoord = aTextureCoord;\n\ vColor = aVertexColor;\n\ vNormal = uNormMat * aNormal;\n\ }'; var DEFAULT_FRAGMENT_SHADER_SOURCE = '\n\ precision highp float;\n\ \n\ uniform sampler2D uSampler;\n\ uniform float uUseDirectionalLight;\n\ uniform vec3 uLightColor;\n\ uniform vec3 uLookVec;\n\ uniform vec4 uAmbient;\n\ uniform vec4 uDiffuse;\n\ uniform vec4 uSpecular;\n\ uniform vec4 uEmission;\n\ uniform vec4 uDetectColor;\n\ uniform float uDetectTouch;\n\ uniform float uUseTexture;\n\ uniform float uShininess;\n\ uniform vec3 uLightDirection;\n\ \n\ varying vec2 vTextureCoord;\n\ varying vec4 vColor;\n\ varying vec3 vNormal;\n\ \n\ \n\ void main() {\n\ vec4 texColor = texture2D(uSampler, vTextureCoord);\n\ vec4 baseColor = vColor;\n\ baseColor *= texColor * uUseTexture + vec4(1.0, 1.0, 1.0, 1.0) * (1.0 - uUseTexture);\n\ float alpha = baseColor.a * uDetectColor.a * uDetectTouch + baseColor.a * (1.0 - uDetectTouch);\n\ if (alpha < 0.2) {\n\ discard;\n\ }\n\ else {\n\ vec4 phongColor = uAmbient;\n\ vec3 N = normalize(vNormal);\n\ vec3 L = normalize(uLightDirection);\n\ vec3 E = normalize(uLookVec);\n\ vec3 R = reflect(-L, N);\n\ float lamber = max(dot(N, L) , 0.0);\n\ phongColor += uDiffuse * lamber;\n\ float s = max(dot(R,-E), 0.0);\n\ vec4 specularColor= uSpecular * pow(s, uShininess) * sign(lamber);\n\ gl_FragColor = ((uEmission * baseColor + specularColor + vec4(baseColor.rgb * phongColor.rgb * uLightColor.rgb, baseColor.a)) \ * uUseDirectionalLight + baseColor * (1.0 - uUseDirectionalLight)) \ * (1.0 - uDetectTouch) + uDetectColor * uDetectTouch;\n\ }\n\ }'; })();
dev/plugins/gl.enchant.js
/* [lang:ja] * gl.enchant.js * @version 0.3.6 * @require enchant.js v0.4.5+ * @require gl-matrix.js 1.3.7+ * @author Ubiquitous Entertainment Inc. * * @description * WebGLを用いた描画ライブラリ * enchant.js と組み合わせることで高度な3D描画と、2D描画を組み合わせることができる * * @detail * ベクトル・行列演算にgl-matrix.jsを使用しています. * gl-matrix.js: * https://github.com/toji/gl-matrix/ * [/lang] [lang:en] * gl.enchant.js * @version 0.3.6 * @require enchant.js v0.4.5+ * @require gl-matrix.js 1.3.7+ * @author Ubiquitous Entertainment Inc. * * @description * Drawing library using WebGL * By combining with enchant.js, high quality 3D drawing and combination with 2D drawing is possible * * @detail * Uses gl-matrix.js in vector, matrix operation. * gl-matrix.js: * https://github.com/toji/gl-matrix/ * [/lang] */ /** [lang:ja] * enchantにgl.enchant.jsのクラスをエクスポートする. [/lang] [lang:en] * Exports gl.enchant.js class to enchant. [/lang] */ enchant.gl = {}; (function() { var CONTEXT_NAME = 'experimental-webgl'; var parentModule = null; (function() { enchant(); if (enchant.nineleap != undefined) { if (enchant.nineleap.memory != undefined && Object.getPrototypeOf(enchant.nineleap.memory) == Object.prototype) { parentModule = enchant.nineleap.memory; } else if (enchant.nineleap != undefined && Object.getPrototypeOf(enchant.nineleap) == Object.prototype) { parentModule = enchant.nineleap; } } else { parentModule = enchant; } })(); enchant.gl.Game = enchant.Class.create(parentModule.Game, { initialize: function(width, height) { parentModule.Game.call(this, width, height); this.GL = new GLUtil(); this.currentScene3D = null; this.addEventListener('enterframe', function(e) { if (!this.currentScene3D) { return; } var nodes = this.currentScene3D.childNodes.slice(); var push = Array.prototype.push; while (nodes.length) { var node = nodes.pop(); node.dispatchEvent(e); node.age++; if (node.childNodes) { push.apply(nodes, node.childNodes); } } }); }, debug: function() { this.GL._enableDebugContext(); this._debug = true; this.addEventListener("enterframe", function(time) { this._actualFps = (1000 / time.elapsed); }); this.start(); } }); var GLUtil = enchant.Class.create({ initialize: function() { var game = enchant.Game.instance; if (typeof game.GL != 'undefined') { return game.GL; } this._canvas; this._gl; this._createStage(game.width, game.height, game.scale); this._prepare(); this.textureManager = new TextureManager(); this.detectColorManager = new DetectColorManager(); this.detectFrameBuffer = new enchant.gl.FrameBuffer(game.width, game.height); this.currentProgram; this.defaultProgram = new enchant.gl.Shader(DEFAULT_VERTEX_SHADER_SOURCE, DEFAULT_FRAGMENT_SHADER_SOURCE); this.setDefaultProgram(); }, setDefaultProgram: function() { this.setProgram(this.defaultProgram); }, setProgram: function(program) { program.use(); this.currentProgram = program; }, _prepare: function() { var width = this._canvas.width; var height = this._canvas.height; gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.viewport(0, 0, width, height); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.enable(gl.DEPTH_TEST); gl.enable(gl.CULL_FACE); }, _createStage: function(width, height, scale) { var div = createParentDiv(); var that = this; var stage = document.getElementById('enchant-stage'); var cvs = this._canvas = createGLCanvas(width, height, scale); var detect = new enchant.Sprite(width, height); var game = enchant.Game.instance; (function() { var color = new Uint8Array(4); var touching = null; var sprite; detect.addEventListener('touchstart', function(e) { var scene = game.currentScene3D; var x = parseInt(e.x); var y = parseInt(this.height - e.y); that.detectFrameBuffer.bind(); scene._draw('detect'); gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, color); sprite = that.detectColorManager.getSpriteByColor(color); if (sprite) { touching = sprite; touching.dispatchEvent(e); } that.detectFrameBuffer.unbind(); }); detect.addEventListener('touchmove', function(e) { if (touching != null) { touching.dispatchEvent(e); } }); detect.addEventListener('touchend', function(e) { if (touching != null) { touching.dispatchEvent(e); } touching = null; }); })(); window['gl'] = this._gl = this._getContext(cvs); div.appendChild(cvs); stage.insertBefore(div, game.rootScene._element); game.rootScene.addChild(detect); }, _getContext: function(canvas, debug) { var ctx = canvas.getContext(CONTEXT_NAME); if (!ctx) { alert('could not initialized WebGL'); throw new Error('could not initialized WebGL'); } if (debug) { ctx = createDebugContext(ctx); } return ctx; }, _enableDebugContext: function() { window['gl'] = this._gl = createDebugContext(this._gl); }, parseColor: function(string) { return parseColor(string); }, renderElements: function(buffer, offset, length, attributes, uniforms) { if (attributes) { this.currentProgram.setAttributes(attributes); } if (uniforms) { this.currentProgram.setUniforms(uniforms); } buffer.bind(); gl.drawElements(gl.TRIANGLES, length, gl.UNSIGNED_SHORT, offset); buffer.unbind(); } }); var parseColor = function(string) { var color = []; if (typeof string == 'string') { if (string.match(/#/)) { string.match(/[0-9a-fA-F]{2}/g).forEach(function(n) { color[color.length] = ('0x' + n - 0) / 255; }); color[color.length] = 1.0; } else if (string.match(/rgba/)) { string.match(/[0-9]{1,3},/g).forEach(function(n) { color[color.length] = parseInt(n, 10) / 255; }); color[color.length] = parseFloat(string.match(/[0-9]\.[0-9]{1,}/)[0]); } else if (string.match(/rgb/)) { string.match(/[0-9]{1,3},/g).forEach(function(n) { color[color.length] = parseInt(n, 10) / 255; }); color[color.length] = 1.0; } } else if (string instanceof Array) { color = string; } return color; }; var createDebugContext = function(context) { var ctx = {}; var names = {}; var type = ''; var val; for (var prop in context) if(context.hasOwnProperty(prop)) { type = typeof context[prop]; val = context[prop]; if (type == 'function') { ctx[prop] = (function(context, prop) { return function() { var value, error; value = context[prop].apply(context, arguments); error = context.getError(); if (error) { console.log(names[error] + '(' + error + ')' + ': ' + prop); console.log(arguments); } return value; } })(context, prop); } else if (type == 'number') { names[val] = prop; ctx[prop] = val; } else { ctx[prop] = val; } } ctx.getNameById = function(i) { return names[i]; }; return ctx; }; var createParentDiv = function() { var div = document.createElement('div'); div.style['position'] = 'absolute'; div.style['z-index'] = -1; div.style[enchant.ENV.VENDOR_PREFIX + 'TransformOrigin'] = '0 0'; return div; }; var createGLCanvas = function(width, height, scale) { var cvs = document.createElement('canvas'); cvs.width = width; cvs.height = height; cvs.style['position'] = 'absolute'; cvs.style['z-index'] = -1; cvs.style[enchant.ENV.VENDOR_PREFIX + 'Transform'] = 'scale(' + scale + ')'; cvs.style[enchant.ENV.VENDOR_PREFIX + 'TransformOrigin'] = '0 0'; return cvs; }; var TextureManager = enchant.Class.create({ initialize: function() { this.storage = {}; }, hasTexture: function(src) { return src in this.storage; }, getWebGLTexture: function(image, flip, wrap, mipmap) { var ret; if (this.hasTexture(image.src)) { ret = this.storage[image.src]; } else { ret = this.createWebGLTexture(image, flip, wrap, mipmap); } return ret; }, isPowerOfTwo: function(n) { return (n > 0) && ((n & (n - 1)) == 0); }, setTextureParameter: function(power, target, wrap, mipmap) { var filter; if (mipmap) { filter = gl.LINEAR_MIPMAP_LINEAR; } else { filter = gl.NEAREST; } if (!power) { wrap = gl.CLAMP_TO_EDGE; } gl.texParameteri(target, gl.TEXTURE_WRAP_S, wrap); gl.texParameteri(target, gl.TEXTURE_WRAP_T, wrap); gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filter); gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filter); }, _texImage: function(image, target) { gl.texImage2D(target, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); }, _writeWebGLTexture: function(image, target, wrap, mipmap) { var power = this.isPowerOfTwo(image.width) && this.isPowerOfTwo(image.height); if (typeof target == 'undefined') { target = gl.TEXTURE_2D; } if (typeof wrap == 'undefined') { wrap = gl.REPEAT; } this.setTextureParameter(power, target, wrap, mipmap); this._texImage(image, target); if (mipmap) { gl.generateMipmap(target); } }, createWebGLTexture: function(image, flip, wrap, mipmap) { var tex = gl.createTexture(); var target = gl.TEXTURE_2D; gl.bindTexture(target, tex); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, flip); this._writeWebGLTexture(image, target, wrap, mipmap); gl.bindTexture(target, null); this.storage[image.src] = tex; return tex; }, createWebGLCubeMapTexture: function(images, wrap, mipmap) { var faceTargets = [ gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ]; var tex = gl.createTexture(); var target, image; gl.bindTexture(gl.TEXTURE_CUBE_MAP, tex); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); for (var i = 0, l = images.length; i < l; i++) { target = faceTargets[i]; image = images[i]; this._writeWebGLTexture(image, target, wrap, mipmap); } gl.bindTexture(gl.TEXTURE_CUBE_MAP, null); return tex; } }); var DetectColorManager = enchant.Class.create({ initialize: function() { this.reference = new Array(); this.detectColorNum = 0; }, attachDetectColor: function(sprite) { this.detectColorNum += 1; this.reference[this.detectColorNum] = sprite; return this._createNewColor(); }, _createNewColor: function() { var n = this.detectColorNum; return [ parseInt(n / 65536) / 255, parseInt(n / 256) / 255, parseInt(n % 256) / 255, 1.0 ]; }, _decodeDetectColor: function(color) { return ~~(color[0] * 65536) + ~~(color[1] * 256) + ~~(color[2]); }, getSpriteByColor: function(color) { return this.reference[this._decodeDetectColor(color)]; } }); /** [lang:ja] * @scope enchant.gl.FrameBuffer.prototype [/lang] [lang:en] * @scope enchant.gl.Framebuffer.prototype [/lang] */ enchant.gl.FrameBuffer = enchant.Class.create({ /** [lang:ja] * WebGLのフレームバッファを管理するクラス. * @param {String} width フレームバッファの横幅 * @param {String} height フレームバッファの縦幅 * @constructs [/lang] [lang:en] * Class for controlling WebGL frame buffers * @param {String} width Frame buffer width * @param {String} height Frame buffer height * @constructs [/lang] */ initialize: function(width, height) { var game = enchant.Game.instance; if (typeof width == 'undefined') { width = game.width; } if (typeof height == 'undefined') { height = game.height; } this.framebuffer = gl.createFramebuffer(); this.colorbuffer = gl.createRenderbuffer(); this.depthbuffer = gl.createRenderbuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); gl.bindRenderbuffer(gl.RENDERBUFFER, this.colorbuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.RGBA4, width, height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, this.colorbuffer); gl.bindRenderbuffer(gl.RENDERBUFFER, this.depthbuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this.depthbuffer); gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.bindRenderbuffer(gl.RENDERBUFFER, null); }, /** [lang:ja] * フレームバッファをバインドする. [/lang] [lang:en] * Bind frame buffer. [/lang] */ bind: function() { gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); }, /** [lang:ja] * フレームバッファをアンバインドする. [/lang] [lang:en] * Unbind frame buffer. [/lang] */ unbind: function() { gl.bindFramebuffer(gl.FRAMEBUFFER, null); }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { gl.deleteFramebuffer(this.framebuffer); gl.deleteFramebuffer(this.colorbuffer); gl.deleteFramebuffer(this.depthbuffer); delete this; } }); /** [lang:ja] * @scope enchant.gl.Shader.prototype [/lang] [lang:en] * @scope enchant.gl.Shader.prototype [/lang] */ enchant.gl.Shader = enchant.Class.create({ /** [lang:ja] * WebGLのシェーダプログラムを管理するクラス. * バーテックスシェーダのソースとフラグメントシェーダのソースを渡すことでシェーダプログラムが作成される. * @param {String} vshader バーテックスシェーダのソース * @param {String} fshader フラグメントシェーダのソース * @constructs [/lang] [lang:en] * Class to control WebGL shader program. * A shader program will be created by delivering the vertex shader source and fragment shader source. * @param {String} vshader Vertex shader source * @param {String} fshader Fragment shader source * @constructs [/lang] */ initialize: function(vshader, fshader) { this._vShaderSource = ''; this._fShaderSource = ''; this._updatedVShaderSource = false; this._updatedFShaderSource = false; this._vShaderProgram = null; this._fShaderProgram = null; this._program = null; this._uniforms = {}; this._attributes = {}; this._attribLocs = {}; this._samplersNum = 0; if (typeof vshader == 'string') { this.vShaderSource = vshader; } if (typeof fshader == 'string') { this.fShaderSource = fshader; } if (this._updatedVShaderSource && this._updatedFShaderSource) { this.compile(); } }, /** [lang:ja] * バーテックスシェーダのソース * @type String [/lang] [lang:en] * Vertex shader source * @type String [/lang] */ vShaderSource: { get: function() { return this._vShaderSource; }, set: function(string) { this._vShaderSource = string; this._updatedVShaderSource = true; } }, /** [lang:ja] * フラグメントシェーダのソース * @type String [/lang] [lang:en] * Fragment shader source * @type String [/lang] */ fShaderSource: { get: function() { return this._fShaderSource; }, set: function(string) { this._fShaderSource = string; this._updatedFShaderSource = true; } }, /** [lang:ja] * シェーダプログラムをコンパイルする. * コンストラクタからシェーダソースを渡した場合は自動的にコンパイルされる. * @example * var shader = new Shader(); * // シェーダプログラムのソースを渡す. * shader.vShaderSource = vert; * shader.fShaderSource = frag; * // コンパイル. * shader.compile(); [/lang] [lang:en] * Compile shader program. * Will be automatically compiled when shader source is delivered from constructor. * @example * var shader = new Shader(); * // Deliver shader program source. * shader.vShaderSource = vert; * shader.fShaderSource = frag; * // Compile. * shader.compile(); [/lang] */ compile: function() { if (this._updatedVShaderSource) { this._prepareVShader(); } if (this._updatedFShaderSource) { this._prepareFShader(); } if (this._program == null) { this._program = gl.createProgram(); } else { gl.detachShader(this._program, this._vShaderProgram); gl.detachShader(this._program, this._fShaderProgram); } gl.attachShader(this._program, this._vShaderProgram); gl.attachShader(this._program, this._fShaderProgram); gl.linkProgram(this._program); if (!gl.getProgramParameter(this._program, gl.LINK_STATUS)) { this._logShadersInfo(); throw 'could not compile shader'; } this._getAttributesProperties(); this._getUniformsProperties(); }, /** [lang:ja] * シェーダプログラムを使用するように設定する. [/lang] [lang:en] * Set shader program to be used. [/lang] */ use: function() { gl.useProgram(this._program); }, /** [lang:ja] * シェーダプログラムにattribute変数をセットする. * enchant.gl.Sprite3Dの内部などで使用される. * @param {*} 値 * @example * var shader = new Shader(vert, frag); * shader.setAttributes({ * aVertexPosition: indices, * aNormal: normals * }); [/lang] [lang:en] * Sets attribute variables to shader program. * Used in enchant.gl.Sprite3D contents and elsewhere. * @param {*} params Level * @example * var shader = new Shader(vert, frag); * shader.setAttributes({ * aVertexPosition: indices, * aNormal: normals * }); [/lang] */ setAttributes: function(params) { for (var prop in params) if(params.hasOwnProperty(prop)) { this._attributes[prop] = params[prop]; } }, /** [lang:ja] * シェーダプログラムにuniform変数をセットする. * enchant.gl.Sprite3Dの内部などで使用される. * @param {*} params 値 * @example * var shader = new Shader(vert, frag); * shader.setUniforms({ * uDiffuse: diffuse, * uLightColor: lightColor * }); [/lang] [lang:en] * Set uniform variables to shader program. * Used in enchant.gl.Sprite3D and elsewhere. * @param {*} params Level * @example * var shader = new Shader(vert, frag); * shader.setUniforms({ * uDiffuse: diffuse, * uLightColor: lightColor * }); [/lang] */ setUniforms: function(params) { for (prop in params) if(params.hasOwnProperty(prop)) { this._uniforms[prop] = params[prop]; } }, _prepareVShader: function() { if (this._vShaderProgram == null) { this._vShaderProgram = gl.createShader(gl.VERTEX_SHADER); } gl.shaderSource(this._vShaderProgram, this._vShaderSource); gl.compileShader(this._vShaderProgram); this._updatedVShaderSource = false; }, _prepareFShader: function() { if (this._fShaderProgram == null) { this._fShaderProgram = gl.createShader(gl.FRAGMENT_SHADER); } gl.shaderSource(this._fShaderProgram, this._fShaderSource); gl.compileShader(this._fShaderProgram); this._updatedFShaderSource = false; }, _logShadersInfo: function() { console.log(gl.getShaderInfoLog(this._vShaderProgram)); console.log(gl.getShaderInfoLog(this._fShaderProgram)); }, _getAttributesProperties: function() { var n; n = gl.getProgramParameter(this._program, gl.ACTIVE_ATTRIBUTES); for (var i = 0; i < n; i++) { var info = gl.getActiveAttrib(this._program, i); this._attribLocs[info.name] = i; addAttributesProperty(this, info); } }, _getUniformsProperties: function() { var n; n = gl.getProgramParameter(this._program, gl.ACTIVE_UNIFORMS); for (var i = 0; i < n; i++) { var info = gl.getActiveUniform(this._program, i); this._uniforms[info.name]; addUniformsProperty(this, info); } }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { gl.deleteProgram(this._vShaderProgram); gl.deleteProgram(this._fShaderProgram); gl.deleteProgram(this._program); delete this; } }); var addAttributesProperty = function(program, info) { var name = info.name; var loc = program._attribLocs[name]; var desc = { get: function() { return 'attrib'; }, set: (function(loc) { return function(buf) { gl.enableVertexAttribArray(loc); buf._setToAttrib(loc); }; })(loc) }; Object.defineProperty(program._attributes, name, desc); }; var addUniformsProperty = function(program, info) { var name = info.name; var loc = gl.getUniformLocation(program._program, info.name); var suffix; var sampler = false; var matrix = false; var desc = { get: function() { return 'uniform'; } }; switch (info.type) { case gl.FLOAT: suffix = '1f'; break; case gl.FLOAT_MAT2: matrix = true; case gl.FLOAT_VEC2: suffix = '2fv'; break; case gl.FLOAT_MAT3: matrix = true; case gl.FLOAT_VEC3: suffix = '3fv'; break; case gl.FLOAT_MAT4: matrix = true; case gl.FLOAT_VEC4: suffix = '4fv'; break; case gl.SAMPLER_2D: case gl.SAMPLER_CUBE: sampler = true; case gl.INT: case gl.BOOL: suffix = '1i'; break; case gl.INT_VEC2: case gl.BOOL_VEC2: suffix = '2iv'; break; case gl.INT_VEC3: case gl.BOOL_VEC3: suffix = '3iv'; break; case gl.INT_VEC4: case gl.BOOL_VEC4: suffix = '4iv'; break; default: throw new Error('no match'); } if (matrix) { desc.set = (function(loc, suffix) { return function(value) { gl['uniformMatrix' + suffix](loc, false, value); }; })(loc, suffix); } else if (sampler) { desc.set = (function(loc, suffix, samplersNum) { return function(texture) { gl.activeTexture(gl.TEXTURE0 + samplersNum); gl.bindTexture(gl.TEXTURE_2D, texture._glTexture); gl['uniform' + suffix](loc, samplersNum); }; })(loc, suffix, program._samplersNum); program._samplersNum++; } else { desc.set = (function(loc, suffix) { return function(value) { gl['uniform' + suffix](loc, value); }; })(loc, suffix); } Object.defineProperty(program._uniforms, name, desc); }; /** [lang:ja] * @scope enchant.gl.Quat.prototype [/lang] [lang:en] * @scope enchant.gl.Quat.prototype [/lang] */ enchant.gl.Quat = enchant.Class.create({ /** [lang:ja] * クォータニオンを簡単に使用するクラス. * @param {Number} x * @param {Number} y * @param {Number} z * @param {Number} rad * @constructs [/lang] [lang:en] * Class that easily uses quaternions. * @param {Number} x * @param {Number} y * @param {Number} z * @param {Number} rad * @constructs [/lang] */ initialize: function(x, y, z, rad) { var l = Math.sqrt(x * x + y * y + z * z); if (l) { x /= l; y /= l; z /= l; } var s = Math.sin(rad / 2); var w = Math.cos(rad / 2); this._quat = quat4.create([x * s, y * s, z * s, w]); }, /** [lang:ja] * クォータニオン同士で球面線形補間を行う. * 自身ともう一つのクォータニオンの間の回転移動を補完したクォータニオンを計算する. * 回転の度合いは0から1の値で表される. 0が自身側, 1がもう一つ側. * 新しいインスタンスが返される. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] [lang:en] * Performs spherical linear interpolation between quarternions. * Calculates quarternion that supplements rotation between this quarternion and another. * Degree of rotation will be expressed in levels from 0 to 1. 0 is the side of this quarternion, 1 is the side of its counterpart. * New instance will be returned. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] */ slerp: function(another, ratio) { var q = new Quat(0, 0, 0, 0); quat4.slerp(this._quat, another._quat, ratio, q); return q; }, /** [lang:ja] * クォータニオン同士で球面線形補間を行う. * 自身ともう一つのクォータニオンの間の回転移動を補完したクォータニオンを計算する. * 回転の度合いは0から1の値で表される. 0が自身側, 1がもう一つ側. * 自身の値が上書きされる. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] [lang:en] * Performs spherical linear interpolation between quarternions. * Calculates quarternion that supplements rotation between this quarternion and another. * Degree of rotation will be expressed in levels from 0 to 1. 0 is the side of this quarternion, 1 is the side of its counterpart. * This side's value will be overwritten. * @param {enchant.gl.Quat} another Quaternion * @param {Number} ratio * @return {enchant.gl.Quat} [/lang] */ slerpApply: function(another, ratio) { quat4.slerp(this._quat, another._quat, ratio); return this; }, /** [lang:ja] * クォータニオンを回転行列に変換する. * @param {Number[]} matrix * @return {Number[]} [/lang] [lang:en] * Convert quarternion to rotation matrix. * @param {Number[]} matrix * @return {Number[]} [/lang] */ toMat4: function(matrix) { quat4.toMat4(this._quat, matrix); return matrix; }, /** [lang:ja] * クォータニオンをベクトルに適用する. * @param {Number[]} vector * @return {Number[]} [/lang] [lang:en] * Apply quarternion to vector. * @param {Number[]} vector * @return {Number[]} [/lang] */ multiplyVec3: function(vector) { quat4.multiplyVec3(this._quat, vector); return vector; } }); /** [lang:ja] * @scope enchant.gl.Light3D.prototype [/lang] [lang:en] * @scope enchant.gl.Light3D.prototype [/lang] */ enchant.gl.Light3D = enchant.Class.create(enchant.EventTarget, { /** [lang:ja] * 光源クラスの親となるクラス. * * @constructs * @extends enchant.EventTarget [/lang] [lang:en] * Light source class parent class. * * @constructs * @extends enchant.EventTarget [/lang] */ initialize: function() { this._changedColor = true; this._color = [0.8, 0.8, 0.8]; }, /** [lang:ja] * 光源の光の色 * @type Number[] [/lang] [lang:en] * Light source light color * @type Number[] [/lang] */ color: { set: function(array) { this._color = array; this._changedColor = true; }, get: function() { return this._color; } } }); /** [lang:ja] * @scope enchant.gl.DirectionalLight.prototype [/lang] [lang:en] * @scope enchant.gl.DirectionalLight.prototype [/lang] */ enchant.gl.DirectionalLight = enchant.Class.create(enchant.gl.Light3D, { /** [lang:ja] * 3Dシーンでの光源を設定するクラス. * 位置を持たない方向光源. * @example * var scene = new Scene3D(); * var light = new DirectionalLight(); * light.color = [1.0, 1.0, 0.0]; * light.directionY = 10; * scene.setDirectionalLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] [lang:en] * Class for setting light source in 3D scene. * Directioned light source without position. * @example * var scene = new Scene3D(); * var light = new DirectionalLight(); * light.color = [1.0, 1.0, 0.0]; * light.directionY = 10; * scene.setDirectionalLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] */ initialize: function() { enchant.gl.Light3D.call(this); this._directionX = 0.5; this._directionY = 0.5; this._directionZ = 1.0; this._changedDirection = true; } }); /** [lang:ja] * 光源の照射方向のx成分 * @type Number [/lang] [lang:en] * Light source exposure direction x component * @type Number [/lang] */ enchant.gl.DirectionalLight.prototype.directionX = 0.5; /** [lang:ja] * 光源の照射方向のy成分 * @type Number [/lang] [lang:en] * Light source exposure direction y component * @type Number [/lang] */ enchant.gl.DirectionalLight.prototype.directionY = 0.5; /** [lang:ja] * 光源の照射方向のz成分 * @type Number [/lang] [lang:en] * Light source exposure direction z component * @type Number [/lang] */ enchant.gl.DirectionalLight.prototype.directionZ = 1.0; /** [lang:ja] * 光源の照射方向 * @type {Number} [/lang] [lang:en] * Light source exposure direction * @type {Number} [/lang] */ 'directionX directionY directionZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.DirectionalLight.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedDirection = true; } }); enchant.gl.DirectionalLight.prototype[prop] = 0; }); /** [lang:ja] * @scope enchant.gl.PointLight.prototype [/lang] [lang:en] * @scope enchant.gl.PointLight.prototype [/lang] */ enchant.gl.PointLight = enchant.Class.create(enchant.gl.Light3D, { /** [lang:ja] * 3Dシーンでの光源を設定するクラス. * 方向を持たない点光源. * 現在, シーンに追加しても適用されない. * @example * var scene = new Scene3D(); * var light = new PointLight(); * light.color = [1.0, 1.0, 0.0]; * light.y = 10; * scene.addLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] [lang:en] * Class that sets 3D scene light source. * Directionless positional light source. * At present, will not be applied even if added to scene. * @example * var scene = new Scene3D(); * var light = new PointLight(); * light.color = [1.0, 1.0, 0.0]; * light.y = 10; * scene.addLight(light); * * @constructs * @extends enchant.gl.Light3D [/lang] */ initialize: function() { enchant.gl.Light3D.call(this); this._x = 0; this._y = 0; this._z = 0; this._changedPosition = true; } }); /** [lang:ja] * 光源のx座標 * @type Number [/lang] [lang:en] * Light source x axis * @type Number [/lang] */ enchant.gl.PointLight.prototype.x = 0; /** [lang:ja] * 光源のy座標 * @type Number [/lang] [lang:en] * Light source y axis * @type Number [/lang] */ enchant.gl.PointLight.prototype.y = 0; /** [lang:ja] * 光源のz座標 * @type Number [/lang] [lang:en] * Light source z axis * @type Number [/lang] */ enchant.gl.PointLight.prototype.z = 0; 'x y z'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.PointLight.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedPosition = true; } }); enchant.gl.PointLight.prototype[prop] = 0; }); /** [lang:ja] * @scope enchant.gl.Texture.prototype [/lang] [lang:en] * @scope enchant.gl.Texture.prototype [/lang] */ enchant.gl.Texture = enchant.Class.create({ /** [lang:ja] * テクスチャ情報を格納するクラス. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "http://example.com/texture.png"; * // 以下のようにも宣言できる. * // var texture = new Texture("http://example.com/texture.png"); * sprite.texture = texture; * @constructs [/lang] [lang:en] * Class to store Sprite3D texture information. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "http://example.com/texture.png"; * // Can also be declared as below. * // var texture = new Texture("http://example.com/texture.png"); * sprite.texture = texture; * @constructs [/lang] */ initialize: function(src, opt) { /** [lang:ja] * 環境光のパラメータ * @type Number[] [/lang] [lang:en] * Ambient light parameter * @type Number[] [/lang] */ this.ambient = [ 0.1, 0.1, 0.1, 1.0 ]; /** [lang:ja] * 拡散光のパラメータ * @type Number[] [/lang] [lang:en] * Light scattering parameter * @type Number[] [/lang] */ this.diffuse = [ 1.0, 1.0, 1.0, 1.0]; /** [lang:ja] * 光の反射量 * @type Number[] [/lang] [lang:en] * Amount of light reflection * @type Number[] [/lang] */ this.specular = [ 1.0, 1.0, 1.0, 1.0 ]; /** [lang:ja] * 光の発光量 * @type Number[] [/lang] [lang:en] * Amount of luminescence * @type Number[] [/lang] */ this.emission = [ 0.0, 0.0, 0.0, 1.0 ]; /** [lang:ja] * 鏡面計数 * @type Number [/lang] [lang:en] * Specular figures * @type Number [/lang] */ this.shininess = 20; this._glTexture = null; this._image = null; this._wrap = 10497; this._mipmap = false; this._flipY = true; if (opt) { var valid = ['flipY', 'wrap', 'mipmap']; for (var prop in opt) if(opt.hasOwnProperty(prop)) { if (valid.indexOf(prop) != -1) { this['_' + prop] = opt[prop]; } } } if (src) { this.src = src; } }, _write: function() { gl.bindTexture(gl.TEXTURE_2D, this._glTexture); enchant.Game.instance.GL.textureManager._writeWebGLTexture(this._image, gl.TEXTURE_2D, this._wrap, this._mipmap); gl.bindTexture(gl.TEXTURE_2D, null); }, /** [lang:ja] * テクスチャ画像のソース. * URLかgame.assets内のデータを指定できる. * @type String * @type enchant.Surface [/lang] [lang:en] * Texture image source. * You can set URL or game.assets data. * @type String * @type enchant.Surface [/lang] */ src: { get: function() { return this._src; }, set: function(source) { if (typeof source == 'undefined' || source == null) { return; } var that = this; var game = enchant.Game.instance; var onload = (function(that) { return function() { that._glTexture = game.GL.textureManager.getWebGLTexture(that._image, that._flipY, that._wrap, that._mipmap); }; })(that); if (source instanceof Image) { this._image = source; onload(); } else if (source instanceof Surface) { this._image = source._element; onload(); } else if (typeof source == 'string') { this._image = new Image(); this._image.onload = onload; this._image.src = source; } else { this._image = source; this._image.src = "c" + Math.random(); onload(); } } } }); /** [lang:ja] * @scope enchant.gl.Buffer.prototype [/lang] [lang:en] * @scope enchant.gl.Buffer.prototype [/lang] */ enchant.gl.Buffer = enchant.Class.create({ /** [lang:ja] * 頂点などの配列情報を管理する. * enchant.gl.Meshのプロパティとして使用される. * @param {*} params parameter * @param {Number[]} array * * @example * var index = [ 0, 1, 2, 2, 3, 0 ]; * var indices = new Buffer(Buffer.INDICES, index); * * @constructs [/lang] [lang:en] * Controls peak and other array information. * Used as enchant.gl.Mesh property. * @param {*} params parameter * @param {Number[]} array * * @example * var index = [ 0, 1, 2, 2, 3, 0 ]; * var indices = new Buffer(Buffer.INDICES, index); * * @constructs [/lang] */ initialize: function(params, array) { this._setParams(params); if (typeof array != 'undefined') { this._array = array; } else { this._array = new Array(); } this._buffer = null; }, /** [lang:ja] * バッファをバインドする. [/lang] [lang:en] * Bind buffer. [/lang] */ bind: function() { gl.bindBuffer(this.btype, this._buffer); }, /** [lang:ja] * バッファをアンバインドする. [/lang] [lang:en] * Unbind buffer. [/lang] */ unbind: function() { gl.bindBuffer(this.btype, null); }, _setParams: function(params) { for (prop in params) if(params.hasOwnProperty(prop)) { this[prop] = params[prop]; } }, _create: function() { this._buffer = gl.createBuffer(); }, _delete: function() { gl.deleteBuffer(this._buffer); }, _bufferData: function() { this.bind(); gl.bufferData(this.btype, new this.Atype(this._array), gl.STATIC_DRAW); this.unbind(); }, _bufferDataFast: function() { this.bind(); gl.bufferData(this.btype, this._array, gl.STATIC_DRAW); this.unbind(); }, _setToAttrib: function(loc) { this.bind(); gl.vertexAttribPointer(loc, this.size, this.type, this.norm, this.stride, this.offset); this.unbind(); }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { this._delete(); delete this; } }); var bufferProto = Object.getPrototypeOf(enchant.gl.Buffer); bufferProto.VERTICES = bufferProto.NORMALS = { size: 3, type: 5126, norm: false, stride: 0, offset: 0, btype: 34962, Atype: Float32Array }; bufferProto.TEXCOORDS = { size: 2, type: 5126, normed: false, stride: 0, ptr: 0, btype: 34962, Atype: Float32Array }; bufferProto.COLORS = { size: 4, type: 5126, normed: false, stride: 0, ptr: 0, btype: 34962, Atype: Float32Array }; bufferProto.INDICES = { size: 3, type: 5123, normed: false, stride: 0, offset: 0, btype: 34963, Atype: Uint16Array }; /** [lang:ja] * @scope enchant.gl.Mesh.prototype [/lang] [lang:en] * @scope enchant.gl.Mesh.prototype [/lang] */ enchant.gl.Mesh = enchant.Class.create({ /** [lang:ja] * 頂点配列やテクスチャを格納するクラス. * enchant.gl.Sprite3Dのプロパティとして使用される. * @constructs [/lang] [lang:en] * Class to store peak arrays and textures. * Used as a sprite property. * @constructs [/lang] */ initialize: function() { this.__count = 0; this._appear = false; this._vertices = new enchant.gl.Buffer(enchant.gl.Buffer.VERTICES); this._normals = new enchant.gl.Buffer(enchant.gl.Buffer.NORMALS); this._colors = new enchant.gl.Buffer(enchant.gl.Buffer.COLORS); this._texCoords = new enchant.gl.Buffer(enchant.gl.Buffer.TEXCOORDS); this._indices = new enchant.gl.Buffer(enchant.gl.Buffer.INDICES); this.texture = new Texture(); }, /** [lang:ja] * Meshの色を変更する. * Mesh.colorsを指定した色の頂点配列にする. * @param {Number[]|String} color z z軸方向の平行移動量 * @example * var sprite = new Sprite3D(); * //紫色に設定. どれも同じ結果が得られる. * sprite.mesh.setBaseColor([1.0, 0.0, 1.0, 0.0]); * sprite.mesh.setBaseColor('#ff00ff'); * sprite.mesh.setBaseColor('rgb(255, 0, 255'); * sprite.mesh.setBaseColor('rgba(255, 0, 255, 1.0'); [/lang] [lang:en] * Change Mesh color. * Becomes peak array for Mesh.colors set color. * @param {Number[]|String} color z Amount of parallel displacement on z axis * @example * var sprite = new Sprite3D(); * //Sets to purple. All yield the same result. * sprite.mesh.setBaseColor([1.0, 0.0, 1.0, 0.0]); * sprite.mesh.setBaseColor('#ff00ff'); * sprite.mesh.setBaseColor('rgb(255, 0, 255'); * sprite.mesh.setBaseColor('rgba(255, 0, 255, 1.0'); [/lang] */ setBaseColor: function(color) { var c = enchant.Game.instance.GL.parseColor(color); var newColors = []; for (var i = 0, l = this.vertices.length / 3; i < l; i++) { Array.prototype.push.apply(newColors, c); } this.colors = newColors; }, /** [lang:ja] * メッシュの面の向きと法線の向きを反転させる. [/lang] [lang:en] * Reverse direction of the mesh surface and the normal vector. [/lang] */ reverse: function() { var norm = this.normals; var idx = this.indices; var t, i, l; for (i = 0, l = norm.length; i < l; i++) { norm[i] *= -1; } for (i = 0, l = idx.length; i < l; i += 3) { t = idx[i + 1]; idx[i + 1] = idx[i + 2]; idx[i + 2] = t; } this._normals._bufferData(); this._indices._bufferData(); }, _createBuffer: function() { for (var prop in this) if(this.hasOwnProperty(prop)) { if (this[prop] instanceof enchant.gl.Buffer) { this[prop]._create(); this[prop]._bufferData(); } } }, _deleteBuffer: function() { for (var prop in this) if(this.hasOwnProperty(prop)) { if (this[prop] instanceof enchant.gl.Buffer) { this[prop]._delete(); } } }, _controlBuffer: function() { if (this._appear) { if (this.__count <= 0) { this._appear = false; this._deleteBuffer(); } } else { if (this.__count > 0) { this._appear = true; this._createBuffer(); } } }, _count: { get: function() { return this.__count; }, set: function(c) { this.__count = c; this._controlBuffer(); } }, _join: function(another, ox, oy, oz) { var triangles = this.vertices.length / 3, vertices = this.vertices.slice(0), i, l; for (i = 0, l = another.vertices.length; i < l; i += 3) { vertices.push(another.vertices[i] + ox); vertices.push(another.vertices[i + 1] + oy); vertices.push(another.vertices[i + 2] + oz); } this.vertices = vertices; this.normals = this.normals.concat(another.normals); this.texCoords = this.texCoords.concat(another.texCoords); this.colors = this.colors.concat(another.colors); var indices = this.indices.slice(0); for (i = 0, l = another.indices.length; i < l; i++) { indices.push(another.indices[i] + triangles); } this.indices = indices; }, /** [lang:ja] * オブジェクトを破棄する. [/lang] [lang:en] * Destroy object. [/lang] */ destroy: function() { this._deleteBuffer(); delete this; } }); /** [lang:ja] * Meshの頂点配列. * 3つの要素を一組として頂点を指定する. 全体の要素数は, 頂点の個数nに対して3nとなる. * 3n, 3n+1, 3n+2番目の要素はそれぞれ, n番目の頂点のx, y, z座標である. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] [lang:en] * Mesh peak array. * Sets 3 elements together at peak. The complete number of elements becomes 3n corresponding to the quantity of the peak. * The 3n, 3n+1, and 3n+2 elements become, respectively, the n peak x, y, and z coordinates. * @example * var sprite = new Sprite3D(); * //Substitute peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] */ enchant.gl.Mesh.prototype.vertices; /** [lang:ja] * Meshの頂点法線ベクトル配列. * 3つの要素を一組として法線ベクトルを指定する. 全体の要素数は, 法線ベクトルの個数nに対して3nとなる. * 3n, 3n+1, 3n+2番目の要素はそれぞれ, n番目の頂点の法線ベクトルのx, y, z成分である. * 法線ベクトルはライティングの影の計算に利用される. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //法線ベクトル配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.normals = [ * 0.0, 0.0, 0.0, //0番目の頂点の法線ベクトル(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点の法線ベクトル(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点の法線ベクトル(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点の法線ベクトル(0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#texCoords [/lang] [lang:en] * Mesh peak normal vector array. * Sets 3 elements as one in normal vector. The complete element number becomes 3n for normal vector quantity n. * 3n, 3n+1, and 3n+2 elements are the n level peak x, y, and z elements of the normal vector. * The normal vector is used in calculations for lighting and shadow. * @example * var sprite = new Sprite3D(); * //Substitutes peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes normal vector array * //Data is a stored in an order of x, y, z, x, y, z... * sprite.normals = [ * 0.0, 0.0, 0.0, //0 level peak normal vector (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 level peak normal vector (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 level peak normal vector (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 level peak normal vector (0.0, 1.0, 0.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#texCoords [/lang] */ enchant.gl.Mesh.prototype.normals; /** [lang:ja] * Meshのテクスチャマッピング配列. * 2つの要素を一組としてuv座標を指定する. 全体の要素数は, 頂点の個数nに対して2nとなる. * 2n, 2n+1番目の要素はそれぞれ, n番目の頂点のテクスチャのu, v座標である. * それぞれの座標のとりうる値は0<=u,v<=1である. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "texture.png"; * sprite.mesh.texture = texture; * * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //uv座標配列を代入 * //データはu, v, u, v...の順に格納する * sprite.mesh.texCoords = [ * 0.0, 0.0, //0番目の頂点のuv座標(0.0, 0.0) * 1.0, 0.0, //1番目の頂点のuv座標(1.0, 0.0) * 1.0, 1.0, //2番目の頂点のuv座標(1.0, 1.0) * 0.0, 1.0 //3番目の頂点のuv座標(0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texture# [/lang] [lang:en] * Mesh texture mapping array. * Sets two elements as one in uv coordinates. The total number of elements becomes 2n in response to the peak quantity. * 2n, 2n+1 level elements correspond to n level peak texture u, v coordinates. * The coordinates that can be acquired for each coordinate correspond to 0<=u, v<=1. * @example * var sprite = new Sprite3D(); * var texture = new Texture(); * texture.src = "texture.png"; * sprite.mesh.texture = texture; * * //Substitutes peak level * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes uv coordinate array * //Data is stored in an order of u, v, u, v... * sprite.texCoords = [ * 0.0, 0.0, //0番目の頂点のuv座標(0.0, 0.0) * 1.0, 0.0, //1番目の頂点のuv座標(1.0, 0.0) * 1.0, 1.0, //2番目の頂点のuv座標(1.0, 1.0) * 0.0, 1.0 //3番目の頂点のuv座標(0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#indices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texture# [/lang] */ enchant.gl.Mesh.prototype.texCoords; /** [lang:ja] * Meshの頂点インデックス配列. * 3つの要素を一組として三角形を指定する.全体の要素数は, 三角形の個数nに対して3nとなる. * インデックスの値は, {@link enchant.gl.Mesh#vertices}で指定した頂点の番号である. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //頂点インデックスを代入 * //3要素一組として, 三角形を描画する * //この例では(0,0,0), (1,0,0), (1,1,0)の三角形と * //(1,1,0), (0,1,0), (0,0,0)の三角形の計二つを描画する * sprite.indices = [ * 0, 1, 2, * 2, 3, 0 * ]; * var scene = new Scene3D(); * scene.addChild(sprite); * @type Integer[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] [lang:en] * Sprite3D peak index array. * 3 elements are set as one in a triangle. The total number of elements becomes 3n corresponding to the triangle's total quantity n. * Index level is the peak number designated in {@link enchant.gl.Sprite3D#vertices}. * @example * var sprite = new Sprite3D(); * //Substitutes peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes peak index * //Draws triangle with 3 elements as one * //In this example the two triangles (0,0,0), (1,0,0), (1,1,0) and * //(1,1,0), (0,1,0), (0,0,0) are drawn. * sprite.indices = [ * 0, 1, 2, * 2, 3, 0 * ]; * var scene = new Scene3D(); * scene.addChild(sprite); * @type Integer[] * @see enchant.gl.Mesh#vertices * @see enchant.gl.Mesh#normals * @see enchant.gl.Mesh#texCoords [/lang] */ enchant.gl.Mesh.prototype.indices; /** [lang:ja] * Meshの頂点色配列. * 4つの要素を一組として頂点色を指定する. 全体の要素数は, 頂点の個数nに対して4nとなる. * 4n, 4n+1, 4n+2, 4n+3番目の要素はそれぞれ, n番目の頂点の色のr, g, b, a成分である. * 頂点色はMeshのtextureにテクスチャが割り当てられていない場合の描画に使用される. * {@link enchant.gl.Mesh#setBaseColor}で一括して変更することができる. * @example * var sprite = new Sprite3D(); * //頂点配列を代入 * //データはx, y, z, x, y, z...の順に格納する * sprite.mesh.vertices = [ * 0.0, 0.0, 0.0, //0番目の頂点(0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1番目の頂点(1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2番目の頂点(1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3番目の頂点(0.0, 1.0, 0.0) * ]; * * //頂点色配列を代入 * //データはr, g, b, ,a, r, g, b, a...の順に格納する * sprite.mesh.normals = [ * 0.0, 0.0, 1.0, 1.0, //0番目の頂点の色(0.0, 0.0, 1.0, 1.0) * 0.0, 1.0, 0.0, 1.0, //1番目の頂点の色(0.0, 1.0, 0.0, 1.0) * 0.0, 1.0, 1.0, 1.0, //2番目の頂点の色(0.0, 1.0, 1.0, 1.0) * 1.0, 0.0, 0.0, 1.0 //3番目の頂点の色(1.0, 0.0, 0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#setBaseColor [/lang] [lang:en] * Mesh peak color array. * The 4 elements are set as one peak color. The entire number of elements becomes 4n corresponding to the peak quantity n. * The 4n, 4n+1, 4n+2, and 4n+3 elements are the n level peak colors r, g, b, a. * Peak color is used for drawing when Texture is not assigned to Sprite3D Texture. * {@link enchant.gl.Mesh#setBaseColor} can be used to bundle together and change. * @example * var sprite = new Sprite3D(); * //Substitutes peak array * //Data is stored in an order of x, y, z, x, y, z... * sprite.vertices = [ * 0.0, 0.0, 0.0, //0 peak (0.0, 0.0, 0.0) * 1.0, 0.0, 0.0, //1 peak (1.0, 0.0, 0.0) * 1.0, 1.0, 0.0, //2 peak (1.0, 1.0, 0.0) * 0.0, 1.0, 0.0 //3 peak (0.0, 1.0, 0.0) * ]; * * //Substitutes peak level array * //Data is stored in an order of r, g, b, a, r, g, b, a... * sprite.normals = [ * 0.0, 0.0, 1.0, 1.0, //0 peak color (0.0, 0.0, 1.0, 1.0) * 0.0, 1.0, 0.0, 1.0, //1 peak color (0.0, 1.0, 0.0, 1.0) * 0.0, 1.0, 1.0, 1.0, //2 peak color (0.0, 1.0, 1.0, 1.0) * 1.0, 0.0, 0.0, 1.0 //3 peak color (1.0, 0.0, 0.0, 1.0) * ]; * @type Number[] * @see enchant.gl.Mesh#setBaseColor [/lang] */ enchant.gl.Mesh.prototype.colors; 'vertices normals colors texCoords indices'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Mesh.prototype, prop, { get: function() { return this['_' + prop]._array; }, set: function(array) { this['_' + prop]._array = array; if (this._appear) { this['_' + prop]._bufferData(); } } }); }); /** [lang:ja] * @scope enchant.gl.Sprite3D.prototype [/lang] [lang:en] * @scope enchant.gl.Sprite3D.prototype [/lang] */ enchant.gl.Sprite3D = enchant.Class.create(enchant.EventTarget, { /** [lang:ja] * Sprite3D表示機能を持ったクラス. * <p>{@link enchant.gl.Scene3D}のインスタンスに追加することで, 画面上に表示することができる. * {@link enchant.gl.Sprite3D#vertices}, {@link enchant.gl.Sprite3D#indices}, * {@link enchant.gl.Sprite3D#normals}などを変更することで, 任意のSprite3Dを描画することもでき, * テクスチャなども貼付けることができる.</p> * <p>また, Sprite3Dを子として追加することも可能で, 子は全て親を基準とした座標系で描画される.</p> * @example * //シーンの初期化 * var scene = new Scene3D(); * //Sprite3Dの初期化 * var sprite = new Sprite3D(); * //Sprite3Dをシーンに追加 * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] [lang:en] * Class with Sprite3D display function. * <p>By adding {@link enchant.gl.Scene3D} instance, you can display atop an image. * By changing {@link enchant.gl.Sprite3D#vertices}, {@link enchant.gl.Sprite3D#indices}, * {@link enchant.gl.Sprite3D#normals} and others, you can freely draw Sprite3D, * as well as pasting texture and more.</p> * <p>In addition, it is also possible to add Sprite3D as a child, and all child classes will be drawn with coordinates based on their parents.</p> * @example * //Scene initialization * var scene = new Scene3D(); * //Sprite3D initialization * var sprite = new Sprite3D(); * //Add Sprite3D to scene * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] */ initialize: function() { enchant.EventTarget.call(this); /** [lang:ja] * 子Sprite3D要素の配列. * この要素に子として追加されているSprite3Dの一覧を取得できる. * 子を追加したり削除したりする場合には, この配列を直接操作せずに, * {@link enchant.gl.Sprite3D#addChild}や{@link enchant.gl.Sprite3D#removeChild}を利用する. * @type enchant.gl.Sprite3D[] * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#removeChild [/lang] [lang:en] * Array for child Sprite 3D element. * Can acquire list of Sprite3Ds added as child classes to this element. * When adding or subtracting child classes, without directly operating this array, * {@link enchant.gl.Sprite3D#addChild} or {@link enchant.gl.Sprite3D#removeChild} is used. * @type enchant.gl.Sprite3D[] * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#removeChild [/lang] */ this.childNodes = []; /** [lang:ja] * このSprite3Dが現在追加されているシーンオブジェクト. * どのシーンにも追加されていないときにはnull. * @type enchant.gl.Scene3D * @see enchant.gl.Scene3D#addChild [/lang] [lang:en] * The scene object currently added by this Sprite3D. * When no scene is added this is null. * @type enchant.gl.Scene3D * @see enchant.gl.Scene3D#addChild [/lang] */ this.scene = null; /** [lang:ja] * Sprite3Dの親要素. * 親が存在しない場合にはnull. * @type enchant.gl.Sprite3D|enchant.gl.Scene3D [/lang] [lang:en] * Sprite3D parent element. * When no parent exists this is null. * @type enchant.gl.Sprite3D|enchant.gl.Scene3D [/lang] */ this.parentNode = null; /** [lang:ja] * Sprite3Dに適用されるメッシュオブジェクト. * @type enchant.gl.Mesh * @example * var sprite = new Sprite3D(); * sprite.mesh = new Mesh(); [/lang] [lang:en] * Mesh object applied to Sprite3D. * @type enchant.gl.Mesh * @example * var sprite = new Sprite3D(); * sprite.mesh = new Mesh(); [/lang] */ this._mesh = null; this.program = null; this.bounding = new BS(); this.bounding.parent = this; this.age = 0; this._x = 0; this._y = 0; this._z = 0; this._scaleX = 1; this._scaleY = 1; this._scaleZ = 1; this._changedTranslation = true; this._changedRotation = true; this._changedScale = true; this._touchable = true; this._global = vec3.create(); this.globalX = 0; this.globalY = 0; this.globalZ = 0; this._matrix = mat4.identity(); this.tmpMat = mat4.identity(); this.modelMat = mat4.identity(); this._rotation = mat4.identity(); this._normMat = mat3.identity(); var game = enchant.Game.instance; this.detectColor = game.GL.detectColorManager.attachDetectColor(this); var parentEvent = function(e) { if (this.parentNode instanceof Sprite3D) { this.parentNode.dispatchEvent(e); } } this.addEventListener('touchstart', parentEvent); this.addEventListener('touchmove', parentEvent); this.addEventListener('touchend', parentEvent); var added = function(e) { if (this.mesh != null) { this.mesh._count++; } if (this.childNodes.length) { for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i].scene = this.scene; this.childNodes[i].dispatchEvent(e); } } }; this.addEventListener('addedtoscene', added); var removed = function(e) { if (this.mesh != null) { this.mesh._count--; } if (this.childNodes.length) { for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i].scene = null; this.childNodes[i].dispatchEvent(e); } } }; this.addEventListener('removedfromscene', removed); }, /** [lang:ja] * Sprite3Dの複製を作成する. * 位置,回転行列などがコピーされた新しいインスタンスが返される. * @example * var sp = new Sprite3D(); * sp.x = 15; * var sp2 = sp.clone(); * //sp2.x = 15; * @return {enchant.gl.Sprite3D} [/lang] [lang:en] * Executes the reproduction of Sprite3D. * Position, rotation line, and others will be returned to a copied, new instance. * @example * var sp = new Sprite3D(); * sp.x = 15; * var sp2 = sp.clone(); * //sp2.x = 15; * @return {enchant.gl.Sprite3D} [/lang] */ clone: function() { var clone = new Sprite3D(); for (prop in this) { if (typeof this[prop] == 'number' || typeof this[prop] == 'string') { clone[prop] = this[prop]; } else if (this[prop] instanceof WebGLBuffer) { clone[prop] = this[prop]; } else if (this[prop] instanceof Float32Array) { clone[prop] = new Float32Array(this[prop]); } else if (this[prop] instanceof Array && prop != 'childNodes' && prop != 'detectColor') { clone[prop] = this[prop].slice(0); } } if (this.mesh != null) { clone.mesh = this.mesh; } if (this.childNodes) { for (var i = 0, l = this.childNodes.length; i < l; i++) { clone.addChild(this.childNodes[i].clone()); } } return clone; }, /** [lang:ja] * 他のSprite3Dの状態をセットする. * Colladaファイルを読み込んだassetsに対して使用できる. * @example * var sp = new Sprite3D(); * sp.set(game.assets['sample.dae']); * //sample.daeのモデル情報を持ったSprite3Dになる * [/lang] [lang:en] * Sets condition of other Sprite3D. * Can be used corresponding Collada file's loaded assets. * @example * var sp = new Sprite3D(); * sp.set(game.assets['sample.dae']); * //Becomes Sprite3D with sample.dae model information * [/lang] */ set: function(sprite) { for (prop in sprite) { if (typeof sprite[prop] == 'number' || typeof sprite[prop] == 'string') { this[prop] = sprite[prop]; } else if (sprite[prop] instanceof WebGLBuffer) { this[prop] = sprite[prop]; } else if (sprite[prop] instanceof Float32Array) { this[prop] = new Float32Array(sprite[prop]); } else if (sprite[prop] instanceof Array && prop != 'childNodes' && prop != 'detectColor') { this[prop] = sprite[prop].filter(function() { return true; }); } } if (sprite.mesh != null) { this.mesh = sprite.mesh; } if (sprite.childNodes) { for (var i = 0, l = sprite.childNodes.length; i < l; i++) { this.addChild(sprite.childNodes[i].clone()); } } }, /** [lang:ja] * 子Sprite3Dを追加する. * 追加が完了すると, 子Sprite3Dに対してaddedイベントが発生する. * 親が既にシーンに追加されていた場合には, そのシーンに追加され, * addedtosceneイベントが発生する. * @param {enchant.gl.Sprite3D} sprite 追加する子Sprite3D. * @example * var parent = new Sprite3D(); * var child = new Sprite3D(); * //Sprite3Dを別のSprite3Dに子として追加 * parent.addChild(child); * @see enchant.gl.Sprite3D#removeChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] [lang:en] * Add child Sprite3D. * When it is added, an "added" event will be created for child Sprite3D. * When a parent is already added to scene, it will be added to scene, * and an "addedtoscene" event will be created. * Child Sprite3D for adding @param {enchant.gl.Sprite3D} sprite. * @example * var parent = new Sprite3D(); * var child = new Sprite3D(); * //Add Sprite3D as child to another Sprite3D * parent.addChild(child); * @see enchant.gl.Sprite3D#removeChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] */ addChild: function(sprite) { this.childNodes.push(sprite); sprite.parentNode = this; sprite.dispatchEvent(new enchant.Event('added')); if (this.scene) { sprite.scene = this.scene; sprite.dispatchEvent(new enchant.Event('addedtoscene')); } }, /** [lang:ja] * 指定された子Sprite3Dを削除する. * 削除が完了すると, 子Sprite3Dに対してremovedイベントが発生する. * シーンに追加されていた場合には, そのシーンからも削除され, * removedfromsceneイベントが発生する. * @param {enchant.gl.Sprite3D} sprite 削除する子Sprite3D. * @example * var scene = new Scene3D(); * //sceneの一番目の子を削除 * scene.removeChild(scene.childNodes[0]); * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] [lang:en] * Deletes designated child Sprite3D. * When deletion is complete, a "removed" event will be created for child Sprite3D. * When added to scene, it will be deleted from that scene, * and a "removedfromscene" event will be created. * Child Sprite3D for deleting @param {enchant.gl.Sprite3D} sprite. * @example * var scene = new Scene3D(); * //Deletes scene's first child * scene.removeChild(scene.childNodes[0]); * @see enchant.gl.Sprite3D#addChild * @see enchant.gl.Sprite3D#childNodes * @see enchant.gl.Sprite3D#parentNode [/lang] */ removeChild: function(sprite) { var i; if ((i = this.childNodes.indexOf(sprite)) != -1) { this.childNodes.splice(i, 1); } sprite.parentNode = null; sprite.dispatchEvent(new enchant.Event('removed')); if (this.scene) { sprite.scene = null; sprite.dispatchEvent(new enchant.Event('removedfromscene')); } }, /** [lang:ja] * 他のオブジェクトとの衝突判定. * 衝突判定オブジェクトか, x, y, zプロパティを持っているオブジェクトとの衝突を判定することができる. * @param {enchant.gl.Sprite3D} bounding 対象のオブジェクト * @return {Boolean} [/lang] [lang:en] * Other object collison detection. * Can detect collisions with collision detection objects with x, y, z properties. * @param {enchant.gl.Sprite3D} bounding Target object * @return {Boolean} [/lang] */ intersect: function(another) { return this.bounding.intersect(another.bounding); }, /** [lang:ja] * Sprite3Dを平行移動する. * 現在表示されている位置から, 各軸に対して指定された分だけ平行移動をする. * @param {Number} x x軸方向の平行移動量 * @param {Number} y y軸方向の平行移動量 * @param {Number} z z軸方向の平行移動量 * @example * var sprite = new Sprite3D(); * //x軸方向に10, y軸方向に3, z軸方向に-20平行移動 * sprite.translate(10, 3, -20); * @see enchant.gl.Sprite3D#x * @see enchant.gl.Sprite3D#y * @see enchant.gl.Sprite3D#z * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Parallel displacement of Sprite3D. * Displaces each coordinate a designated amount from its current location. * @param {Number} x Parallel displacement of x axis * @param {Number} y Parallel displacement of y axis * @param {Number} z Parallel displacement of z axis * @example * var sprite = new Sprite3D(); * //Parallel displacement by 10 along the x axis, 3 along the y axis, and -20 along the z axis * sprite.translate(10, 3, -20); * @see enchant.gl.Sprite3D#x * @see enchant.gl.Sprite3D#y * @see enchant.gl.Sprite3D#z * @see enchant.gl.Sprite3D#scale [/lang] */ translate: function(x, y, z) { this._x += x; this._y += y; this._z += z; this._changedTranslation = true; }, /** [lang:ja] * Sprite3DをローカルのZ軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves forward Sprite3D. * @param {Number} speed [/lang] */ forward: function(speed) { var x = this._rotation[8] * speed; var y = this._rotation[9] * speed; var z = this._rotation[10] * speed; this.translate(x, y, z); }, /** [lang:ja] * Sprite3DをローカルのX軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves side Sprite3D. * @param {Number} speed [/lang] */ sidestep: function(speed) { var x = this._rotation[0] * speed; var y = this._rotation[1] * speed; var z = this._rotation[2] * speed; this.translate(x, y, z); }, /** [lang:ja] * Sprite3DをローカルのY軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves up Sprite3D. * @param {Number} speed [/lang] */ altitude: function(speed) { var x = this._rotation[4] * speed; var y = this._rotation[5] * speed; var z = this._rotation[6] * speed; this.translate(x, y, z); }, /** [lang:ja] * Sprite3Dを拡大縮小する. * 現在の拡大率から, 各軸に対して指定された倍率分だけ拡大縮小をする. * @param {Number} x x軸方向の拡大率 * @param {Number} y y軸方向の拡大率 * @param {Number} z z軸方向の拡大率 * @example * var sprite = new Sprite3D(); * //x軸方向に2.0倍, y軸方向に3.0倍, z軸方向に0.5倍に拡大する * sprite.scale(2,0, 3.0, 0.5); * @see enchant.gl.Sprite3D#scaleX * @see enchant.gl.Sprite3D#scaleY * @see enchant.gl.Sprite3D#scaleZ * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Expand or contract Sprite3D. * Expands each axis by a designated expansion rate. * @param {Number} x x axis expansion rate * @param {Number} y y axis expansion rate * @param {Number} z z axis expansion rate * @example * var sprite = new Sprite3D(); * //Expand x axis by 2.0 times, y axis by 3.0 times, and z axis by 0.5 times * sprite.scale(2,0, 3.0, 0.5); * @see enchant.gl.Sprite3D#scaleX * @see enchant.gl.Sprite3D#scaleY * @see enchant.gl.Sprite3D#scaleZ * @see enchant.gl.Sprite3D#translate [/lang] */ scale: function(x, y, z) { this._scaleX *= x; this._scaleY *= y; this._scaleZ *= z; this._changedScale = true; }, /** [lang:ja] * Sprite3Dの名前 * @type String [/lang] [lang:en] * Sprite3D name * @type String [/lang] */ name: { get: function() { return this._name; }, set: function(name) { this._name = name; } }, /** [lang:ja] * Sprite3Dの回転行列. * 配列は長さ16の一次元配列であり, 行優先の4x4行列として解釈される. * @example * var sprite = new Sprite3D(); * //x軸周りに45度回転 * var rotX = Math.PI() / 4; * sprite.rotation = [ * 1, 0, 0, 0, * 0, Math.cos(rotX), -Math.sin(rotX), 0, * 0, Math.sin(rotX), Math.cos(rotX), 0, * 0, 0, 0, 1 * ]; * @type Number[] [/lang] [lang:en] * Sprite3D rotation line. * Array is a one-dimensional array of length 16, interpreted as the 4x4 line destination. * @example * var sprite = new Sprite3D(); * //45 degree rotation along the x axis * var rotX = Math.PI() / 4; * sprite.rotation = [ * 1, 0, 0, 0, * 0, Math.cos(rotX), -Math.sin(rotX), 0, * 0, Math.sin(rotX), Math.cos(rotX), 0, * 0, 0, 0, 1 * ]; * @type Number[] [/lang] */ rotation: { get: function() { return this._rotation; }, set: function(rotation) { this._rotation = rotation; this._changedRotation = true; } }, /** [lang:ja] * 回転行列にクォータニオンから得られる回転行列をセットする. * @param {enchant.gl.Quat} quat [/lang] [lang:en] * Sets rotation line in rotation line received from quarterion. * @param {enchant.gl.Quat} quat [/lang] */ rotationSet: function(quat) { quat.toMat4(this._rotation); this._changedRotation = true; }, /** [lang:ja] * 回転行列にクォータニオンから得られる回転行列を適用する. * @param {enchant.gl.Quat} quat [/lang] [lang:en] * Applies rotation line in rotation line received from quarterion. * @type {enchant.gl.Quat} quat [/lang] */ rotationApply: function(quat) { quat.toMat4(this.tmpMat); mat4.multiply(this._rotation, this.tmpMat); this._changedRotation = true; }, /** [lang:ja] * Sprite3DのローカルのZ軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Sprite3D in local Z acxis. * @param {Number} radius [/lang] */ rotateRoll: function(rad) { this.rotationApply(new Quat(0, 0, 1, rad)); this._changedRotation = true; }, /** [lang:ja] * Sprite3DのローカルのX軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Sprite3D in local X acxis. * @param {Number} radius [/lang] */ rotatePitch: function(rad) { this.rotationApply(new Quat(1, 0, 0, rad)); this._changedRotation = true; }, /** [lang:ja] * Sprite3DのローカルのY軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Sprite3D in local Y acxis. * @param {Number} radius [/lang] */ rotateYaw: function(rad) { this.rotationApply(new Quat(0, 1, 0, rad)); this._changedRotation = true; }, mesh: { get: function() { return this._mesh; }, set: function(mesh) { if (this.scene != null) { this._mesh._count -= 1; mesh._count += 1; } this._mesh = mesh; } }, /** [lang:ja] * Sprite3Dに適用する変換行列. * @deprecated * @type Number[] [/lang] [lang:en] * Conversion line applied to Sprite3D. * @deprecated * @type Number[] [/lang] */ matrix: { get: function() { return this._matrix; }, set: function(matrix) { this._matrix = matrix; } }, /** [lang:ja] * Sprite3Dの当たり判定に利用されるオブジェクト. * @type enchant.gl.Bounding | enchant.gl.BS | enchant.gl.AABB [/lang] [lang:en] * Object used in Sprite3D collision detection. * @type enchant.gl.Bounding | enchant.gl.BS | enchant.gl.AABB [/lang] */ bounding: { get: function() { return this._bounding; }, set: function(bounding) { this._bounding = bounding; this._bounding.parent = this; } }, /** [lang:ja] * Sprite3Dをタッチ可能にするか決定する. * falseに設定するとタッチ判定の際無視される. * @type bool [/lang] [lang:en] * Determine whether to make Sprite3D touch compatible. * If set to false, will be ignored each time touch detection occurs. * @type bool [/lang] */ touchable: { get: function() { return this._touchable; }, set: function(bool) { this._touchable = bool; if (this._touchable) { this.detectColor[3] = 1.0; } else { this.detectColor[3] = 0.0; } } }, _transform: function(baseMatrix) { if (this._changedTranslation || this._changedRotation || this._changedScale) { mat4.identity(this.modelMat); mat4.translate(this.modelMat, [this._x, this._y, this._z]); mat4.multiply(this.modelMat, this._rotation, this.modelMat) mat4.scale(this.modelMat, [this._scaleX, this._scaleY, this._scaleZ]); mat4.multiply(this.modelMat, this._matrix, this.modelMat); this._changedTranslation = false; this._changedRotation = false; this._changedScale = false; } mat4.multiply(baseMatrix, this.modelMat, this.tmpMat); this._global[0] = this._x; this._global[1] = this._y; this._global[2] = this._z; mat4.multiplyVec3(this.tmpMat, this._global); this.globalX = this._global[0]; this.globalY = this._global[1]; this.globalZ = this._global[2]; }, _render: function() { var useTexture = this.mesh.texture._image ? 1.0 : 0.0; mat4.toInverseMat3(this.tmpMat, this._normMat); mat3.transpose(this._normMat); var attributes = { aVertexPosition: this.mesh._vertices, aVertexColor: this.mesh._colors, aNormal: this.mesh._normals, aTextureCoord: this.mesh._texCoords }; var uniforms = { uModelMat: this.tmpMat, uDetectColor: this.detectColor, uSpecular: this.mesh.texture.specular, uDiffuse: this.mesh.texture.diffuse, uEmission: this.mesh.texture.emission, uAmbient: this.mesh.texture.ambient, uShininess: this.mesh.texture.shininess, uNormMat: this._normMat, uSampler: this.mesh.texture, uUseTexture: useTexture }; var length = this.mesh.indices.length; enchant.Game.instance.GL.renderElements(this.mesh._indices, 0, length, attributes, uniforms); }, _draw: function(scene, hoge, baseMatrix) { this._transform(baseMatrix); if (this.childNodes.length) { for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i]._draw(scene, hoge, this.tmpMat); } } this.dispatchEvent(new enchant.Event('prerender')); if (this.mesh != null) { if (this.program != null) { enchant.Game.instance.GL.setProgram(this.program); this._render(); enchant.Game.instance.GL.setDefaultProgram(); } else { this._render(); } } this.dispatchEvent(new enchant.Event('render')); } }); /** [lang:ja] * Sprite3Dのx座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D x coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.x = 0; /** [lang:ja] * Sprite3Dのy座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D y coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.y = 0; /** [lang:ja] * Sprite3Dのz座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D z coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.z = 0; 'x y z'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Sprite3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedTranslation = true; } }); }); /** [lang:ja] * Sprite3Dのx軸方向に対する拡大率 * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Sprite3D x axis direction expansion rate * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] */ enchant.gl.Sprite3D.prototype.scaleX = 1; /** [lang:ja] * Sprite3Dのy軸方向に対する拡大率 * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Sprite3D y axis direction expansion rate * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] */ enchant.gl.Sprite3D.prototype.scaleY = 1; /** [lang:ja] * Sprite3Dのz軸方向に対する拡大率 * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] [lang:en] * Sprite3D z axis direction expansion rate * @default 1.0 * @type Number * @see enchant.gl.Sprite3D#scale [/lang] */ enchant.gl.Sprite3D.prototype.scaleZ = 1; 'scaleX scaleY scaleZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Sprite3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(scale) { this['_' + prop] = scale; this._changedScale = true; } }); }); /** [lang:ja] * Sprite3Dのグローバルのx座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D global x coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.globalX = 0; /** [lang:ja] * Sprite3Dのグローバルのy座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite 3D global y coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.globalY = 0; /** [lang:ja] * Sprite3Dのグローバルのz座標. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] [lang:en] * Sprite3D global 3D coordinates. * @default 0 * @type Number * @see enchant.gl.Sprite3D#translate [/lang] */ enchant.gl.Sprite3D.prototype.globalZ = 0; /** [lang:ja] * @scope enchant.gl.Camera3D.prototype [/lang] [lang:en] * @scope enchant.gl.Camera3D.prototype [/lang] */ enchant.gl.Camera3D = enchant.Class.create({ /** [lang:ja] * 3Dシーンのカメラを設定するクラス * @example * var scene = new Scene3D(); * var camera = new Camera3D(); * camera.x = 0; * camera.y = 0; * camera.z = 10; * scene.setCamera(camera); * @constructs [/lang] [lang:en] * Class to set 3D scene camera * @example * var scene = new Scene3D(); * var camera = new Camera3D(); * camera.x = 0; * camera.y = 0; * camera.z = 10; * scene.setCamera(camera); * @constructs [/lang] */ initialize: function() { var game = enchant.Game.instance; this.mat = mat4.identity(); this.invMat = mat4.identity(); this.invMatY = mat4.identity(); this._projMat = mat4.create(); mat4.perspective(20, game.width / game.height, 1.0, 1000.0, this._projMat); this._changedPosition = false; this._changedCenter = false; this._changedUpVector = false; this._changedProjection = false; this._x = 0; this._y = 0; this._z = 10; this._centerX = 0; this._centerY = 0; this._centerZ = 0; this._upVectorX = 0; this._upVectorY = 1; this._upVectorZ = 0; this._focus; this._focusing = function() { }; }, projMat: { get: function() { return this._projMat; }, set: function(mat) { this._projMat = mat; this._changedProjection = true; } }, /** [lang:ja] * カメラの注視点をSprite3Dの位置に合わせる. * @param {enchant.gl.Sprite3D} sprite 注視するSprite3D [/lang] [lang:en] * Fit camera perspective to Sprite3D position. * @param {enchant.gl.Sprite3D} sprite Sprite3D being focused on [/lang] */ lookAt: function(sprite) { if (sprite instanceof Sprite3D) { this._centerX = sprite.x; this._centerY = sprite.y; this._centerZ = sprite.z; this._changedCenter = true; } }, /** [lang:ja] * カメラの位置をSprite3Dに近づける. * @param {enchant.gl.Sprite3D} sprite 対象のSprite3D * @param {Number} position 対象との距離 * @param {Number} speed 対象に近づく速度 * @example * var sp = new Sprite3D(); * var camera = new Camera3D(); * // spを注視しながら後ろ10にカメラの位置を近づけ続ける. * sp.addEventListener('enterframe', function() { * camera.lookAt(sp); * camera.chase(sp, -10, 20); * }); [/lang] [lang:en] * Bring camera position closer to that of Sprite3D. * @param {enchant.gl.Sprite3D} sprite Target Sprite3D * @param {Number} position Distance from target * @param {Number} speed Speed of approach to target * @example * var sp = new Sprite3D(); * var camera = new Camera3D(); * // Continue approaching camera position from 10 behind while focusing on sp * sp.addEventListener('enterframe', function() { * camera.lookAt(sp); * camera.chase(sp, -10, 20); * }); [/lang] */ chase: function(sprite, position, speed) { if (sprite instanceof Sprite3D) { var vx = sprite.x + sprite.rotation[8] * position; var vy = sprite.y + sprite.rotation[9] * position; var vz = sprite.z + sprite.rotation[10] * position; this._x += (vx - this._x) / speed; this._y += (vy - this._y) / speed; this._z += (vz - this._z) / speed; this._changedPosition = true; } }, _getForwardVec: function() { var x = this._centerX - this._x; var y = this._centerY - this._y; var z = this._centerZ - this._z; return vec3.normalize([x, y, z]); }, _getSideVec: function() { var f = this._getForwardVec(); var u = this._getUpVec(); return vec3.cross(u, f); }, _getUpVec: function() { var x = this._upVectorX; var y = this._upVectorY; var z = this._upVectorZ; return [x, y, z]; }, _move: function(v, s) { v[0] *= s; v[1] *= s; v[2] *= s; this._x += v[0]; this._y += v[1]; this._z += v[2]; this._centerX += v[0]; this._centerY += v[1]; this._centerZ += v[2]; }, /** [lang:ja] * Camera3DをローカルのZ軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves forward Camera3D. * @param {Number} speed [/lang] */ forward: function(s) { var v = this._getForwardVec(); this._move(v, s); }, /** [lang:ja] * Camera3DをローカルのX軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves side Camera3D. * @param {Number} speed [/lang] */ sidestep: function(s) { var v = this._getSideVec(); this._move(v, s); }, /** [lang:ja] * Camera3DをローカルのY軸方向に動かす. * @param {Number} speed [/lang] [lang:en] * Moves up Camera3D. * @param {Number} speed [/lang] */ altitude: function(s) { var v = this._getUpVec(); this._move(v, s); }, /** [lang:ja] * Camera3DのローカルのZ軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Camera3D in local Z acxis. * @param {Number} radius [/lang] */ rotateRoll: function(rad) { var u = this._getUpVec(); var f = this._getForwardVec(); var x = f[0]; var y = f[1]; var z = f[2]; var quat = new Quat(x, y, z, -rad); var vec = quat.multiplyVec3(u); this._upVectorX = vec[0]; this._upVectorY = vec[1]; this._upVectorZ = vec[2]; this._changedUpVector = true; }, /** [lang:ja] * Camera3DのローカルのX軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Camera3D in local X acxis. * @param {Number} radius [/lang] */ rotatePitch: function(rad) { var u = this._getUpVec(); var f = this._getForwardVec(); var s = this._getSideVec(); var sx = s[0]; var sy = s[1]; var sz = s[2]; var quat = new Quat(sx, sy, sz, -rad); var vec = quat.multiplyVec3(f); this._centerX = this._x + vec[0]; this._centerY = this._y + vec[1]; this._centerZ = this._z + vec[2]; vec = vec3.normalize(quat.multiplyVec3(u)); this._upVectorX = vec[0]; this._upVectorY = vec[1]; this._upVectorZ = vec[2]; this._changedCenter = true; this._changedUpVector = true; }, /** [lang:ja] * Camera3DのローカルのY軸を軸に回転させる. * @param {Number} radius [/lang] [lang:en] * Rotate Camera3D in local Y acxis. * @param {Number} radius [/lang] */ rotateYaw: function(rad) { var u = this._getUpVec(); var ux = u[0]; var uy = u[1]; var uz = u[2]; var f = this._getForwardVec() var quat = new Quat(ux, uy, uz, -rad); var vec = quat.multiplyVec3(f); this._centerX = this._x + vec[0]; this._centerY = this._y + vec[1]; this._centerZ = this._z + vec[2]; this._changedCenter = true; }, _updateMatrix: function() { this.mat; this.invMat; this.invMatY; mat4.lookAt( [this._x, this._y, this._z], [this._centerX, this._centerY, this._centerZ], [this._upVectorX, this._upVectorY, this._upVectorZ], this.mat); mat4.lookAt( [0, 0, 0], [-this._x + this._centerX, -this._y + this._centerY, -this._z + this._centerZ], [this._upVectorX, this._upVectorY, this._upVectorZ], this.invMat); mat4.inverse(this.invMat); mat4.lookAt( [0, 0, 0], [-this._x + this._centerX, 0, -this._z + this._centerZ], [this._upVectorX, this._upVectorY, this._upVectorZ], this.invMatY); mat4.inverse(this.invMatY); } }); /** [lang:ja] * カメラのx座標 * @type Number [/lang] [lang:en] * Camera x coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.x = 0; /** [lang:ja] * カメラのy座標 * @type Number [/lang] [lang:en] * Camera y coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.y = 0; /** [lang:ja] * カメラのz座標 * @type Number [/lang] [lang:en] * Camera z coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.z = 0; 'x y z'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Camera3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedPosition = true; } }); }); /** [lang:ja] * カメラの視点のx座標 * @type Number [/lang] [lang:en] * Camera perspective x coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.centerX = 0; /** [lang:ja] * カメラの視点のy座標 * @type Number [/lang] [lang:en] * Camera perspective y coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.centerY = 0; /** [lang:ja] * カメラの視点のz座標 * @type Number [/lang] [lang:en] * Camera perspective z coordinates * @type Number [/lang] */ enchant.gl.Camera3D.prototype.centerZ = 0; 'centerX centerY centerZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Camera3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedCenter = true; } }); }); /** [lang:ja] * カメラの上方向ベクトルのx成分 * @type Number [/lang] [lang:en] * Camera upper vector x component * @type Number [/lang] */ enchant.gl.Camera3D.prototype.upVectorX = 0; /** [lang:ja] * カメラの上方向ベクトルのy成分 * @type Number [/lang] [lang:en] * Camera upper vector y component * @type Number [/lang] */ enchant.gl.Camera3D.prototype.upVectorY = 1; /** [lang:ja] * カメラの上方向ベクトルのz成分 * @type Number [/lang] [lang:en] * Camera upper vector z component * @type Number [/lang] */ enchant.gl.Camera3D.prototype.upVectorZ = 0; 'upVectorX upVectorY upVectorZ'.split(' ').forEach(function(prop) { Object.defineProperty(enchant.gl.Camera3D.prototype, prop, { get: function() { return this['_' + prop]; }, set: function(n) { this['_' + prop] = n; this._changedUpVector = true; } }); }); /** [lang:ja] * @scope enchant.gl.Scene3D.prototype [/lang] [lang:en] * @scope enchant.gl.Scene3D.prototype [/lang] */ enchant.gl.Scene3D = enchant.Class.create(enchant.EventTarget, { /** [lang:ja] * 表示Sprite3Dツリーのルートになるクラス. * 現在, 複数定義することは出来ず, 最初に定義したScene3Dが返される. * * @example * var scene = new Scene3D(); * var sprite = new Sprite3D(); * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] [lang:en] * Class for displayed Sprite3D tree route. * Currently, multiple definitions are impossible, and the Scene3D defined first will be returned. * * @example * var scene = new Scene3D(); * var sprite = new Sprite3D(); * scene.addChild(sprite); * * @constructs * @extends enchant.EventTarget [/lang] */ initialize: function() { var game = enchant.Game.instance; if (game.currentScene3D) { return game.currentScene3D; } enchant.EventTarget.call(this); /** [lang:ja] * 子要素の配列. * このシーンに子として追加されているSprite3Dの一覧を取得できる. * 子を追加したり削除したりする場合には, この配列を直接操作せずに, * {@link enchant.gl.Scene3D#addChild}や{@link enchant.gl.Scene3D#removeChild}を利用する. * @type enchant.gl.Sprite3D[] [/lang] [lang:en] * Child element array. * A list of Sprite3D added as child classes in this scene can be acquired. * When adding or subtracting child classes, without directly operating this array, * {@link enchant.gl.Scene3D#addChild} or {@link enchant.gl.Scene3D#removeChild} is used. * @type enchant.gl.Sprite3D[] [/lang] */ this.childNodes = []; /** [lang:ja] * 照明の配列. * 現在, シーンに適用される光源は0番目のみ. * このシーンに追加されている光源の一覧を取得する. * 照明を追加したり削除したりする場合には, この配列を直接操作せずに, * {@link enchant.gl.Scene3D#addLight}や{@link enchant.gl.Scene3D#removeLight}を利用する. * @type enchant.gl.PointLight[] [/lang] [lang:en] * Lighting array. * At present, the only light source active in the scene is 0. * Acquires a list of light sources acquired in this scene. * When lighting is added or deleted, without directly operating this array, * {@link enchant.gl.Scene3D#addLight} or {@link enchant.gl.Scene3D#removeLight} is used. * @type enchant.gl.PointLight[] [/lang] */ this.lights = []; this.identityMat = mat4.identity(); this._backgroundColor = [0.0, 0.0, 0.0, 1.0]; var listener = function(e) { for (var i = 0, len = this.childNodes.length; i < len; i++) { var sprite = this.childNodes[i]; sprite.dispatchEvent(e); } }; this.addEventListener('added', listener); this.addEventListener('removed', listener); this.addEventListener('addedtoscene', listener); this.addEventListener('removedfromscene', listener); var that = this; var func = function() { that._draw(); }; game.addEventListener('enterframe', func); var uniforms = {}; uniforms['uUseCamera'] = 0.0; gl.activeTexture(gl.TEXTURE0); game.GL.defaultProgram.setUniforms(uniforms); if (game.currentScene3D == null) { game.currentScene3D = this; } this.setDirectionalLight(new DirectionalLight()); this.setCamera(new Camera3D()); }, /** [lang:ja] * Scene3Dの背景色 * @type Number[] [/lang] [lang:en] * Scene3D background color * @type Number[] [/lang] */ backgroundColor: { get: function() { return this._backgroundColor; }, set: function(arg) { var c = enchant.Game.instance.GL.parseColor(arg); this._backgroundColor = c; gl.clearColor(c[0], c[1], c[2], c[3]); } }, /** [lang:ja] * シーンにSprite3Dを追加する. * 引数に渡されたSprite3Dと, その子を全てシーンに追加する. * シーンに追加されると自動的にSprite3Dは画面上に表示される. * 一度追加したオブジェクトを削除するには{@link enchant.gl.Scene3D#removeChild}を利用する. * @param {enchant.gl.Sprite3D} sprite 追加するSprite3D * @see enchant.gl.Scene3D#removeChild * @see enchant.gl.Scene3D#childNodes [/lang] [lang:en] * Add Sprite3D to scene. * Adds Sprite3D delivered to argument and child classes to scene. * Sprite3D will automatically be displayed on screen if added to scene. * Use {@link enchant.gl.Scene3D#removeChild} to delete object added once. * @param {enchant.gl.Sprite3D} sprite Sprite3D to be added * @see enchant.gl.Scene3D#removeChild * @see enchant.gl.Scene3D#childNodes [/lang] */ addChild: function(sprite) { this.childNodes.push(sprite); sprite.parentNode = sprite.scene = this; sprite.dispatchEvent(new enchant.Event('added')); sprite.dispatchEvent(new enchant.Event('addedtoscene')); sprite.dispatchEvent(new enchant.Event('render')); }, /** [lang:ja] * シーンからSprite3Dを削除する. * シーンから指定されたSprite3Dを削除する. * 削除されたSprite3Dは画面上に表示されなくなる. * Sprite3Dを追加するには{@link enchant.gl.Scene3D#addChild}を利用する. * @param {enchant.gl.Sprite3D} sprite 削除するSprite3D * @see enchant.gl.Scene3D#addChild * @see enchant.gl.Scene3D#childNodes [/lang] [lang:en] * Delete Sprite3D from scene. * Deletes designated Sprite3D from scene. * The deleted Sprite3D will no longer be displayed on the screen. * Use {@link enchant.gl.Scene3D#addChild} to add Sprite3D. * @param {enchant.gl.Sprite3D} sprite Sprite3D to delete * @see enchant.gl.Scene3D#addChild * @see enchant.gl.Scene3D#childNodes [/lang] */ removeChild: function(sprite) { var i; if ((i = this.childNodes.indexOf(sprite)) != -1) { this.childNodes.splice(i, 1); } sprite.parentNode = sprite.scene = null; sprite.dispatchEvent(new enchant.Event('removed')); sprite.dispatchEvent(new enchant.Event('removedfromscene')); }, /** [lang:ja] * シーンのカメラ位置をセットする. * @param {enchant.gl.Camera3D} camera セットするカメラ * @see enchant.gl.Camera3D [/lang] [lang:en] * Sets scene's camera postion. * @param {enchant.gl.Camera3D} camera Camera to set * @see enchant.gl.Camera3D [/lang] */ setCamera: function(camera) { camera._changedPosition = true; camera._changedCenter = true; camera._changedUpVector = true; camera._changedProjection = true; this._camera = camera; enchant.Game.instance.GL.defaultProgram.setUniforms({ uUseCamera: 1.0 }); }, /** [lang:ja] * シーンに設定されているカメラを取得する. * @see enchant.gl.Camera3D * @return {enchant.gl.Camera} [/lang] [lang:en] * Gets camera source in scene. * @see enchant.gl.Camera3D * @return {enchant.gl.Camera} [/lang] */ getCamera: function() { return this._camera; }, /** [lang:ja] * シーンに平行光源を設定する. * @param {enchant.gl.DirectionalLight} light 設定する照明 * @see enchant.gl.DirectionalLight [/lang] [lang:en] * Sets directional light source in scene. * @param {enchant.gl.DirectionalLight} light Lighting to set * @see enchant.gl.DirectionalLight [/lang] */ setDirectionalLight: function(light) { this.directionalLight = light; this.useDirectionalLight = true; enchant.Game.instance.GL.defaultProgram.setUniforms({ uUseDirectionalLight: 1.0 }); }, /** [lang:ja] * シーンに設定されている平行光源を取得する. * @see enchant.gl.DirectionalLight * @return {enchant.gl.DirectionalLight} [/lang] [lang:en] * Gets directional light source in scene. * @see enchant.gl.DirectionalLight * @return {enchant.gl.DirectionalLight} [/lang] */ getDirectionalLight: function() { return this.directionalLight; }, /** [lang:ja] * シーンに照明を追加する. * 現在, シーンに追加しても適用されない. * @param {enchant.gl.PointLight} light 追加する照明 * @see enchant.gl.PointLight [/lang] [lang:en] * Add lighting to scene. * Currently, will not be used even if added to scene. * @param {enchant.gl.PointLight} light Lighting to add * @see enchant.gl.PointLight [/lang] */ addLight: function(light) { this.lights.push(light); this.usePointLight = true; }, /** [lang:ja] * シーンから照明を削除する * @param {enchant.gl.PointLight} light 削除する照明 * @see enchant.gl.PointLight. [/lang] [lang:en] * Delete lighting from scene * @param {enchant.gl.PointLight} light Lighting to delete * @see enchant.gl.PointLight. [/lang] */ removeLight: function(light) { var i; if ((i = this.lights.indexOf(light)) != -1) { this.lights.splice(i, 1); } }, _draw: function(detectTouch) { var game = enchant.Game.instance; var program = game.GL.defaultProgram; gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); var detect = (detectTouch == 'detect') ? 1.0 : 0.0; var uniforms = { uDetectTouch: detect }; if (this.useDirectionalLight) { if (this.directionalLight._changedDirection) { uniforms['uLightDirection'] = [ this.directionalLight.directionX, this.directionalLight.directionY, this.directionalLight.directionZ ]; this.directionalLight._changedDirection = false; } if (this.directionalLight._changedColor) { uniforms['uLightColor'] = this.directionalLight.color; this.directionalLight._changedColor = false; } } if (this._camera) { if (this._camera._changedPosition || this._camera._changedCenter || this._camera._changedUpVector || this._camera._changedProjection) { this._camera._updateMatrix(); uniforms['uCameraMat'] = this._camera.mat; uniforms['uProjMat'] = this._camera._projMat; uniforms['uLookVec'] = [ this._camera._centerX - this._camera._x, this._camera._centerY - this._camera._y, this._camera._centerZ - this._camera._z ]; } } program.setUniforms(uniforms); mat4.identity(this.identityMat); for (var i = 0, l = this.childNodes.length; i < l; i++) { this.childNodes[i]._draw(this, detectTouch, this.identityMat); } } }); enchant.gl.collision = {}; var point2point = function(p1, p2) { var vx = p1.x + p1.parent.x - p2.x - p2.parent.x; var vy = p1.y + p1.parent.y - p2.y - p2.parent.y; var vz = p1.z + p1.parent.z - p2.z - p2.parent.z; return (vx * vx + vy * vy + vz * vz); }; var point2BS = function(p, bs) { return (point2point(p, bs) - bs.radius * bs.radius); }; var point2AABB = function(p, aabb) { var ppx = p.x + p.parent.x; var ppy = p.y + p.parent.y; var ppz = p.z + p.parent.z; var px = aabb.parent.x + aabb.x + aabb.scale; var py = aabb.parent.y + aabb.y + aabb.scale; var pz = aabb.parent.z + aabb.z + aabb.scale; var nx = aabb.parent.x + (aabb.x - aabb.scale); var ny = aabb.parent.y + (aabb.y - aabb.scale); var nz = aabb.parent.z + (aabb.z - aabb.scale); var dist = 0; if (ppx < nx) { dist += (ppx - nx) * (ppx - nx); } else if (px < ppx) { dist += (ppx - px) * (ppx - px); } if (ppy < ny) { dist += (ppy - ny) * (ppy - ny); } else if (py < ppy) { dist += (ppy - py) * (ppy - py); } if (ppz < nz) { dist += (ppz - nz) * (ppz - nz); } else if (pz < ppz) { dist += (ppz - pz) * (ppz - pz); } return dist; }; var point2OBB = function(p, obb) { return 1; }; var BS2BS = function(bs1, bs2) { return (point2point(bs1, bs2) - (bs1.radius + bs2.radius) * (bs1.radius + bs2.radius)); }; var BS2AABB = function(bs, aabb) { return (point2AABB(bs, aabb) - bs.radius * bs.radius); }; var BS2OBB = function(bs, obb) { return 1; }; var AABB2AABB = function(aabb1, aabb2) { var px1 = aabb1.parent.x + aabb1.x + aabb1.scale; var py1 = aabb1.parent.y + aabb1.y + aabb1.scale; var pz1 = aabb1.parent.z + aabb1.z + aabb1.scale; var nx1 = aabb1.parent.x + (aabb1.x - aabb1.scale); var ny1 = aabb1.parent.y + (aabb1.y - aabb1.scale); var nz1 = aabb1.parent.z + (aabb1.z - aabb1.scale); var px2 = aabb2.parent.x + aabb2.x + aabb2.scale; var py2 = aabb2.parent.y + aabb2.y + aabb2.scale; var pz2 = aabb2.parent.z + aabb2.z + aabb2.scale; var nx2 = aabb2.parent.x + (aabb2.x - aabb2.scale); var ny2 = aabb2.parent.y + (aabb2.y - aabb2.scale); var nz2 = aabb2.parent.z + (aabb2.z - aabb2.scale); return ((nx2 <= px1) && (nx1 <= px2) && (ny2 <= py1) && (ny1 <= py2) && (nz2 <= pz1) && (nz1 <= pz2)) ? 0.0 : 1.0; }; var AABB2OBB = function(aabb, obb) { return 1; }; var OBB2OBB = function(obb1, obb2) { return 1; }; /** [lang:ja] * @scope enchant.gl.collision.Bounding.prototype [/lang] [lang:en] * @scope enchant.gl.collision.Bounding.prototype [/lang] */ enchant.gl.collision.Bounding = enchant.Class.create({ /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 点として定義されている. * enchant.gl.collision.Boundingを継承したクラスとして, * {@link enchant.gl.collision.BS}, {@link enchant.gl.collision.AABB}, * {@link enchant.gl.collision.OBB}, がある. * 現在, OBBはサポートされていない. * @constructs [/lang] [lang:en] * Class to set Sprite3D collision detection. * Defined as a point. * {@link enchant.gl.collision.BS}, {@link enchant.gl.collision.AABB}, * {@link enchant.gl.collision.OBB} exist as * inherited classes of enchant.gl.collision.Bounding * Currently, OBB is not supported. * @constructs [/lang] */ initialize: function() { this.type = 'point'; this.threshold = 0.0001; this.x = 0; this.y = 0; this.z = 0; this.parent = { x: 0, y: 0, z: 0 }; }, /** [lang:ja] * 点との距離を計算する. * @param {enchant.gl.collision.Bounding} bounding 衝突点オブジェクト * @return {Number} [/lang] [lang:en] * Calculates distance between points. * @param {enchant.gl.collision.Bounding} bounding Collision point object * @return {Number} [/lang] */ toBounding: function(another) { return point2point(this, another); }, /** [lang:ja] * 球との距離を計算する. * @param {enchant.gl.collision.BS} boudning 衝突球オブジェクト * @return {Number} [/lang] [lang:en] * Calculates distance between balls. * @param {enchant.gl.collision.BS} boudning Collision ball object * @return {Number} [/lang] */ toBS: function(another) { return point2BS(this, another); }, /** [lang:ja] * 回転しない立方体との距離を計算する. * 現在, 衝突していなければ1, 衝突していれば0が返される. * @param {enchant.gl.collision.AABB} bounding AABB * @return {Number} [/lang] [lang:en] * Calculates distance from non-rotating cube. * Currently, 0 will be returned with or without collision. * @param {enchant.gl.collision.AABB} bounding AABB * @return {Number} [/lang] */ toAABB: function(another) { return point2AABB(this, another); }, /** [lang:ja] * 回転する直方体との距離を計算する. * 現在, サポートされていない. * @param {enchant.gl.collision.OBB} bounding OBB * @return {Number} [/lang] [lang:en] * Calculates distance from rotating cuboid. * Not currently supported. * @param {enchant.gl.collision.OBB} bounding OBB * @return {Number} [/lang] */ toOBB: function(another) { return point2OBB(this, another); }, /** [lang:ja] * 他の衝突判定オブジェクトとの衝突判定. * 衝突判定オブジェクトか, x, y, zプロパティを持っているオブジェクトとの衝突を判定することができる. * @param {enchant.gl.collision.Bounding|enchant.gl.collision.BS|enchant.gl.collision.AABB|enchant.gl.collision.OBB} bounding 衝突判定オブジェクト * @return {Boolean} [/lang] [lang:en] * Collision detection with other collision detection object. * A collision detection object can detect collision with an object with x, y, z properties. * @param {enchant.gl.collision.Bounding|enchant.gl.collision.BS|enchant.gl.collision.AABB|enchant.gl.collision.OBB} bounding Collision detection object * @return {Boolean} [/lang] */ intersect: function(another) { switch (another.type) { case 'point': return (this.toBounding(another) < this.threshold); case 'BS': return (this.toBS(another) < this.threshold); case 'AABB': return (this.toAABB(another) < this.threshold); case 'OBB': return (this.toOBB(another) < this.threshold); default: return false; } } }); /** [lang:ja] * @scope enchant.gl.collision.BS.prototype [/lang] [lang:en] * @scope enchant.gl.collision.BS.prototype [/lang] */ enchant.gl.collision.BS = enchant.Class.create(enchant.gl.collision.Bounding, { /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 球として定義されている. * @constructs * @see enchant.gl.collision.Bounding [/lang] [lang:en] * Class that sets Sprite3D collision detection. * Defined as a ball. * @constructs * @see enchant.gl.collision.Bounding [/lang] */ initialize: function() { enchant.gl.collision.Bounding.call(this); this.type = 'BS'; this.radius = 0.5; }, toBounding: function(another) { return point2BS(another, this); }, toBS: function(another) { return BS2BS(this, another); }, toAABB: function(another) { return BS2AABB(this, another); }, toOBB: function(another) { return BS2OBB(this, another); } }); /** [lang:ja] * @scope enchant.gl.collision.AABB.prototype [/lang] [lang:en] * @scope enchant.gl.collision.AABB.prototype [/lang] */ enchant.gl.collision.AABB = enchant.Class.create(enchant.gl.collision.Bounding, { /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 回転しない立方体として定義されている. * @constructs * @see enchant.gl.collision.Bounding [/lang] [lang:en] * Class that sets Sprite3D collision detection. * Defined as non-rotating cube. * @constructs * @see enchant.gl.collision.Bounding [/lang] */ initialize: function() { enchant.gl.collision.Bounding.call(this); this.type = 'AABB'; this.scale = 0.5; }, toBounding: function(another) { return point2AABB(another, this); }, toBS: function(another) { return BS2AABB(another, this); }, toAABB: function(another) { return AABB2AABB(this, another); }, toOBB: function(another) { return AABB2OBB(this, another); } }); /** [lang:ja] * @scope enchant.gl.collision.OBB.prototype [/lang] [lang:en] * @scope enchant.gl.collision.OBB.prototype [/lang] */ enchant.gl.collision.OBB = enchant.Class.create(enchant.gl.collision.Bounding, { /** [lang:ja] * Sprite3Dの衝突判定を設定するクラス. * 回転するとして定義されている. * @constructs * @see enchant.gl.collision.Bounding [/lang] [lang:en] * Class that sets Sprite3D collision detection. * Defined as rotating. * @constructs * @see enchant.gl.collision.Bounding [/lang] */ initialize: function() { enchant.gl.collision.Bounding.call(this); this.type = 'OBB'; }, toBounding: function(another) { return point2OBB(another, this); }, toBS: function(another) { return BS2OBB(another, this); }, toAABB: function(another) { return AABB2OBB(another, this); }, toOBB: function(another) { return OBB2OBB(this, another); } }); var DEFAULT_VERTEX_SHADER_SOURCE = '\n\ attribute vec3 aVertexPosition;\n\ attribute vec4 aVertexColor;\n\ \n\ attribute vec3 aNormal;\n\ attribute vec2 aTextureCoord;\n\ \n\ uniform mat4 uModelMat;\n\ uniform mat4 uRotMat;\n\ uniform mat4 uCameraMat;\n\ uniform mat4 uProjMat;\n\ uniform mat3 uNormMat;\n\ uniform float uUseCamera;\n\ \n\ varying vec2 vTextureCoord;\n\ varying vec4 vColor;\n\ varying vec3 vNormal;\n\ \n\ void main() {\n\ vec4 p = uModelMat * vec4(aVertexPosition, 1.0);\n\ gl_Position = uProjMat * (uCameraMat * uUseCamera) * p + uProjMat * p * (1.0 - uUseCamera);\n\ vTextureCoord = aTextureCoord;\n\ vColor = aVertexColor;\n\ vNormal = uNormMat * aNormal;\n\ }'; var DEFAULT_FRAGMENT_SHADER_SOURCE = '\n\ precision highp float;\n\ \n\ uniform sampler2D uSampler;\n\ uniform float uUseDirectionalLight;\n\ uniform vec3 uLightColor;\n\ uniform vec3 uLookVec;\n\ uniform vec4 uAmbient;\n\ uniform vec4 uDiffuse;\n\ uniform vec4 uSpecular;\n\ uniform vec4 uEmission;\n\ uniform vec4 uDetectColor;\n\ uniform float uDetectTouch;\n\ uniform float uUseTexture;\n\ uniform float uShininess;\n\ uniform vec3 uLightDirection;\n\ \n\ varying vec2 vTextureCoord;\n\ varying vec4 vColor;\n\ varying vec3 vNormal;\n\ \n\ \n\ void main() {\n\ vec4 texColor = texture2D(uSampler, vTextureCoord);\n\ vec4 baseColor = vColor;\n\ baseColor *= texColor * uUseTexture + vec4(1.0, 1.0, 1.0, 1.0) * (1.0 - uUseTexture);\n\ float alpha = baseColor.a * uDetectColor.a * uDetectTouch + baseColor.a * (1.0 - uDetectTouch);\n\ if (alpha < 0.2) {\n\ discard;\n\ }\n\ else {\n\ vec4 phongColor = uAmbient;\n\ vec3 N = normalize(vNormal);\n\ vec3 L = normalize(uLightDirection);\n\ vec3 E = normalize(uLookVec);\n\ vec3 R = reflect(-L, N);\n\ float lamber = max(dot(N, L) , 0.0);\n\ phongColor += uDiffuse * lamber;\n\ float s = max(dot(R,-E), 0.0);\n\ vec4 specularColor= uSpecular * pow(s, uShininess) * sign(lamber);\n\ gl_FragColor = ((uEmission * baseColor + specularColor + vec4(baseColor.rgb * phongColor.rgb * uLightColor.rgb, baseColor.a)) \ * uUseDirectionalLight + baseColor * (1.0 - uUseDirectionalLight)) \ * (1.0 - uDetectTouch) + uDetectColor * uDetectTouch;\n\ }\n\ }'; })();
Quat.slerpメソッド修正 バグかと思われます。 よろしくお願いします。
dev/plugins/gl.enchant.js
Quat.slerpメソッド修正
<ide><path>ev/plugins/gl.enchant.js <ide> */ <ide> slerp: function(another, ratio) { <ide> var q = new Quat(0, 0, 0, 0); <del> quat4.slerp(this._quat, another._quat, ratio, q); <add> quat4.slerp(this._quat, another._quat, ratio, q._quat); <ide> return q; <ide> }, <ide> /**
Java
epl-1.0
4ee6f08fde998b19f4ebaea045fb7a5e0ce930df
0
riuvshin/che-plugins,Panthro/che-plugins,codenvy/che-plugins,ollie314/che-plugins,riuvshin/che-plugins,Panthro/che-plugins,vitaliy0922/cop_che-plugins,riuvshin/che-plugins,vitaliy0922/cop_che-plugins,codenvy/che-plugins,codenvy/che-plugins,riuvshin/che-plugins,vitaliy0922/cop_che-plugins,ollie314/che-plugins,vitaliy0922/cop_che-plugins,ollie314/che-plugins,ollie314/che-plugins,Panthro/che-plugins,Panthro/che-plugins
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.git.server; import org.eclipse.che.api.core.ConflictException; import org.eclipse.che.api.core.ForbiddenException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.UnauthorizedException; import org.eclipse.che.api.core.util.FileCleaner; import org.eclipse.che.api.core.util.LineConsumerFactory; import org.eclipse.che.api.project.server.FolderEntry; import org.eclipse.che.api.project.server.ProjectImporter; import org.eclipse.che.commons.lang.IoUtil; import org.eclipse.che.dto.server.DtoFactory; import org.eclipse.che.vfs.impl.fs.VirtualFileImpl; import org.eclipse.che.ide.ext.git.shared.Branch; import org.eclipse.che.ide.ext.git.shared.BranchCheckoutRequest; import org.eclipse.che.ide.ext.git.shared.BranchListRequest; import org.eclipse.che.ide.ext.git.shared.CloneRequest; import org.eclipse.che.ide.ext.git.shared.FetchRequest; import org.eclipse.che.ide.ext.git.shared.InitRequest; import org.eclipse.che.ide.ext.git.shared.RemoteAddRequest; import org.eclipse.che.vfs.impl.fs.LocalPathResolver; import com.google.inject.Inject; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Collections; import java.util.List; import java.util.Map; /** * @author Vladyslav Zhukovskii */ @Singleton public class GitProjectImporter implements ProjectImporter { private final GitConnectionFactory gitConnectionFactory; private final LocalPathResolver localPathResolver; private static final Logger LOG = LoggerFactory.getLogger(GitProjectImporter.class); @Inject public GitProjectImporter(GitConnectionFactory gitConnectionFactory, LocalPathResolver localPathResolver) { this.gitConnectionFactory = gitConnectionFactory; this.localPathResolver = localPathResolver; } @Override public String getId() { return "git"; } @Override public boolean isInternal() { return false; } @Override public String getDescription() { return "Import project from hosted GIT repository URL."; } /** {@inheritDoc} */ @Override public ImporterCategory getCategory() { return ImporterCategory.SOURCE_CONTROL; } @Override public void importSources(FolderEntry baseFolder, String location, Map<String, String> parameters) throws ForbiddenException, ConflictException, UnauthorizedException, IOException, ServerException { importSources(baseFolder, location, parameters, LineConsumerFactory.NULL); } @Override public void importSources(FolderEntry baseFolder, String location, Map<String, String> parameters, LineConsumerFactory consumerFactory) throws ForbiddenException, ConflictException, UnauthorizedException, IOException, ServerException { GitConnection git = null; try { // For factory: checkout particular commit after clone String commitId = null; // For factory: github pull request feature String remoteOriginFetch = null; String branch = null; // For factory or probably for our projects templates: // If git repository contains more than one project need clone all repository but after cloning keep just // sub-project that is specified in parameter "keepDirectory". String keepDirectory = null; // For factory and for our projects templates: // Keep all info related to the vcs. In case of Git: ".git" directory and ".gitignore" file. // Delete vcs info if false. String branchMerge = null; boolean keepVcs = true; if (parameters != null) { commitId = parameters.get("commitId"); branch = parameters.get("branch"); remoteOriginFetch = parameters.get("remoteOriginFetch"); keepDirectory = parameters.get("keepDirectory"); if (parameters.containsKey("keepVcs")) { keepVcs = Boolean.parseBoolean(parameters.get("keepVcs")); } branchMerge = parameters.get("branchMerge"); } // Get path to local file. Git works with local filesystem only. final String localPath = localPathResolver.resolve((VirtualFileImpl)baseFolder.getVirtualFile()); final DtoFactory dtoFactory = DtoFactory.getInstance(); if (keepDirectory != null) { final File temp = Files.createTempDirectory(null).toFile(); try { git = gitConnectionFactory.getConnection(temp, consumerFactory); sparsecheckout(git, location, branch == null ? "master" : branch, keepDirectory, dtoFactory); // Copy content of directory to the project folder. final File projectDir = new File(localPath); IoUtil.copy(temp, projectDir, IoUtil.ANY_FILTER); } finally { FileCleaner.addFile(temp); } } else { git = gitConnectionFactory.getConnection(localPath, consumerFactory); if (baseFolder.getChildren().size() == 0) { cloneRepository(git, "origin", location, dtoFactory); if (commitId != null) { checkoutCommit(git, commitId, dtoFactory); } else if (remoteOriginFetch != null) { git.getConfig().add("remote.origin.fetch", remoteOriginFetch); fetch(git, "origin", dtoFactory); if (branch != null) { checkoutBranch(git, branch, dtoFactory); } } else if (branch != null) { checkoutBranch(git, branch, dtoFactory); } } else { initRepository(git, dtoFactory); addRemote(git, "origin", location, dtoFactory); if (commitId != null) { fetchBranch(git, "origin", branch == null ? "*" : branch, dtoFactory); checkoutCommit(git, commitId, dtoFactory); } else if (remoteOriginFetch != null) { git.getConfig().add("remote.origin.fetch", remoteOriginFetch); fetch(git, "origin", dtoFactory); if (branch != null) { checkoutBranch(git, branch, dtoFactory); } } else { fetchBranch(git, "origin", branch == null ? "*" : branch, dtoFactory); List<Branch> branchList = git.branchList(dtoFactory.createDto(BranchListRequest.class).withListMode("r")); if (!branchList.isEmpty()) { checkoutBranch(git, branch == null ? "master" : branch, dtoFactory); } } } if (branchMerge != null) { git.getConfig().set("branch." + (branch == null ? "master" : branch) + ".merge", branchMerge); } if (!keepVcs) { cleanGit(git.getWorkingDir()); } } } catch (UnauthorizedException e) { throw new UnauthorizedException( "You are not authorized to perform the remote import. Codenvy may need accurate keys to the " + "external system. You can create a new SSH key pair in Window->Preferences->Keys And " + "Certificates->SSH Keystore."); } catch (URISyntaxException e) { throw new ServerException( "Your project cannot be imported. The issue is either from git configuration, a malformed URL, " + "or file system corruption. Please contact support for assistance.", e); } finally { if (git != null) { git.close(); } } } private void cloneRepository(GitConnection git, String remoteName, String url, DtoFactory dtoFactory) throws ServerException, UnauthorizedException, URISyntaxException { final CloneRequest request = dtoFactory.createDto(CloneRequest.class).withRemoteName(remoteName).withRemoteUri(url); git.clone(request); } private void initRepository(GitConnection git, DtoFactory dtoFactory) throws GitException { final InitRequest request = dtoFactory.createDto(InitRequest.class).withInitCommit(false).withBare(false); git.init(request); } private void addRemote(GitConnection git, String name, String url, DtoFactory dtoFactory) throws GitException { final RemoteAddRequest request = dtoFactory.createDto(RemoteAddRequest.class).withName(name).withUrl(url); git.remoteAdd(request); } private void fetch(GitConnection git, String remote, DtoFactory dtoFactory) throws UnauthorizedException, GitException { final FetchRequest request = dtoFactory.createDto(FetchRequest.class).withRemote(remote); git.fetch(request); } private void fetchBranch(GitConnection gitConnection, String remote, String branch, DtoFactory dtoFactory) throws UnauthorizedException, GitException { final List<String> refSpecs = Collections.singletonList(String.format("refs/heads/%1$s:refs/remotes/origin/%1$s", branch)); try { fetchRefSpecs(gitConnection, remote, refSpecs, dtoFactory); } catch (GitException e) { LOG.warn("Git exception on branch fetch", e); throw new GitException( String.format("Unable to fetch remote branch %s. Make sure it exists and can be accessed.", branch), e); } } private void fetchRefSpecs(GitConnection git, String remote, List<String> refSpecs, DtoFactory dtoFactory) throws UnauthorizedException, GitException { final FetchRequest request = dtoFactory.createDto(FetchRequest.class).withRemote(remote).withRefSpec(refSpecs); git.fetch(request); } private void checkoutCommit(GitConnection git, String commit, DtoFactory dtoFactory) throws GitException { final BranchCheckoutRequest request = dtoFactory.createDto(BranchCheckoutRequest.class).withName("temp").withCreateNew(true) .withStartPoint(commit); try { git.branchCheckout(request); } catch (GitException e) { LOG.warn("Git exception on commit checkout", e); throw new GitException( String.format("Unable to checkout commit %s. Make sure it exists and can be accessed.", commit), e); } } private void checkoutBranch(GitConnection git, String branch, DtoFactory dtoFactory) throws GitException { final BranchCheckoutRequest request = dtoFactory.createDto(BranchCheckoutRequest.class).withName(branch); try { git.branchCheckout(request); } catch (GitException e) { LOG.warn("Git exception on branch checkout", e); throw new GitException( String.format("Unable to checkout remote branch %s. Make sure it exists and can be accessed.", branch), e); } } private void sparsecheckout(GitConnection git, String url, String branch, String directory, DtoFactory dtoFactory) throws GitException, UnauthorizedException { /* Does following sequence of Git commands: $ git init $ git remote add origin <URL> $ git config core.sparsecheckout true $ echo keepDirectory >> .git/info/sparse-checkout $ git pull origin master */ initRepository(git, dtoFactory); addRemote(git, "origin", url, dtoFactory); git.getConfig().add("core.sparsecheckout", "true"); final File workingDir = git.getWorkingDir(); final File sparseCheckout = new File(workingDir, ".git" + File.separator + "info" + File.separator + "sparse-checkout"); try { try (BufferedWriter writer = Files.newBufferedWriter(sparseCheckout.toPath(), Charset.forName("UTF-8"))) { writer.write(directory); } } catch (IOException e) { throw new GitException(e); } fetchBranch(git, "origin", branch, dtoFactory); checkoutBranch(git, branch, dtoFactory); } private void cleanGit(File project) { IoUtil.deleteRecursive(new File(project, ".git")); new File(project, ".gitignore").delete(); } }
plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/server/GitProjectImporter.java
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.git.server; import org.eclipse.che.api.core.ConflictException; import org.eclipse.che.api.core.ForbiddenException; import org.eclipse.che.api.core.ServerException; import org.eclipse.che.api.core.UnauthorizedException; import org.eclipse.che.api.core.util.FileCleaner; import org.eclipse.che.api.core.util.LineConsumerFactory; import org.eclipse.che.api.project.server.FolderEntry; import org.eclipse.che.api.project.server.ProjectImporter; import org.eclipse.che.commons.lang.IoUtil; import org.eclipse.che.dto.server.DtoFactory; import org.eclipse.che.vfs.impl.fs.VirtualFileImpl; import org.eclipse.che.ide.ext.git.shared.Branch; import org.eclipse.che.ide.ext.git.shared.BranchCheckoutRequest; import org.eclipse.che.ide.ext.git.shared.BranchListRequest; import org.eclipse.che.ide.ext.git.shared.CloneRequest; import org.eclipse.che.ide.ext.git.shared.FetchRequest; import org.eclipse.che.ide.ext.git.shared.InitRequest; import org.eclipse.che.ide.ext.git.shared.RemoteAddRequest; import org.eclipse.che.vfs.impl.fs.LocalPathResolver; import com.google.inject.Inject; import com.google.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedWriter; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.Collections; import java.util.List; import java.util.Map; /** * @author Vladyslav Zhukovskii */ @Singleton public class GitProjectImporter implements ProjectImporter { private final GitConnectionFactory gitConnectionFactory; private final LocalPathResolver localPathResolver; private static final Logger LOG = LoggerFactory.getLogger(GitProjectImporter.class); @Inject public GitProjectImporter(GitConnectionFactory gitConnectionFactory, LocalPathResolver localPathResolver) { this.gitConnectionFactory = gitConnectionFactory; this.localPathResolver = localPathResolver; } @Override public String getId() { return "git"; } @Override public boolean isInternal() { return false; } @Override public String getDescription() { return "Import project from hosted GIT repository URL."; } /** {@inheritDoc} */ @Override public ImporterCategory getCategory() { return ImporterCategory.SOURCE_CONTROL; } @Override public void importSources(FolderEntry baseFolder, String location, Map<String, String> parameters) throws ForbiddenException, ConflictException, UnauthorizedException, IOException, ServerException { importSources(baseFolder, location, parameters, LineConsumerFactory.NULL); } @Override public void importSources(FolderEntry baseFolder, String location, Map<String, String> parameters, LineConsumerFactory consumerFactory) throws ForbiddenException, ConflictException, UnauthorizedException, IOException, ServerException { GitConnection git = null; try { // For factory: checkout particular commit after clone String commitId = null; // For factory: github pull request feature String remoteOriginFetch = null; String branch = null; // For factory or probably for our projects templates: // If git repository contains more than one project need clone all repository but after cloning keep just // sub-project that is specified in parameter "keepDirectory". String keepDirectory = null; // For factory and for our projects templates: // Keep all info related to the vcs. In case of Git: ".git" directory and ".gitignore" file. // Delete vcs info if false. String branchMerge = null; boolean keepVcs = true; if (parameters != null) { commitId = parameters.get("commitId"); branch = parameters.get("branch"); remoteOriginFetch = parameters.get("remoteOriginFetch"); keepDirectory = parameters.get("keepDirectory"); if (parameters.containsKey("keepVcs")) { keepVcs = Boolean.parseBoolean(parameters.get("keepVcs")); } branchMerge = parameters.get("branchMerge"); } // Get path to local file. Git works with local filesystem only. final String localPath = localPathResolver.resolve((VirtualFileImpl)baseFolder.getVirtualFile()); final DtoFactory dtoFactory = DtoFactory.getInstance(); if (keepDirectory != null) { final File temp = Files.createTempDirectory(null).toFile(); try { git = gitConnectionFactory.getConnection(temp, consumerFactory); sparsecheckout(git, location, branch == null ? "master" : branch, keepDirectory, dtoFactory); // Copy content of directory to the project folder. final File projectDir = new File(localPath); IoUtil.copy(new File(temp, keepDirectory), projectDir, IoUtil.ANY_FILTER); } finally { FileCleaner.addFile(temp); } } else { git = gitConnectionFactory.getConnection(localPath, consumerFactory); if (baseFolder.getChildren().size() == 0) { cloneRepository(git, "origin", location, dtoFactory); if (commitId != null) { checkoutCommit(git, commitId, dtoFactory); } else if (remoteOriginFetch != null) { git.getConfig().add("remote.origin.fetch", remoteOriginFetch); fetch(git, "origin", dtoFactory); if (branch != null) { checkoutBranch(git, branch, dtoFactory); } } else if (branch != null) { checkoutBranch(git, branch, dtoFactory); } } else { initRepository(git, dtoFactory); addRemote(git, "origin", location, dtoFactory); if (commitId != null) { fetchBranch(git, "origin", branch == null ? "*" : branch, dtoFactory); checkoutCommit(git, commitId, dtoFactory); } else if (remoteOriginFetch != null) { git.getConfig().add("remote.origin.fetch", remoteOriginFetch); fetch(git, "origin", dtoFactory); if (branch != null) { checkoutBranch(git, branch, dtoFactory); } } else { fetchBranch(git, "origin", branch == null ? "*" : branch, dtoFactory); List<Branch> branchList = git.branchList(dtoFactory.createDto(BranchListRequest.class).withListMode("r")); if (!branchList.isEmpty()) { checkoutBranch(git, branch == null ? "master" : branch, dtoFactory); } } } if (branchMerge != null) { git.getConfig().set("branch." + (branch == null ? "master" : branch) + ".merge", branchMerge); } if (!keepVcs) { cleanGit(git.getWorkingDir()); } } } catch (UnauthorizedException e) { throw new UnauthorizedException( "You are not authorized to perform the remote import. Codenvy may need accurate keys to the " + "external system. You can create a new SSH key pair in Window->Preferences->Keys And " + "Certificates->SSH Keystore."); } catch (URISyntaxException e) { throw new ServerException( "Your project cannot be imported. The issue is either from git configuration, a malformed URL, " + "or file system corruption. Please contact support for assistance.", e); } finally { if (git != null) { git.close(); } } } private void cloneRepository(GitConnection git, String remoteName, String url, DtoFactory dtoFactory) throws ServerException, UnauthorizedException, URISyntaxException { final CloneRequest request = dtoFactory.createDto(CloneRequest.class).withRemoteName(remoteName).withRemoteUri(url); git.clone(request); } private void initRepository(GitConnection git, DtoFactory dtoFactory) throws GitException { final InitRequest request = dtoFactory.createDto(InitRequest.class).withInitCommit(false).withBare(false); git.init(request); } private void addRemote(GitConnection git, String name, String url, DtoFactory dtoFactory) throws GitException { final RemoteAddRequest request = dtoFactory.createDto(RemoteAddRequest.class).withName(name).withUrl(url); git.remoteAdd(request); } private void fetch(GitConnection git, String remote, DtoFactory dtoFactory) throws UnauthorizedException, GitException { final FetchRequest request = dtoFactory.createDto(FetchRequest.class).withRemote(remote); git.fetch(request); } private void fetchBranch(GitConnection gitConnection, String remote, String branch, DtoFactory dtoFactory) throws UnauthorizedException, GitException { final List<String> refSpecs = Collections.singletonList(String.format("refs/heads/%1$s:refs/remotes/origin/%1$s", branch)); try { fetchRefSpecs(gitConnection, remote, refSpecs, dtoFactory); } catch (GitException e) { LOG.warn("Git exception on branch fetch", e); throw new GitException( String.format("Unable to fetch remote branch %s. Make sure it exists and can be accessed.", branch), e); } } private void fetchRefSpecs(GitConnection git, String remote, List<String> refSpecs, DtoFactory dtoFactory) throws UnauthorizedException, GitException { final FetchRequest request = dtoFactory.createDto(FetchRequest.class).withRemote(remote).withRefSpec(refSpecs); git.fetch(request); } private void checkoutCommit(GitConnection git, String commit, DtoFactory dtoFactory) throws GitException { final BranchCheckoutRequest request = dtoFactory.createDto(BranchCheckoutRequest.class).withName("temp").withCreateNew(true) .withStartPoint(commit); try { git.branchCheckout(request); } catch (GitException e) { LOG.warn("Git exception on commit checkout", e); throw new GitException( String.format("Unable to checkout commit %s. Make sure it exists and can be accessed.", commit), e); } } private void checkoutBranch(GitConnection git, String branch, DtoFactory dtoFactory) throws GitException { final BranchCheckoutRequest request = dtoFactory.createDto(BranchCheckoutRequest.class).withName(branch); try { git.branchCheckout(request); } catch (GitException e) { LOG.warn("Git exception on branch checkout", e); throw new GitException( String.format("Unable to checkout remote branch %s. Make sure it exists and can be accessed.", branch), e); } } private void sparsecheckout(GitConnection git, String url, String branch, String directory, DtoFactory dtoFactory) throws GitException, UnauthorizedException { /* Does following sequence of Git commands: $ git init $ git remote add origin <URL> $ git config core.sparsecheckout true $ echo keepDirectory >> .git/info/sparse-checkout $ git pull origin master */ initRepository(git, dtoFactory); addRemote(git, "origin", url, dtoFactory); git.getConfig().add("core.sparsecheckout", "true"); final File workingDir = git.getWorkingDir(); final File sparseCheckout = new File(workingDir, ".git" + File.separator + "info" + File.separator + "sparse-checkout"); try { try (BufferedWriter writer = Files.newBufferedWriter(sparseCheckout.toPath(), Charset.forName("UTF-8"))) { writer.write(directory); } } catch (IOException e) { throw new GitException(e); } fetchBranch(git, "origin", branch, dtoFactory); checkoutBranch(git, branch, dtoFactory); } private void cleanGit(File project) { IoUtil.deleteRecursive(new File(project, ".git")); new File(project, ".gitignore").delete(); } }
IDEX-1977; keep .git folder when keepDirectory is used;
plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/server/GitProjectImporter.java
IDEX-1977; keep .git folder when keepDirectory is used;
<ide><path>lugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/server/GitProjectImporter.java <ide> sparsecheckout(git, location, branch == null ? "master" : branch, keepDirectory, dtoFactory); <ide> // Copy content of directory to the project folder. <ide> final File projectDir = new File(localPath); <del> IoUtil.copy(new File(temp, keepDirectory), projectDir, IoUtil.ANY_FILTER); <add> IoUtil.copy(temp, projectDir, IoUtil.ANY_FILTER); <ide> } finally { <ide> FileCleaner.addFile(temp); <ide> }
Java
apache-2.0
e31fc5df5872d2d8d84fc578e42069c52e212067
0
alphafoobar/intellij-community,kool79/intellij-community,ryano144/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,ol-loginov/intellij-community,caot/intellij-community,tmpgit/intellij-community,da1z/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,samthor/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,robovm/robovm-studio,semonte/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,diorcety/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,FHannes/intellij-community,apixandru/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,vladmm/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,semonte/intellij-community,clumsy/intellij-community,semonte/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,xfournet/intellij-community,retomerz/intellij-community,slisson/intellij-community,izonder/intellij-community,ibinti/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,allotria/intellij-community,da1z/intellij-community,retomerz/intellij-community,retomerz/intellij-community,dslomov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,jagguli/intellij-community,fnouama/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,kool79/intellij-community,wreckJ/intellij-community,slisson/intellij-community,orekyuu/intellij-community,amith01994/intellij-community,petteyg/intellij-community,kool79/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,asedunov/intellij-community,jagguli/intellij-community,caot/intellij-community,slisson/intellij-community,caot/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,diorcety/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,tmpgit/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,xfournet/intellij-community,clumsy/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,supersven/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,asedunov/intellij-community,diorcety/intellij-community,holmes/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,semonte/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,ibinti/intellij-community,fnouama/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,allotria/intellij-community,FHannes/intellij-community,asedunov/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,supersven/intellij-community,semonte/intellij-community,petteyg/intellij-community,adedayo/intellij-community,caot/intellij-community,adedayo/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,caot/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,allotria/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,allotria/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,signed/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,clumsy/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,slisson/intellij-community,signed/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,samthor/intellij-community,youdonghai/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,asedunov/intellij-community,amith01994/intellij-community,samthor/intellij-community,semonte/intellij-community,izonder/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,izonder/intellij-community,caot/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,kdwink/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,vladmm/intellij-community,samthor/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,amith01994/intellij-community,blademainer/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,slisson/intellij-community,dslomov/intellij-community,supersven/intellij-community,signed/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,ryano144/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,kdwink/intellij-community,holmes/intellij-community,akosyakov/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,adedayo/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,robovm/robovm-studio,izonder/intellij-community,blademainer/intellij-community,diorcety/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,clumsy/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,tmpgit/intellij-community,da1z/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,izonder/intellij-community,kool79/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,vladmm/intellij-community,allotria/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,signed/intellij-community,samthor/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,signed/intellij-community,samthor/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,supersven/intellij-community,apixandru/intellij-community,ryano144/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,apixandru/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,hurricup/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,ibinti/intellij-community,muntasirsyed/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,signed/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ryano144/intellij-community,kdwink/intellij-community,petteyg/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,amith01994/intellij-community,dslomov/intellij-community,diorcety/intellij-community,vladmm/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,asedunov/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,izonder/intellij-community,xfournet/intellij-community,kool79/intellij-community,apixandru/intellij-community,kool79/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,caot/intellij-community,holmes/intellij-community,FHannes/intellij-community,amith01994/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,allotria/intellij-community,slisson/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,dslomov/intellij-community,retomerz/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,allotria/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,FHannes/intellij-community,robovm/robovm-studio,holmes/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ryano144/intellij-community,signed/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,clumsy/intellij-community,caot/intellij-community,xfournet/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,signed/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,fitermay/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,apixandru/intellij-community,xfournet/intellij-community,slisson/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,fnouama/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,da1z/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,caot/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,signed/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ryano144/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,caot/intellij-community,Lekanich/intellij-community,robovm/robovm-studio,blademainer/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,supersven/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,amith01994/intellij-community,petteyg/intellij-community,hurricup/intellij-community,samthor/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,vladmm/intellij-community,ryano144/intellij-community,kool79/intellij-community,fitermay/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,semonte/intellij-community,slisson/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,holmes/intellij-community,da1z/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,nicolargo/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,kool79/intellij-community,izonder/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,blademainer/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,supersven/intellij-community
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Created by IntelliJ IDEA. * User: mike * Date: Sep 27, 2002 * Time: 3:10:17 PM * To change template for new class use * Code Style | Class Templates options (Tools | IDE Options). */ package com.intellij.codeInsight.highlighting; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.hint.EditorFragmentComponent; import com.intellij.concurrency.Job; import com.intellij.concurrency.JobLauncher; import com.intellij.injected.editor.EditorWindow; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.ColorUtil; import com.intellij.util.Alarm; import com.intellij.util.Processor; import com.intellij.util.containers.WeakHashMap; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; public class BraceHighlightingHandler { private static final Key<List<RangeHighlighter>> BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY = Key.create("BraceHighlighter.BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY"); private static final Key<RangeHighlighter> LINE_MARKER_IN_EDITOR_KEY = Key.create("BraceHighlighter.LINE_MARKER_IN_EDITOR_KEY"); /** * Holds weak references to the editors that are being processed at non-EDT. * <p/> * Is intended to be used to avoid submitting unnecessary new processing request from EDT, i.e. it's assumed that the collection * is accessed from the single thread (EDT). */ private static final Set<Editor> PROCESSED_EDITORS = Collections.newSetFromMap(new WeakHashMap<Editor, Boolean>()); @NotNull private final Project myProject; @NotNull private final Editor myEditor; private final Alarm myAlarm; private final DocumentEx myDocument; private final PsiFile myPsiFile; private final CodeInsightSettings myCodeInsightSettings; private BraceHighlightingHandler(@NotNull Project project, @NotNull Editor editor, @NotNull Alarm alarm, PsiFile psiFile) { myProject = project; myEditor = editor; myAlarm = alarm; myDocument = (DocumentEx)myEditor.getDocument(); myPsiFile = psiFile; myCodeInsightSettings = CodeInsightSettings.getInstance(); // myFileType = myPsiFile == null ? null : myPsiFile.getFileType(); } static void lookForInjectedAndMatchBracesInOtherThread(@NotNull final Editor editor, @NotNull final Alarm alarm, @NotNull final Processor<BraceHighlightingHandler> processor) { ApplicationManagerEx.getApplicationEx().assertIsDispatchThread(); if (!PROCESSED_EDITORS.add(editor)) { // Skip processing if that is not really necessary. // Assuming to be in EDT here. return; } final Project project = editor.getProject(); if (project == null) return; final int offset = editor.getCaretModel().getOffset(); final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); JobLauncher.getInstance().submitToJobThread(Job.DEFAULT_PRIORITY, new Runnable() { @Override public void run() { if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(new Runnable() { @Override public void run() { final PsiFile injected; try { if (isReallyDisposed(editor, project)) return; injected = psiFile == null || psiFile instanceof PsiCompiledElement ? null : getInjectedFileIfAny(editor, project, offset, psiFile, alarm); } catch (RuntimeException e) { // Reset processing flag in case of unexpected exception. ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { @Override public void run() { PROCESSED_EDITORS.remove(editor); } }); throw e; } ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { @Override public void run() { try { if (!isReallyDisposed(editor, project)) { Editor newEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injected); BraceHighlightingHandler handler = new BraceHighlightingHandler(project, newEditor, alarm, injected); processor.process(handler); } } finally { PROCESSED_EDITORS.remove(editor); } } }, ModalityState.stateForComponent(editor.getComponent())); } })) { // write action is queued in AWT. restart after it's finished ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { PROCESSED_EDITORS.remove(editor); lookForInjectedAndMatchBracesInOtherThread(editor, alarm, processor); } }, ModalityState.stateForComponent(editor.getComponent())); } } }); } private static boolean isReallyDisposed(@NotNull Editor editor, @NotNull Project project) { Project editorProject = editor.getProject(); return editorProject == null || editorProject.isDisposed() || project.isDisposed() || !editor.getComponent().isShowing() || editor.isViewer(); } @NotNull private static PsiFile getInjectedFileIfAny(@NotNull final Editor editor, @NotNull final Project project, int offset, @NotNull PsiFile psiFile, @NotNull final Alarm alarm) { Document document = editor.getDocument(); // when document is committed, try to highlight braces in injected lang - it's fast if (PsiDocumentManager.getInstance(project).isCommitted(document)) { final PsiElement injectedElement = InjectedLanguageUtil.findInjectedElementNoCommit(psiFile, offset); if (injectedElement != null /*&& !(injectedElement instanceof PsiWhiteSpace)*/) { final PsiFile injected = injectedElement.getContainingFile(); if (injected != null) { return injected; } } } else { PsiDocumentManager.getInstance(project).performForCommittedDocument(document, new Runnable() { @Override public void run() { if (!project.isDisposed() && !editor.isDisposed()) { BraceHighlighter.updateBraces(editor, alarm); } } }); } return psiFile; } void updateBraces() { ApplicationManager.getApplication().assertIsDispatchThread(); if (myPsiFile == null || !myPsiFile.isValid()) return; clearBraceHighlighters(); if (!myCodeInsightSettings.HIGHLIGHT_BRACES) return; if (myEditor.getSelectionModel().hasSelection()) return; if (myEditor.getSoftWrapModel().isInsideOrBeforeSoftWrap(myEditor.getCaretModel().getVisualPosition())) return; int offset = myEditor.getCaretModel().getOffset(); final CharSequence chars = myEditor.getDocument().getCharsSequence(); //if (myEditor.offsetToLogicalPosition(offset).column != myEditor.getCaretModel().getLogicalPosition().column) { // // we are in virtual space // final int caretLineNumber = myEditor.getCaretModel().getLogicalPosition().line; // if (caretLineNumber >= myDocument.getLineCount()) return; // offset = myDocument.getLineEndOffset(caretLineNumber) + myDocument.getLineSeparatorLength(caretLineNumber); //} final int originalOffset = offset; HighlighterIterator iterator = getEditorHighlighter().createIterator(offset); FileType fileType = PsiUtilBase.getPsiFileAtOffset(myPsiFile, offset).getFileType(); if (iterator.atEnd()) { offset--; } else if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { offset--; } else if (!BraceMatchingUtil.isLBraceToken(iterator, chars, fileType)) { offset--; if (offset >= 0) { final HighlighterIterator i = getEditorHighlighter().createIterator(offset); if (!BraceMatchingUtil.isRBraceToken(i, chars, getFileTypeByIterator(i))) offset++; } } if (offset < 0) { removeLineMarkers(); return; } iterator = getEditorHighlighter().createIterator(offset); fileType = getFileTypeByIterator(iterator); myAlarm.cancelAllRequests(); if (BraceMatchingUtil.isLBraceToken(iterator, chars, fileType) || BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { doHighlight(offset, originalOffset, fileType); } else if (offset > 0 && offset < chars.length()) { // There is a possible case that there are paired braces nearby the caret position and the document contains only white // space symbols between them. We want to highlight such braces as well. // Example: // public void test() { <caret> // } char c = chars.charAt(offset); boolean searchForward = c != '\n'; // Try to find matched brace backwards. if (offset >= originalOffset && (c == ' ' || c == '\t' || c == '\n')) { int backwardNonWsOffset = CharArrayUtil.shiftBackward(chars, offset - 1, "\t "); if (backwardNonWsOffset >= 0) { iterator = getEditorHighlighter().createIterator(backwardNonWsOffset); FileType newFileType = getFileTypeByIterator(iterator); if (BraceMatchingUtil.isLBraceToken(iterator, chars, newFileType) || BraceMatchingUtil.isRBraceToken(iterator, chars, newFileType)) { offset = backwardNonWsOffset; searchForward = false; doHighlight(backwardNonWsOffset, originalOffset, newFileType); } } } // Try to find matched brace forward. if (searchForward) { int forwardOffset = CharArrayUtil.shiftForward(chars, offset, "\t "); if (forwardOffset > offset || c == ' ' || c == '\t') { iterator = getEditorHighlighter().createIterator(forwardOffset); FileType newFileType = getFileTypeByIterator(iterator); if (BraceMatchingUtil.isLBraceToken(iterator, chars, newFileType) || BraceMatchingUtil.isRBraceToken(iterator, chars, newFileType)) { offset = forwardOffset; doHighlight(forwardOffset, originalOffset, newFileType); } } } } //highlight scope if (!myCodeInsightSettings.HIGHLIGHT_SCOPE) { removeLineMarkers(); return; } final int _offset = offset; final FileType _fileType = fileType; myAlarm.addRequest(new Runnable() { @Override public void run() { if (!myProject.isDisposed() && !myEditor.isDisposed()) { highlightScope(_offset, _fileType); } } }, 300); } @NotNull private FileType getFileTypeByIterator(@NotNull HighlighterIterator iterator) { return PsiUtilBase.getPsiFileAtOffset(myPsiFile, iterator.getStart()).getFileType(); } @NotNull private FileType getFileTypeByOffset(int offset) { return PsiUtilBase.getPsiFileAtOffset(myPsiFile, offset).getFileType(); } @NotNull private EditorHighlighter getEditorHighlighter() { return ((EditorEx)myEditor).getHighlighter(); } private void highlightScope(int offset, @NotNull FileType fileType) { if (myEditor.getFoldingModel().isOffsetCollapsed(offset)) return; if (myEditor.getDocument().getTextLength() <= offset) return; HighlighterIterator iterator = getEditorHighlighter().createIterator(offset); final CharSequence chars = myDocument.getCharsSequence(); if (!BraceMatchingUtil.isStructuralBraceToken(fileType, iterator, chars)) { // if (BraceMatchingUtil.isRBraceTokenToHighlight(myFileType, iterator) || BraceMatchingUtil.isLBraceTokenToHighlight(myFileType, iterator)) return; } else { if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType) || BraceMatchingUtil.isLBraceToken(iterator, chars, fileType)) return; } if (!BraceMatchingUtil.findStructuralLeftBrace(fileType, iterator, chars)) { removeLineMarkers(); return; } highlightLeftBrace(iterator, true, fileType); } private void doHighlight(int offset, int originalOffset, @NotNull FileType fileType) { if (myEditor.getFoldingModel().isOffsetCollapsed(offset)) return; HighlighterIterator iterator = getEditorHighlighter().createIterator(offset); final CharSequence chars = myDocument.getCharsSequence(); if (BraceMatchingUtil.isLBraceToken(iterator, chars, fileType)) { IElementType tokenType = iterator.getTokenType(); iterator.advance(); if (!iterator.atEnd() && BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { if (BraceMatchingUtil.isPairBraces(tokenType, iterator.getTokenType(), fileType) && originalOffset == iterator.getStart()) return; } iterator.retreat(); highlightLeftBrace(iterator, false, fileType); if (offset > 0) { iterator = getEditorHighlighter().createIterator(offset - 1); if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { highlightRightBrace(iterator, fileType); } } } else if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { highlightRightBrace(iterator, fileType); } } private void highlightRightBrace(@NotNull HighlighterIterator iterator, @NotNull FileType fileType) { TextRange brace1 = TextRange.create(iterator.getStart(), iterator.getEnd()); boolean matched = BraceMatchingUtil.matchBrace(myDocument.getCharsSequence(), fileType, iterator, false); TextRange brace2 = iterator.atEnd() ? null : TextRange.create(iterator.getStart(), iterator.getEnd()); highlightBraces(brace2, brace1, matched, false, fileType); } private void highlightLeftBrace(@NotNull HighlighterIterator iterator, boolean scopeHighlighting, @NotNull FileType fileType) { TextRange brace1Start = TextRange.create(iterator.getStart(), iterator.getEnd()); boolean matched = BraceMatchingUtil.matchBrace(myDocument.getCharsSequence(), fileType, iterator, true); TextRange brace2End = iterator.atEnd() ? null : TextRange.create(iterator.getStart(), iterator.getEnd()); highlightBraces(brace1Start, brace2End, matched, scopeHighlighting, fileType); } private void highlightBraces(@Nullable TextRange lBrace, @Nullable TextRange rBrace, boolean matched, boolean scopeHighlighting, @NotNull FileType fileType) { if (!matched && fileType == FileTypes.PLAIN_TEXT) { return; } EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); final TextAttributes attributes = matched ? scheme.getAttributes(CodeInsightColors.MATCHED_BRACE_ATTRIBUTES) : scheme.getAttributes(CodeInsightColors.UNMATCHED_BRACE_ATTRIBUTES); if (rBrace != null && !scopeHighlighting) { highlightBrace(rBrace, matched); } if (lBrace != null && !scopeHighlighting) { highlightBrace(lBrace, matched); } if (!myEditor.equals(FileEditorManager.getInstance(myProject).getSelectedTextEditor())) { return; } if (lBrace != null && rBrace !=null) { final int startLine = myEditor.offsetToLogicalPosition(lBrace.getStartOffset()).line; final int endLine = myEditor.offsetToLogicalPosition(rBrace.getEndOffset()).line; if (endLine - startLine > 0) { final Runnable runnable = new Runnable() { @Override public void run() { if (myProject.isDisposed() || myEditor.isDisposed()) return; Color color = attributes.getBackgroundColor(); if (color == null) return; color = UIUtil.isUnderDarcula() ? ColorUtil.shift(color, 1.1d) : color.darker(); lineMarkFragment(startLine, endLine, color); } }; if (!scopeHighlighting) { myAlarm.addRequest(runnable, 300); } else { runnable.run(); } } else { if (!myCodeInsightSettings.HIGHLIGHT_SCOPE) { removeLineMarkers(); } } if (!scopeHighlighting) { showScopeHint(lBrace.getStartOffset(), lBrace.getEndOffset()); } } else { if (!myCodeInsightSettings.HIGHLIGHT_SCOPE) { removeLineMarkers(); } } } private void highlightBrace(@NotNull TextRange braceRange, boolean matched) { EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); final TextAttributes attributes = matched ? scheme.getAttributes(CodeInsightColors.MATCHED_BRACE_ATTRIBUTES) : scheme.getAttributes(CodeInsightColors.UNMATCHED_BRACE_ATTRIBUTES); RangeHighlighter rbraceHighlighter = myEditor.getMarkupModel().addRangeHighlighter( braceRange.getStartOffset(), braceRange.getEndOffset(), HighlighterLayer.LAST + 1, attributes, HighlighterTargetArea.EXACT_RANGE); rbraceHighlighter.setGreedyToLeft(false); rbraceHighlighter.setGreedyToRight(false); registerHighlighter(rbraceHighlighter); } private void registerHighlighter(@NotNull RangeHighlighter highlighter) { getHighlightersList().add(highlighter); } @NotNull private List<RangeHighlighter> getHighlightersList() { // braces are highlighted across the whole editor, not in each injected editor separately Editor editor = myEditor instanceof EditorWindow ? ((EditorWindow)myEditor).getDelegate() : myEditor; List<RangeHighlighter> highlighters = editor.getUserData(BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY); if (highlighters == null) { highlighters = new ArrayList<RangeHighlighter>(); editor.putUserData(BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY, highlighters); } return highlighters; } private void showScopeHint(final int lbraceStart, final int lbraceEnd) { LogicalPosition bracePosition = myEditor.offsetToLogicalPosition(lbraceStart); Point braceLocation = myEditor.logicalPositionToXY(bracePosition); final int y = braceLocation.y; myAlarm.addRequest( new Runnable() { @Override public void run() { if (!myEditor.getComponent().isShowing()) return; Rectangle viewRect = myEditor.getScrollingModel().getVisibleArea(); if (y < viewRect.y) { int start = lbraceStart; if (!(myPsiFile instanceof PsiPlainTextFile) && myPsiFile.isValid()) { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); start = BraceMatchingUtil.getBraceMatcher(getFileTypeByOffset(lbraceStart), PsiUtilCore .getLanguageAtOffset(myPsiFile, lbraceStart)).getCodeConstructStart(myPsiFile, lbraceStart); } TextRange range = new TextRange(start, lbraceEnd); int line1 = myDocument.getLineNumber(range.getStartOffset()); int line2 = myDocument.getLineNumber(range.getEndOffset()); line1 = Math.max(line1, line2 - 5); range = new TextRange(myDocument.getLineStartOffset(line1), range.getEndOffset()); EditorFragmentComponent.showEditorFragmentHint(myEditor, range, true, true); } } }, 300, ModalityState.stateForComponent(myEditor.getComponent())); } void clearBraceHighlighters() { List<RangeHighlighter> highlighters = getHighlightersList(); for (final RangeHighlighter highlighter : highlighters) { highlighter.dispose(); } highlighters.clear(); } private void lineMarkFragment(int startLine, int endLine, @NotNull Color color) { removeLineMarkers(); if (startLine >= endLine || endLine >= myDocument.getLineCount()) return; int startOffset = myDocument.getLineStartOffset(startLine); int endOffset = myDocument.getLineStartOffset(endLine); RangeHighlighter highlighter = myEditor.getMarkupModel().addRangeHighlighter(startOffset, endOffset, 0, null, HighlighterTargetArea.LINES_IN_RANGE); highlighter.setLineMarkerRenderer(new MyLineMarkerRenderer(color)); myEditor.putUserData(LINE_MARKER_IN_EDITOR_KEY, highlighter); } private void removeLineMarkers() { ApplicationManager.getApplication().assertIsDispatchThread(); RangeHighlighter marker = myEditor.getUserData(LINE_MARKER_IN_EDITOR_KEY); if (marker != null && ((MarkupModelEx)myEditor.getMarkupModel()).containsHighlighter(marker)) { marker.dispose(); } myEditor.putUserData(LINE_MARKER_IN_EDITOR_KEY, null); } private static class MyLineMarkerRenderer implements LineMarkerRenderer { private static final int DEEPNESS = 2; private static final int THICKNESS = 2; private final Color myColor; private MyLineMarkerRenderer(@NotNull Color color) { myColor = color; } @Override public void paint(Editor editor, Graphics g, Rectangle r) { int height = r.height + editor.getLineHeight(); g.setColor(myColor); g.fillRect(r.x, r.y, THICKNESS, height); g.fillRect(r.x + THICKNESS, r.y, DEEPNESS, THICKNESS); g.fillRect(r.x + THICKNESS, r.y + height - THICKNESS, DEEPNESS, THICKNESS); } } }
platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlightingHandler.java
/* * Copyright 2000-2013 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Created by IntelliJ IDEA. * User: mike * Date: Sep 27, 2002 * Time: 3:10:17 PM * To change template for new class use * Code Style | Class Templates options (Tools | IDE Options). */ package com.intellij.codeInsight.highlighting; import com.intellij.codeInsight.CodeInsightSettings; import com.intellij.codeInsight.hint.EditorFragmentComponent; import com.intellij.concurrency.Job; import com.intellij.concurrency.JobLauncher; import com.intellij.injected.editor.EditorWindow; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.colors.CodeInsightColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.EditorColorsScheme; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.ex.MarkupModelEx; import com.intellij.openapi.editor.highlighter.EditorHighlighter; import com.intellij.openapi.editor.highlighter.HighlighterIterator; import com.intellij.openapi.editor.markup.*; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.DumbAwareRunnable; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiUtilBase; import com.intellij.psi.util.PsiUtilCore; import com.intellij.ui.ColorUtil; import com.intellij.util.Alarm; import com.intellij.util.Processor; import com.intellij.util.containers.WeakHashMap; import com.intellij.util.text.CharArrayUtil; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; public class BraceHighlightingHandler { private static final Key<List<RangeHighlighter>> BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY = Key.create("BraceHighlighter.BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY"); private static final Key<RangeHighlighter> LINE_MARKER_IN_EDITOR_KEY = Key.create("BraceHighlighter.LINE_MARKER_IN_EDITOR_KEY"); /** * Holds weak references to the editors that are being processed at non-EDT. * <p/> * Is intended to be used to avoid submitting unnecessary new processing request from EDT, i.e. it's assumed that the collection * is accessed from the single thread (EDT). */ private static final Set<Editor> PROCESSED_EDITORS = Collections.newSetFromMap(new WeakHashMap<Editor, Boolean>()); @NotNull private final Project myProject; @NotNull private final Editor myEditor; private final Alarm myAlarm; private final DocumentEx myDocument; private final PsiFile myPsiFile; private final CodeInsightSettings myCodeInsightSettings; private BraceHighlightingHandler(@NotNull Project project, @NotNull Editor editor, @NotNull Alarm alarm, PsiFile psiFile) { myProject = project; myEditor = editor; myAlarm = alarm; myDocument = (DocumentEx)myEditor.getDocument(); myPsiFile = psiFile; myCodeInsightSettings = CodeInsightSettings.getInstance(); // myFileType = myPsiFile == null ? null : myPsiFile.getFileType(); } static void lookForInjectedAndMatchBracesInOtherThread(@NotNull final Editor editor, @NotNull final Alarm alarm, @NotNull final Processor<BraceHighlightingHandler> processor) { ApplicationManagerEx.getApplicationEx().assertIsDispatchThread(); if (!PROCESSED_EDITORS.add(editor)) { // Skip processing if that is not really necessary. // Assuming to be in EDT here. return; } final Project project = editor.getProject(); if (project == null) return; final int offset = editor.getCaretModel().getOffset(); JobLauncher.getInstance().submitToJobThread(Job.DEFAULT_PRIORITY, new Runnable() { @Override public void run() { if (!ApplicationManagerEx.getApplicationEx().tryRunReadAction(new Runnable() { @Override public void run() { final PsiFile injected; try { if (isReallyDisposed(editor, project)) return; PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); injected = psiFile == null || psiFile instanceof PsiCompiledElement ? null : getInjectedFileIfAny(editor, project, offset, psiFile, alarm); } catch (RuntimeException e) { // Reset processing flag in case of unexpected exception. ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { @Override public void run() { PROCESSED_EDITORS.remove(editor); } }); throw e; } ApplicationManager.getApplication().invokeLater(new DumbAwareRunnable() { @Override public void run() { try { if (!isReallyDisposed(editor, project)) { Editor newEditor = InjectedLanguageUtil.getInjectedEditorForInjectedFile(editor, injected); BraceHighlightingHandler handler = new BraceHighlightingHandler(project, newEditor, alarm, injected); processor.process(handler); } } finally { PROCESSED_EDITORS.remove(editor); } } }, ModalityState.stateForComponent(editor.getComponent())); } })) { // write action is queued in AWT. restart after it's finished ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { PROCESSED_EDITORS.remove(editor); lookForInjectedAndMatchBracesInOtherThread(editor, alarm, processor); } }, ModalityState.stateForComponent(editor.getComponent())); } } }); } private static boolean isReallyDisposed(@NotNull Editor editor, @NotNull Project project) { Project editorProject = editor.getProject(); return editorProject == null || editorProject.isDisposed() || project.isDisposed() || !editor.getComponent().isShowing() || editor.isViewer(); } @NotNull private static PsiFile getInjectedFileIfAny(@NotNull final Editor editor, @NotNull final Project project, int offset, @NotNull PsiFile psiFile, @NotNull final Alarm alarm) { Document document = editor.getDocument(); // when document is committed, try to highlight braces in injected lang - it's fast if (PsiDocumentManager.getInstance(project).isCommitted(document)) { final PsiElement injectedElement = InjectedLanguageUtil.findInjectedElementNoCommit(psiFile, offset); if (injectedElement != null /*&& !(injectedElement instanceof PsiWhiteSpace)*/) { final PsiFile injected = injectedElement.getContainingFile(); if (injected != null) { return injected; } } } else { PsiDocumentManager.getInstance(project).performForCommittedDocument(document, new Runnable() { @Override public void run() { if (!project.isDisposed() && !editor.isDisposed()) { BraceHighlighter.updateBraces(editor, alarm); } } }); } return psiFile; } void updateBraces() { if (myPsiFile == null || !myPsiFile.isValid()) return; clearBraceHighlighters(); if (!myCodeInsightSettings.HIGHLIGHT_BRACES) return; if (myEditor.getSelectionModel().hasSelection()) return; if (myEditor.getSoftWrapModel().isInsideOrBeforeSoftWrap(myEditor.getCaretModel().getVisualPosition())) return; int offset = myEditor.getCaretModel().getOffset(); final CharSequence chars = myEditor.getDocument().getCharsSequence(); //if (myEditor.offsetToLogicalPosition(offset).column != myEditor.getCaretModel().getLogicalPosition().column) { // // we are in virtual space // final int caretLineNumber = myEditor.getCaretModel().getLogicalPosition().line; // if (caretLineNumber >= myDocument.getLineCount()) return; // offset = myDocument.getLineEndOffset(caretLineNumber) + myDocument.getLineSeparatorLength(caretLineNumber); //} final int originalOffset = offset; HighlighterIterator iterator = getEditorHighlighter().createIterator(offset); FileType fileType = PsiUtilBase.getPsiFileAtOffset(myPsiFile, offset).getFileType(); if (iterator.atEnd()) { offset--; } else if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { offset--; } else if (!BraceMatchingUtil.isLBraceToken(iterator, chars, fileType)) { offset--; if (offset >= 0) { final HighlighterIterator i = getEditorHighlighter().createIterator(offset); if (!BraceMatchingUtil.isRBraceToken(i, chars, getFileTypeByIterator(i))) offset++; } } if (offset < 0) { removeLineMarkers(); return; } iterator = getEditorHighlighter().createIterator(offset); fileType = getFileTypeByIterator(iterator); myAlarm.cancelAllRequests(); if (BraceMatchingUtil.isLBraceToken(iterator, chars, fileType) || BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { doHighlight(offset, originalOffset, fileType); } else if (offset > 0 && offset < chars.length()) { // There is a possible case that there are paired braces nearby the caret position and the document contains only white // space symbols between them. We want to highlight such braces as well. // Example: // public void test() { <caret> // } char c = chars.charAt(offset); boolean searchForward = c != '\n'; // Try to find matched brace backwards. if (offset >= originalOffset && (c == ' ' || c == '\t' || c == '\n')) { int backwardNonWsOffset = CharArrayUtil.shiftBackward(chars, offset - 1, "\t "); if (backwardNonWsOffset >= 0) { iterator = getEditorHighlighter().createIterator(backwardNonWsOffset); FileType newFileType = getFileTypeByIterator(iterator); if (BraceMatchingUtil.isLBraceToken(iterator, chars, newFileType) || BraceMatchingUtil.isRBraceToken(iterator, chars, newFileType)) { offset = backwardNonWsOffset; searchForward = false; doHighlight(backwardNonWsOffset, originalOffset, newFileType); } } } // Try to find matched brace forward. if (searchForward) { int forwardOffset = CharArrayUtil.shiftForward(chars, offset, "\t "); if (forwardOffset > offset || c == ' ' || c == '\t') { iterator = getEditorHighlighter().createIterator(forwardOffset); FileType newFileType = getFileTypeByIterator(iterator); if (BraceMatchingUtil.isLBraceToken(iterator, chars, newFileType) || BraceMatchingUtil.isRBraceToken(iterator, chars, newFileType)) { offset = forwardOffset; doHighlight(forwardOffset, originalOffset, newFileType); } } } } //highlight scope if (!myCodeInsightSettings.HIGHLIGHT_SCOPE) { removeLineMarkers(); return; } final int _offset = offset; final FileType _fileType = fileType; myAlarm.addRequest(new Runnable() { @Override public void run() { if (!myProject.isDisposed() && !myEditor.isDisposed()) { highlightScope(_offset, _fileType); } } }, 300); } @NotNull private FileType getFileTypeByIterator(@NotNull HighlighterIterator iterator) { return PsiUtilBase.getPsiFileAtOffset(myPsiFile, iterator.getStart()).getFileType(); } @NotNull private FileType getFileTypeByOffset(int offset) { return PsiUtilBase.getPsiFileAtOffset(myPsiFile, offset).getFileType(); } @NotNull private EditorHighlighter getEditorHighlighter() { return ((EditorEx)myEditor).getHighlighter(); } private void highlightScope(int offset, @NotNull FileType fileType) { if (myEditor.getFoldingModel().isOffsetCollapsed(offset)) return; if (myEditor.getDocument().getTextLength() <= offset) return; HighlighterIterator iterator = getEditorHighlighter().createIterator(offset); final CharSequence chars = myDocument.getCharsSequence(); if (!BraceMatchingUtil.isStructuralBraceToken(fileType, iterator, chars)) { // if (BraceMatchingUtil.isRBraceTokenToHighlight(myFileType, iterator) || BraceMatchingUtil.isLBraceTokenToHighlight(myFileType, iterator)) return; } else { if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType) || BraceMatchingUtil.isLBraceToken(iterator, chars, fileType)) return; } if (!BraceMatchingUtil.findStructuralLeftBrace(fileType, iterator, chars)) { removeLineMarkers(); return; } highlightLeftBrace(iterator, true, fileType); } private void doHighlight(int offset, int originalOffset, @NotNull FileType fileType) { if (myEditor.getFoldingModel().isOffsetCollapsed(offset)) return; HighlighterIterator iterator = getEditorHighlighter().createIterator(offset); final CharSequence chars = myDocument.getCharsSequence(); if (BraceMatchingUtil.isLBraceToken(iterator, chars, fileType)) { IElementType tokenType = iterator.getTokenType(); iterator.advance(); if (!iterator.atEnd() && BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { if (BraceMatchingUtil.isPairBraces(tokenType, iterator.getTokenType(), fileType) && originalOffset == iterator.getStart()) return; } iterator.retreat(); highlightLeftBrace(iterator, false, fileType); if (offset > 0) { iterator = getEditorHighlighter().createIterator(offset - 1); if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { highlightRightBrace(iterator, fileType); } } } else if (BraceMatchingUtil.isRBraceToken(iterator, chars, fileType)) { highlightRightBrace(iterator, fileType); } } private void highlightRightBrace(@NotNull HighlighterIterator iterator, @NotNull FileType fileType) { TextRange brace1 = TextRange.create(iterator.getStart(), iterator.getEnd()); boolean matched = BraceMatchingUtil.matchBrace(myDocument.getCharsSequence(), fileType, iterator, false); TextRange brace2 = iterator.atEnd() ? null : TextRange.create(iterator.getStart(), iterator.getEnd()); highlightBraces(brace2, brace1, matched, false, fileType); } private void highlightLeftBrace(@NotNull HighlighterIterator iterator, boolean scopeHighlighting, @NotNull FileType fileType) { TextRange brace1Start = TextRange.create(iterator.getStart(), iterator.getEnd()); boolean matched = BraceMatchingUtil.matchBrace(myDocument.getCharsSequence(), fileType, iterator, true); TextRange brace2End = iterator.atEnd() ? null : TextRange.create(iterator.getStart(), iterator.getEnd()); highlightBraces(brace1Start, brace2End, matched, scopeHighlighting, fileType); } private void highlightBraces(@Nullable TextRange lBrace, @Nullable TextRange rBrace, boolean matched, boolean scopeHighlighting, @NotNull FileType fileType) { if (!matched && fileType == FileTypes.PLAIN_TEXT) { return; } EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); final TextAttributes attributes = matched ? scheme.getAttributes(CodeInsightColors.MATCHED_BRACE_ATTRIBUTES) : scheme.getAttributes(CodeInsightColors.UNMATCHED_BRACE_ATTRIBUTES); if (rBrace != null && !scopeHighlighting) { highlightBrace(rBrace, matched); } if (lBrace != null && !scopeHighlighting) { highlightBrace(lBrace, matched); } if (!myEditor.equals(FileEditorManager.getInstance(myProject).getSelectedTextEditor())) { return; } if (lBrace != null && rBrace !=null) { final int startLine = myEditor.offsetToLogicalPosition(lBrace.getStartOffset()).line; final int endLine = myEditor.offsetToLogicalPosition(rBrace.getEndOffset()).line; if (endLine - startLine > 0) { final Runnable runnable = new Runnable() { @Override public void run() { if (myProject.isDisposed() || myEditor.isDisposed()) return; Color color = attributes.getBackgroundColor(); if (color == null) return; color = UIUtil.isUnderDarcula() ? ColorUtil.shift(color, 1.1d) : color.darker(); lineMarkFragment(startLine, endLine, color); } }; if (!scopeHighlighting) { myAlarm.addRequest(runnable, 300); } else { runnable.run(); } } else { if (!myCodeInsightSettings.HIGHLIGHT_SCOPE) { removeLineMarkers(); } } if (!scopeHighlighting) { showScopeHint(lBrace.getStartOffset(), lBrace.getEndOffset()); } } else { if (!myCodeInsightSettings.HIGHLIGHT_SCOPE) { removeLineMarkers(); } } } private void highlightBrace(@NotNull TextRange braceRange, boolean matched) { EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); final TextAttributes attributes = matched ? scheme.getAttributes(CodeInsightColors.MATCHED_BRACE_ATTRIBUTES) : scheme.getAttributes(CodeInsightColors.UNMATCHED_BRACE_ATTRIBUTES); RangeHighlighter rbraceHighlighter = myEditor.getMarkupModel().addRangeHighlighter( braceRange.getStartOffset(), braceRange.getEndOffset(), HighlighterLayer.LAST + 1, attributes, HighlighterTargetArea.EXACT_RANGE); rbraceHighlighter.setGreedyToLeft(false); rbraceHighlighter.setGreedyToRight(false); registerHighlighter(rbraceHighlighter); } private void registerHighlighter(@NotNull RangeHighlighter highlighter) { getHighlightersList().add(highlighter); } @NotNull private List<RangeHighlighter> getHighlightersList() { // braces are highlighted across the whole editor, not in each injected editor separately Editor editor = myEditor instanceof EditorWindow ? ((EditorWindow)myEditor).getDelegate() : myEditor; List<RangeHighlighter> highlighters = editor.getUserData(BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY); if (highlighters == null) { highlighters = new ArrayList<RangeHighlighter>(); editor.putUserData(BRACE_HIGHLIGHTERS_IN_EDITOR_VIEW_KEY, highlighters); } return highlighters; } private void showScopeHint(final int lbraceStart, final int lbraceEnd) { LogicalPosition bracePosition = myEditor.offsetToLogicalPosition(lbraceStart); Point braceLocation = myEditor.logicalPositionToXY(bracePosition); final int y = braceLocation.y; myAlarm.addRequest( new Runnable() { @Override public void run() { if (!myEditor.getComponent().isShowing()) return; Rectangle viewRect = myEditor.getScrollingModel().getVisibleArea(); if (y < viewRect.y) { int start = lbraceStart; if (!(myPsiFile instanceof PsiPlainTextFile) && myPsiFile.isValid()) { PsiDocumentManager.getInstance(myProject).commitAllDocuments(); start = BraceMatchingUtil.getBraceMatcher(getFileTypeByOffset(lbraceStart), PsiUtilCore .getLanguageAtOffset(myPsiFile, lbraceStart)).getCodeConstructStart(myPsiFile, lbraceStart); } TextRange range = new TextRange(start, lbraceEnd); int line1 = myDocument.getLineNumber(range.getStartOffset()); int line2 = myDocument.getLineNumber(range.getEndOffset()); line1 = Math.max(line1, line2 - 5); range = new TextRange(myDocument.getLineStartOffset(line1), range.getEndOffset()); EditorFragmentComponent.showEditorFragmentHint(myEditor, range, true, true); } } }, 300, ModalityState.stateForComponent(myEditor.getComponent())); } void clearBraceHighlighters() { List<RangeHighlighter> highlighters = getHighlightersList(); for (final RangeHighlighter highlighter : highlighters) { highlighter.dispose(); } highlighters.clear(); } private void lineMarkFragment(int startLine, int endLine, @NotNull Color color) { removeLineMarkers(); if (startLine >= endLine || endLine >= myDocument.getLineCount()) return; int startOffset = myDocument.getLineStartOffset(startLine); int endOffset = myDocument.getLineStartOffset(endLine); RangeHighlighter highlighter = myEditor.getMarkupModel().addRangeHighlighter(startOffset, endOffset, 0, null, HighlighterTargetArea.LINES_IN_RANGE); highlighter.setLineMarkerRenderer(new MyLineMarkerRenderer(color)); myEditor.putUserData(LINE_MARKER_IN_EDITOR_KEY, highlighter); } private void removeLineMarkers() { ApplicationManager.getApplication().assertIsDispatchThread(); RangeHighlighter marker = myEditor.getUserData(LINE_MARKER_IN_EDITOR_KEY); if (marker != null && ((MarkupModelEx)myEditor.getMarkupModel()).containsHighlighter(marker)) { marker.dispose(); } myEditor.putUserData(LINE_MARKER_IN_EDITOR_KEY, null); } private static class MyLineMarkerRenderer implements LineMarkerRenderer { private static final int DEEPNESS = 2; private static final int THICKNESS = 2; private final Color myColor; private MyLineMarkerRenderer(@NotNull Color color) { myColor = color; } @Override public void paint(Editor editor, Graphics g, Rectangle r) { int height = r.height + editor.getLineHeight(); g.setColor(myColor); g.fillRect(r.x, r.y, THICKNESS, height); g.fillRect(r.x + THICKNESS, r.y, DEEPNESS, THICKNESS); g.fillRect(r.x + THICKNESS, r.y + height - THICKNESS, DEEPNESS, THICKNESS); } } }
EA-49821 - assert: CaretModelImpl.validateCallContext
platform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlightingHandler.java
EA-49821 - assert: CaretModelImpl.validateCallContext
<ide><path>latform/lang-impl/src/com/intellij/codeInsight/highlighting/BraceHighlightingHandler.java <ide> final Project project = editor.getProject(); <ide> if (project == null) return; <ide> final int offset = editor.getCaretModel().getOffset(); <add> final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); <ide> JobLauncher.getInstance().submitToJobThread(Job.DEFAULT_PRIORITY, new Runnable() { <ide> @Override <ide> public void run() { <ide> final PsiFile injected; <ide> try { <ide> if (isReallyDisposed(editor, project)) return; <del> PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project); <ide> injected = psiFile == null || psiFile instanceof PsiCompiledElement <ide> ? null : getInjectedFileIfAny(editor, project, offset, psiFile, alarm); <ide> } <ide> } <ide> <ide> void updateBraces() { <add> ApplicationManager.getApplication().assertIsDispatchThread(); <add> <ide> if (myPsiFile == null || !myPsiFile.isValid()) return; <ide> <ide> clearBraceHighlighters();
JavaScript
agpl-3.0
8560d36421a2eb7aabe49cf63d51f766b43ebdb3
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
48e4a41a-2e63-11e5-9284-b827eb9e62be
helloWorld.js
48df3b2e-2e63-11e5-9284-b827eb9e62be
48e4a41a-2e63-11e5-9284-b827eb9e62be
helloWorld.js
48e4a41a-2e63-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>48df3b2e-2e63-11e5-9284-b827eb9e62be <add>48e4a41a-2e63-11e5-9284-b827eb9e62be
Java
agpl-3.0
1787a5eca377685f4969bf2ecd9979c93549a21f
0
aikuma/aikuma,aikuma/aikuma,lisaslyis/aikuma,hleeldc/aikuma,lisaslyis/aikuma,aikuma/aikuma,lisaslyis/aikuma,aikuma/aikuma,aikuma/aikuma,lisaslyis/aikuma,hleeldc/aikuma,lisaslyis/aikuma,hleeldc/aikuma,hleeldc/aikuma,hleeldc/aikuma
package org.lp20.aikuma.audio; import android.util.Log; import android.media.MediaPlayer; import java.io.File; import java.io.IOException; import org.lp20.aikuma.model.Recording; /** * @author Oliver Adams <[email protected]> * @author Florian Hanke <[email protected]> */ public class SimplePlayer extends Player implements Sampler { /** * Creates a player to play the supplied recording. * * @param recording The metadata of the recording to play. */ public SimplePlayer(Recording recording) throws IOException { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(recording.getFile().getCanonicalPath()); mediaPlayer.prepare(); setSampleRate(recording.getSampleRate()); } /** * Creates a player to play the supplied recording for when no Recording * metadata file exists * * @param file The location of the recording as a File * @param sampleRate The sample rate of the recording */ public SimplePlayer(File recordingFile, long sampleRate) throws IOException { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(recordingFile.getCanonicalPath()); mediaPlayer.prepare(); setSampleRate(sampleRate); } /** Starts or resumes playback of the recording. */ public void play() { mediaPlayer.start(); } /** Pauses the playback. */ public void pause() { mediaPlayer.pause(); } /** Indicates whether the recording is currently being played. */ public boolean isPlaying() { return mediaPlayer.isPlaying(); } /** Get current point in the recording in milliseconds. */ public int getCurrentMsec() { try { return mediaPlayer.getCurrentPosition(); } catch (IllegalStateException e) { //If we get an IllegalStateException because the recording has //finished playing, just return the duration of the recording. return getDurationMsec(); } } public long getCurrentSample() { return msecToSample(getCurrentMsec()); } /** Get the duration of the recording in milliseconds. */ public int getDurationMsec() { try { return mediaPlayer.getDuration(); } catch (IllegalStateException e) { //If this fails then we won't be in an activity where a duration is //actually required. -1 is returned so we at least know it was //erroneous if we ever need to. return -1; } } /** Seek to a given point in the recording in milliseconds. */ public void seekToMsec(int msec) { mediaPlayer.seekTo(msec); } public void seekToSample(long sample) { seekToMsec(sampleToMsec(sample)); } /** Releases the resources associated with the SimplePlayer */ public void release() { mediaPlayer.release(); } /** Set the callback to be run when the recording completes playing. */ public void setOnCompletionListener(final OnCompletionListener listener) { mediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer _mp) { listener.onCompletion(SimplePlayer.this); } }); } public long getSampleRate() { //If the sample rate is less than zero, then this indicates that there //wasn't a sample rate found in the metadata file. if (sampleRate <= 0l) { throw new RuntimeException( "The sampleRate of the recording is not known."); } return sampleRate; } private void setSampleRate(long sampleRate) { this.sampleRate = sampleRate; } public int sampleToMsec(long sample) { long msec = sample / (getSampleRate() / 1000); if (msec > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return (int) msec; } public long msecToSample(int msec) { return msec * (getSampleRate() / 1000); } public void setAudioStreamType(int type) { mediaPlayer.setAudioStreamType(type); } /** The MediaPlayer used to play the recording. **/ private MediaPlayer mediaPlayer; private long sampleRate; }
Aikuma/src/org/lp20/aikuma/audio/SimplePlayer.java
package org.lp20.aikuma.audio; import android.util.Log; import android.media.MediaPlayer; import java.io.File; import java.io.IOException; import org.lp20.aikuma.model.Recording; /** * @author Oliver Adams <[email protected]> * @author Florian Hanke <[email protected]> */ public class SimplePlayer extends Player implements Sampler { /** * Creates a player to play the supplied recording. * * @param recording The metadata of the recording to play. */ public SimplePlayer(Recording recording) throws IOException { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(recording.getFile().getCanonicalPath()); mediaPlayer.prepare(); setSampleRate(recording.getSampleRate()); } /** * Creates a player to play the supplied recording for when no Recording * metadata file exists * * @param file The location of the recording as a File * @param sampleRate The sample rate of the recording */ public SimplePlayer(File recordingFile, long sampleRate) throws IOException { mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(recordingFile.getCanonicalPath()); mediaPlayer.prepare(); setSampleRate(sampleRate); } /** Starts or resumes playback of the recording. */ public void play() { mediaPlayer.start(); } /** Pauses the playback. */ public void pause() { mediaPlayer.pause(); } /** Indicates whether the recording is currently being played. */ public boolean isPlaying() { return mediaPlayer.isPlaying(); } /** Get current point in the recording in milliseconds. */ public int getCurrentMsec() { try { return mediaPlayer.getCurrentPosition(); } catch (IllegalStateException e) { //If we get an IllegalStateException because the recording has //finished playing, just return the duration of the recording. return getDurationMsec(); } } public long getCurrentSample() { return msecToSample(getCurrentMsec()); } /** Get the duration of the recording in milliseconds. */ public int getDurationMsec() { return mediaPlayer.getDuration(); } /** Seek to a given point in the recording in milliseconds. */ public void seekToMsec(int msec) { mediaPlayer.seekTo(msec); } public void seekToSample(long sample) { seekToMsec(sampleToMsec(sample)); } /** Releases the resources associated with the SimplePlayer */ public void release() { mediaPlayer.release(); } /** Set the callback to be run when the recording completes playing. */ public void setOnCompletionListener(final OnCompletionListener listener) { mediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { public void onCompletion(MediaPlayer _mp) { listener.onCompletion(SimplePlayer.this); } }); } public long getSampleRate() { //If the sample rate is less than zero, then this indicates that there //wasn't a sample rate found in the metadata file. if (sampleRate <= 0l) { throw new RuntimeException( "The sampleRate of the recording is not known."); } return sampleRate; } private void setSampleRate(long sampleRate) { this.sampleRate = sampleRate; } public int sampleToMsec(long sample) { long msec = sample / (getSampleRate() / 1000); if (msec > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } return (int) msec; } public long msecToSample(int msec) { return msec * (getSampleRate() / 1000); } public void setAudioStreamType(int type) { mediaPlayer.setAudioStreamType(type); } /** The MediaPlayer used to play the recording. **/ private MediaPlayer mediaPlayer; private long sampleRate; }
caught the IllegalStateException that getDurationMsec could throw in order to prevent crashing Steven experienced
Aikuma/src/org/lp20/aikuma/audio/SimplePlayer.java
caught the IllegalStateException that getDurationMsec could throw in order to prevent crashing Steven experienced
<ide><path>ikuma/src/org/lp20/aikuma/audio/SimplePlayer.java <ide> <ide> /** Get the duration of the recording in milliseconds. */ <ide> public int getDurationMsec() { <del> return mediaPlayer.getDuration(); <add> try { <add> return mediaPlayer.getDuration(); <add> } catch (IllegalStateException e) { <add> //If this fails then we won't be in an activity where a duration is <add> //actually required. -1 is returned so we at least know it was <add> //erroneous if we ever need to. <add> return -1; <add> } <ide> } <ide> <ide> /** Seek to a given point in the recording in milliseconds. */
JavaScript
apache-2.0
8c05314d6363ebe42265161bd4d058e4a8ed9c18
0
IHTSDO/sct-browser-frontend,IHTSDO/sct-browser-frontend,IHTSDO/sct-browser-frontend
this["JST"] = this["JST"] || {}; this["JST"]["views/conceptDetailsPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='margin: 5px; height:98%; overflow:auto;' class='panel panel-default'>\n <div class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading' ondrop=\"dropC(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\">\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding:2px;position: absolute;top: 1px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-8' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_concept_details'>Concept Details</span></strong></div>\n <div class='col-md-4 text-right'>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div class='panel-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <!-- Nav tabs -->\n <ul class=\"nav nav-tabs\" id=\"details-tabs-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <li class=\"active\"><a href=\"#home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_summary\">Summary</span></a></li>\n <li><a href=\"#details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_details\">Details</span></a></li>\n <li id=\"diagram-tab\"><a href=\"#diagram-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\" id=\"diagram-tab-link-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"><span class=\"i18n\" data-i18n-id=\"i18n_diagram\">Diagram</span></a></li>\n <li id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-members-tab\"><a href=\"#members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_members\">Members</span></a></li>\n <li id=\"product-details-tab\" style=\"display: none;\"><a id=\"product-details-tab-link-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" href=\"#product-details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_vcd\">CD</span></a></li>\n </ul>\n <!-- Tab panes -->\n <div class=\"tab-content\" id=\"details-tab-content-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"tab-pane fade in active\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" style=\"padding: 5px;\">\n <div class=\"pull-right\">\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-stated-button\">Stated</button>\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferred-button\">Inferred</button>\n </div>\n <div><span class=\"text-muted text-center\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-wf-status-label\"></span></div>\n </div>\n <div style=\"max-height: 300px; overflow: auto; margin-left: 0%; margin-bottom: 10px; margin-top: 10px; width: 80%;border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\">\n <div class=\"panel-heading\">\n <h4><span data-i18n-id=\"i18n_parents\" class=\"i18n\">Parents</span></h4>\n </div>\n <div class=\"panel-body\" id=\"home-parents-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <span data-i18n-id=\"i18n_no_parents\" class=\"i18n\">No parents</span>\n </div>\n </div>\n <div class=\"row\" style=\"overflow: auto; max-height: 30%;\">\n <div class=\"col-md-offset-1 col-md-4\" style=\"color: #ffffff;background-color: #1e90ff;display: inline-block; border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\" id=\"home-attributes-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Attributes</div>\n <div class=\"col-md-4\" style=\"background-color: rgba(30, 144, 255, 0.17); display: inline-block; min-height: 100%; margin-left: 10px; border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\" id=\"home-roles-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Relationships</div>\n </div>\n <div style=\"max-height: 300px; overflow: auto; margin-left: 0%; margin-bottom: 10px; margin-top: 10px; width: 80%;border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\" id=\"home-children-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"panel-heading\">\n <h4><span data-i18n-id=\"i18n_children\" class=\"i18n\">Children</span>&nbsp;<span id=\"home-children-cant-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></span></h4>\n </div>\n <div class=\"panel-body\" id=\"home-children-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-body\"></div>\n </div>\n <div><span class=\"text-muted pull-right\" id=\"footer-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></span></div>\n </div>\n <div class=\"tab-pane fade\" id=\"details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"pull-right\">\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" class=\"btn btn-default\" id=\"details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-stated-button\">Stated</button>\n <button type=\"button\" class=\"btn btn-default\" id=\"details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferred-button\">Inferred</button>\n </div>\n <div><span class=\"text-muted text-center\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-wf-status-label\"></span></div>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-attributes-panel' class='panel panel-default'>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descriptions-panel' class='panel panel-default'>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-rels-panel' class='panel panel-default'>\n </div>\n <!--<div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-children-panel' class='panel panel-default' style='height:100px;overflow:auto;margin-bottom: 15px;'>-->\n <!--</div>-->\n </div>\n <div class=\"tab-pane fade\" id=\"diagram-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"row\" style=\"margin-right: 20px\"><span class=\"pull-right text-muted\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagram-viewLabel\"></span></div>\n <div id=\"diagram-canvas-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></div>\n </div>\n <div class=\"tab-pane fade\" id=\"expression-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"row\" style=\"margin-right: 20px\"><span class=\"pull-right text-muted\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expression-viewLabel\"></span></div>\n <div id=\"expression-canvas-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></div>\n </div>\n <div class=\"tab-pane fade\" id=\"refsets-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n </div>\n <div class=\"tab-pane fade\" id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <!--<div class=\"pull-right\" style=\"padding: 5px\">-->\n <!--<button id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-sort\" class=\"btn btn-default\">Sort results</button>-->\n <!--<span class=\"text-muted\">This operation may time-out for large refsets</span>-->\n <!--</div>-->\n <!--<br>-->\n <table id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable\" class=\"table table-hover table-bordered\">\n </table>\n <!--<button id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-normal\" class=\"btn btn-default\">100 first members</button>-->\n </div>\n <div class=\"tab-pane fade\" id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"panel-group\" id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-accordion\">\n\n </div>\n <!--<br>-->\n <!--<span class=\"text-muted\" style=\"padding: 5px;\" id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-total\"></span>-->\n <!--<table id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable\" class=\"table table-hover table-bordered\">-->\n <!--</table>-->\n </div>\n <div class=\"tab-pane fade\" id=\"product-details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n </div>\n</div>\n<div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n</div>\n "; return buffer; }); this["JST"]["views/conceptDetailsPlugin/options.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displaySynonymsOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_display_synonyms2\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options) : helperMissing.call(depth0, "i18n", "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options))) + "</span>\n "; return buffer; } function program3(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displaySynonymsOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_display_synonyms2\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options) : helperMissing.call(depth0, "i18n", "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options))) + "</span>\n "; return buffer; } function program5(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayIdsOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_display_ids\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_ids", "Display Description Ids", options) : helperMissing.call(depth0, "i18n", "i18n_display_ids", "Display Description Ids", options))) + "</span>\n "; return buffer; } function program7(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayIdsOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_display_ids\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_ids", "Display Description Ids", options) : helperMissing.call(depth0, "i18n", "i18n_display_ids", "Display Description Ids", options))) + "</span>\n "; return buffer; } function program9(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayInactiveDescriptionsOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_display_inactive_descriptions\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_inactive_descriptions", "Display inactive descriptions", options) : helperMissing.call(depth0, "i18n", "i18n_display_inactive_descriptions", "Display inactive descriptions", options))) + "</span>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayInactiveDescriptionsOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_display_inactive_descriptions\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_inactive_descriptions", "Display inactive descriptions", options) : helperMissing.call(depth0, "i18n", "i18n_display_inactive_descriptions", "Display inactive descriptions", options))) + "</span>\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-hideNotAcceptableOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_hide_not_acceptable\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options) : helperMissing.call(depth0, "i18n", "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options))) + "</span>\n "; return buffer; } function program15(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-hideNotAcceptableOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_hide_not_acceptable\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options) : helperMissing.call(depth0, "i18n", "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options))) + "</span>\n "; return buffer; } function program17(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagrammingMarkupEnabledOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_diagramming_markup_enabled\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options) : helperMissing.call(depth0, "i18n", "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options))) + "</span>\n "; return buffer; } function program19(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagrammingMarkupEnabledOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_diagramming_markup_enabled\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options) : helperMissing.call(depth0, "i18n", "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options))) + "</span>\n "; return buffer; } function program21(depth0,data) { return "checked"; } function program23(depth0,data) { return "\n <option value=\"stated\" selected>Stated</option>\n "; } function program25(depth0,data) { return "\n <option value=\"stated\">Stated</option>\n "; } function program27(depth0,data) { return "\n <option value=\"inferred\" selected>Inferred</option>\n "; } function program29(depth0,data) { return "\n <option value=\"inferred\">Inferred</option>\n "; } function program31(depth0,data) { return "\n <option value=\"all\" selected>All</option>\n "; } function program33(depth0,data) { return "\n <option value=\"all\">All</option>\n "; } function program35(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.manifest)),stack1 == null || stack1 === false ? stack1 : stack1.languageRefsets), {hash:{},inverse:self.noop,fn:self.programWithDepth(36, program36, data, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program36(depth0,data,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <div class=\"checkbox\">\n <label>\n <input class=\"langOption\" type=\"checkbox\" value=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = (helper = helpers.ifIn || (depth0 && depth0.ifIn),options={hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptId), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.langRefset), options) : helperMissing.call(depth0, "ifIn", (depth0 && depth0.conceptId), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.langRefset), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </label>\n </div>\n "; return buffer; } function program38(depth0,data,depth1) { var buffer = "", stack1, helper; buffer += "-->\n <!--<tr>-->\n <!--<td>"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>-->\n <!--<td>-->\n <!--<div class=\"checkbox\">-->\n <!--<label>-->\n <!--<input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscribeTo-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscribed), {hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">-->\n <!--</label>-->\n <!--</div>-->\n <!--</td>-->\n <!--<td>-->\n <!--<div class=\"checkbox\">-->\n <!--<label>-->\n <!--<input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscriptor-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscriptor), {hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">-->\n <!--</label>-->\n <!--</div>-->\n <!--</td>-->\n <!--</tr>-->\n <!--"; return buffer; } buffer += "<form role=\"form\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-options-form\">\n <div class=\"form-group\">\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.displaySynonyms), {hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.showIds), {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.displayInactiveDescriptions), {hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.hideNotAcceptable), {hash:{},inverse:self.program(15, program15, data),fn:self.program(13, program13, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.diagrammingMarkupEnabled), {hash:{},inverse:self.program(19, program19, data),fn:self.program(17, program17, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayChildren\" "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.displayChildren), {hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> <span class=\"i18n\" data-i18n-id=\"i18n_display_children\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_children", "Display All Children", options) : helperMissing.call(depth0, "i18n", "i18n_display_children", "Display All Children", options))) + "</span>\n </label>\n </div>\n </div>\n <div class=\"form-group\">\n <label for=\"selectedRelsView\"><span class=\"i18n\" data-i18n-id=\"i18n_rels_view\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_rels_view", "Relationships View", options) : helperMissing.call(depth0, "i18n", "i18n_rels_view", "Relationships View", options))) + "</span></label>\n <select class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-relsViewOption\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(25, program25, data),fn:self.program(23, program23, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(29, program29, data),fn:self.program(27, program27, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(33, program33, data),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "all", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "all", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </select>\n </div>\n <div class=\"form-group\">\n <label><span class=\"i18n\" data-i18n-id=\"i18n_language_refset\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_language_refset", "Language Refset", options) : helperMissing.call(depth0, "i18n", "i18n_language_refset", "Language Refset", options))) + "</span></label>\n\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.manifest)),stack1 == null || stack1 === false ? stack1 : stack1.languageRefsets), {hash:{},inverse:self.noop,fn:self.programWithDepth(35, program35, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <!--<div class=\"form-group\">-->\n <!--<table class='table table-bordered table-hover'>-->\n <!--<thead>-->\n <!--<tr>-->\n <!--<th>Panel</th>-->\n <!--<th>Subscribed</th>-->\n <!--<th>Subscriptor</th>-->\n <!--</tr>-->\n <!--</thead>-->\n <!--<tbody>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.possibleSubscribers), {hash:{},inverse:self.noop,fn:self.programWithDepth(38, program38, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</tbody>-->\n <!--</table>-->\n <!--</div>-->\n</form>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/attributes-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { return "\n class = 'highlightEffectiveTime'\n "; } function program3(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" style=\"color: inherit;text-decoration: inherit;\"><span class=\"badge alert-warning\">&nbsp;&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program5(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" style=\"color: inherit;text-decoration: inherit;\"><span class=\"badge alert-warning\" >&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program7(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_primitive'>PRIMITIVE</span>\n "; } function program9(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_fully_defined'>Fully defined</span>\n "; } function program11(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_active'>Active</span>\n "; } function program13(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_inactive'>Inactive</span>\n "; } function program15(depth0,data) { return "\n "; } function program17(depth0,data) { var buffer = "", stack1; buffer += "\n . Descendants count, Stated: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendantsString)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " concepts, Inferred: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.inferredDescendantsString)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " concepts.\n "; return buffer; } function program19(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"pull-right\">\n <div class=\"dropdown\">\n <button class=\"btn btn-link dropdown-toggle\" type=\"button\" id=\"dropdownMenu1-details\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <i class=\"glyphicon glyphicon-plus-sign pull-right\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addsyn-icon-details\"></i>\n </button>\n <ul class=\"dropdown-menu small pull-right\" role=\"menu\" aria-labelledby=\"dropdownMenu2-details\">\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addsyn-sctid-details\">Skicka synonymförslag</a></li>\n </ul>\n </div>\n </span>\n "; return buffer; } buffer += "<table class='table table-default' >\n <tr\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n >\n <td>\n <h4>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <span ondrop=\"dropC(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n </h4>\n <br>SCTID: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.active), true, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.active), true, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(17, program17, data),fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendantsString), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendantsString), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr><tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.effectiveTime)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td></tr></table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n &nbsp;\n <span class=\"pull-right\">\n <div class=\"dropdown\">\n <button class=\"btn btn-link dropdown-toggle\" type=\"button\" id=\"dropdownMenu1-details\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <i class=\"glyphicon glyphicon-export pull-right\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-icon-details\"></i>\n </button>\n <ul class=\"dropdown-menu small pull-right\" role=\"menu\" aria-labelledby=\"dropdownMenu1-details\">\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid-details\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy ConceptId</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-term-details\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid-term-details\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " |" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "|\">Copy ConceptId + term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-link-details\" class=\"clip-btn\" data-clipboard-text=\""; if (helper = helpers.link) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.link); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Copy Link to share</a></li>\n </ul>\n </div>\n </span>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(19, program19, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.edition), "se-edition", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.edition), "se-edition", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <!--<button type=\"button\" id=\"share-link-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"btn btn-link more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"-->\n <!--<form><input class='form-control' id='share-field-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' value='"; if (helper = helpers.dataContentValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.dataContentValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "?perspective=full&conceptId1=" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&edition="; if (helper = helpers.edition) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.edition); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&release="; if (helper = helpers.release) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.release); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&server="; if (helper = helpers.server) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.server); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&langRefset="; if (helper = helpers.langRefset) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.langRefset); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></form><br>Copy the concept link (e.g. CTRL-C) to save and share a reference to this concept.-->\n <!--\" data-html=\"true\"><i class=\"glyphicon glyphicon-share-alt\"></i></button>-->\n <span class=\"pull-right\">\n <div class=\"phoca-flagbox\" style=\"width:40px;height:40px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId), options))) + "\"></span>\n </div>\n </span>\n </td>\n\n </tr>\n</table>\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/children-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <tr><td draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n "; return buffer; } buffer += "<div>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th>\n <span class='i18n' data-i18n-id='i18n_children'>Children</span>\n </th>\n </tr>\n </thead>\n <tbody>\n</div>\n"; stack1 = helpers.each.call(depth0, (depth0 && depth0.childrenResult), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</tbody>\n</table>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/descriptions-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { return "\n <th>SCTID</th>\n "; } function program3(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options)); if(stack1 || stack1 === 0) { buffer += stack1; } stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth1 && depth1.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth1 && depth1.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.preferred), {hash:{},inverse:self.program(27, program27, data),fn:self.program(22, program22, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;&nbsp;&nbsp;"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth1 && depth1.options)),stack1 == null || stack1 === false ? stack1 : stack1.showIds), {hash:{},inverse:self.noop,fn:self.program(32, program32, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.preferred), {hash:{},inverse:self.program(36, program36, data),fn:self.program(34, program34, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>DescriptionId</th><th style='padding: 3px;'>Type</th><th style='padding: 3px;'>Language</th><th style='padding: 3px;'>Case Significance</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.descriptionId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.descriptionId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>" + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "</td><td style='padding: 3px;'>"; if (helper = helpers.lang) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.lang); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>" + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.ics)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.ics)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program4(depth0,data) { return " fsn-row"; } function program6(depth0,data) { return " synonym-row"; } function program8(depth0,data) { var buffer = ""; return buffer; } function program10(depth0,data) { return " danger"; } function program12(depth0,data) { return " highlightEffectiveTime"; } function program14(depth0,data) { var buffer = "", helper, options; buffer += "\n <span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_fsn", "FSN", options) : helperMissing.call(depth0, "i18n", "i18n_fsn", "FSN", options))) + "\">F</span>\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(19, program19, data),fn:self.program(17, program17, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000013009", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000013009", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program17(depth0,data) { var buffer = "", helper, options; buffer += "\n <span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_synonym", "Synonym", options) : helperMissing.call(depth0, "i18n", "i18n_synonym", "Synonym", options))) + "\">S</span>\n "; return buffer; } function program19(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000550004", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000550004", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program20(depth0,data) { var buffer = "", helper, options; buffer += "\n <span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_definition", "Definition", options) : helperMissing.call(depth0, "i18n", "i18n_definition", "Definition", options))) + "\">D</span>\n "; return buffer; } function program22(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(25, program25, data),fn:self.program(23, program23, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program23(depth0,data) { var buffer = "", helper, options; buffer += "\n &nbsp;<span class=\"glyphicon glyphicon-star-empty\" rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_preferred", "Preferred", options) : helperMissing.call(depth0, "i18n", "i18n_preferred", "Preferred", options))) + "\"></span>\n "; return buffer; } function program25(depth0,data) { var buffer = "", helper, options; buffer += "\n &nbsp;<span class=\"glyphicon glyphicon-star\" rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_preferred", "Preferred", options) : helperMissing.call(depth0, "i18n", "i18n_preferred", "Preferred", options))) + "\"></span>\n "; return buffer; } function program27(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.acceptable), {hash:{},inverse:self.program(30, program30, data),fn:self.program(28, program28, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program28(depth0,data) { var buffer = "", helper, options; buffer += "\n &nbsp;<span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_acceptable", "Acceptable", options) : helperMissing.call(depth0, "i18n", "i18n_acceptable", "Acceptable", options))) + "\">&#10004;</span></span>\n "; return buffer; } function program30(depth0,data) { return "\n &nbsp;&nbsp;&nbsp;\n "; } function program32(depth0,data) { var buffer = "", stack1; buffer += "\n <td>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.concept)),stack1 == null || stack1 === false ? stack1 : stack1.id)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n "; return buffer; } function program34(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n' data-i18n-id='i18n_preferred'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_preferred", "Preferred", options) : helperMissing.call(depth0, "i18n", "i18n_preferred", "Preferred", options))) + "</span>\n "; return buffer; } function program36(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.acceptable), {hash:{},inverse:self.program(39, program39, data),fn:self.program(37, program37, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program37(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n' data-i18n-id='i18n_acceptable'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_acceptable", "Acceptable", options) : helperMissing.call(depth0, "i18n", "i18n_acceptable", "Acceptable", options))) + "</span>\n "; return buffer; } function program39(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n' data-i18n-id='i18n_not_acceptable'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_not_acceptable", "Not acceptable", options) : helperMissing.call(depth0, "i18n", "i18n_not_acceptable", "Not acceptable", options))) + "</span>\n "; return buffer; } buffer += "<table class='table table-bordered' id = '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descriptions-panel-table'>\n <thead>\n <tr>\n <th colspan=\"2\" class=\"text-center\">" + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.longLangName), options) : helperMissing.call(depth0, "removeSemtag", (depth0 && depth0.longLangName), options))) + "</th>\n </tr>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_term'>Term</span></th>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.showIds), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <th><span class='i18n' data-i18n-id='i18n_acceptability'>Acceptability</span>&nbsp;&nbsp;"; if (helper = helpers.languageName) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.languageName); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.allDescriptions), {hash:{},inverse:self.noop,fn:self.programWithDepth(3, program3, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n</table>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/diagram.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div class=\"container\" style=\"max-width: 100%;\">\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagram-toolbar\" class=\"row\">\n <div class=\"row\" style=\"margin: 15px;\">\n <div class=\"btn-toolbar pull-right\" role=\"toolbar\">\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\" style=\"margin-right: 5px;\">\n <button type=\"button\" class=\"btn btn-default btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-stated-button-d\">Stated</button>\n <button type=\"button\" class=\"btn btn-default btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferred-button-d\">Inferred</button>\n </div>\n </div>\n </div>\n </div>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagram-body\" class=\"row\" style=\"overflow: auto; width: 1000;\">\n\n </div>\n</div>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/rels-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, self=this, helperMissing=helpers.helperMissing, functionType="function", escapeExpression=this.escapeExpression; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), "undefined", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program3(depth0,data) { return "\n <tr><td colspan='4'><span class='text-muted'>No relationships</span></td></tr>\n "; } function program5(depth0,data) { var buffer = "", stack1; buffer += "\n\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), {hash:{},inverse:self.noop,fn:self.program(6, program6, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(7, program7, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program7(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.programWithDepth(8, program8, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.characteristicType), "INFERRED_RELATIONSHIP", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.characteristicType), "INFERRED_RELATIONSHIP", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program8(depth0,data,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='inferred-rel\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n '>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(17, program17, data),fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(21, program21, data),fn:self.program(19, program19, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>TypeId</th><th style='padding: 3px;'>TargetId</th><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program9(depth0,data) { return "\n highlightEffectiveTime\n "; } function program11(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program15(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program17(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program19(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_stated'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_stated", "Stated", options) : helperMissing.call(depth0, "i18n", "i18n_stated", "Stated", options))) + "</span>\n "; return buffer; } function program21(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program22(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_inferred'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_inferred", "Inferred", options) : helperMissing.call(depth0, "i18n", "i18n_inferred", "Inferred", options))) + "</span>\n "; return buffer; } function program24(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_other'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_other", "Other", options) : helperMissing.call(depth0, "i18n", "i18n_other", "Other", options))) + "</span>\n "; return buffer; } function program26(depth0,data) { return "\n <p>No additional relationships</p>\n"; } function program28(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.additionalRels), {hash:{},inverse:self.noop,fn:self.program(29, program29, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n"; return buffer; } function program29(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(30, program30, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(33, program33, data),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(37, program37, data),fn:self.program(35, program35, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_additional", "Additional", options) : helperMissing.call(depth0, "i18n", "i18n_additional", "Additional", options))) + "</span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program31(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program33(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program35(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program37(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program39(depth0,data) { return "\n <p>No Axioms found</p>\n"; } function program41(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(42, program42, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program42(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(43, program43, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program43(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <p>Axiom - "; if (helper = helpers.axiomId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.axiomId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(44, program44, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; return buffer; } function program44(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(45, program45, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program45(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(48, program48, data),fn:self.program(46, program46, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(17, program17, data),fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>Axiom </span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program46(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program48(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program50(depth0,data) { return "\n <p>No GCI's found</p>\n"; } function program52(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(53, program53, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program53(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(54, program54, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program54(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <p>GCI - "; if (helper = helpers.axiomId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.axiomId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(55, program55, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; return buffer; } function program55(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(56, program56, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program56(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(48, program48, data),fn:self.program(46, program46, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(59, program59, data),fn:self.program(57, program57, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>GCI Axiom</span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program57(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program59(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n"; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(28, program28, data),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.additionalRels), options) : helperMissing.call(depth0, "if_undefined", (depth0 && depth0.additionalRels), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n"; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(41, program41, data),fn:self.program(39, program39, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(52, program52, data),fn:self.program(50, program50, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/expression.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<p class=\"\" style=\"margin-top: 20px;\">Pre-coordinated Expression (*)&nbsp;&nbsp;&nbsp;&nbsp;<small><i class=\"glyphicon glyphicon-export clip-btn-exp\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-pre-coordinated-expression\" data-clipboard-text=\""; if (helper = helpers.plainPreCoordinatedExpression) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.plainPreCoordinatedExpression); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></i></small></p>\n<div class=\"expression-code\" style=\"margin-top: 10px; padding: 10px;\">"; if (helper = helpers.preCoordinatedExpressionHtml) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.preCoordinatedExpressionHtml); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n<p class=\"\" style=\"margin-top: 20px;\">Expression from Stated Concept Definition (*)&nbsp;&nbsp;&nbsp;&nbsp;<small><i class=\"glyphicon glyphicon-export clip-btn-exp\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-stated-expression\" data-clipboard-text=\""; if (helper = helpers.plainStatedExpression) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.plainStatedExpression); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></i></small></p>\n<div class=\"expression-code\" style=\"margin-top: 10px; padding: 10px;\">"; if (helper = helpers.statedExpressionHtml) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedExpressionHtml); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n<p class=\"\" style=\"margin-top: 20px;\">Expression from Inferred Concept Definition (*)&nbsp;&nbsp;&nbsp;&nbsp;<small><i class=\"glyphicon glyphicon-export clip-btn-exp\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-inferred-expression\" data-clipboard-text=\""; if (helper = helpers.plainInferredExpression) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.plainInferredExpression); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></i></small></p>\n<div class=\"expression-code\" style=\"margin-top: 10px; padding: 10px;\">"; if (helper = helpers.inferredExpressionHtml) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.inferredExpressionHtml); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n<br><br>\n<div class=\"well small\">\n <p>(*) The expressions are generated according to the ABNF syntax found in the \"SNOMED CT Compositional Grammar Specification and Guide\" (<a href=\"http://snomed.org/compgrammar\" target=\"_blank\">http://snomed.org/compgrammar</a>)</p>\n <p>SNOMED CT Compositional Grammar is a lightweight syntax for the representation of SNOMED CT expressions. SNOMED CT expressions are used in Electronic Health Records (EHRs) to represent clinical meanings in a way that enables automatic interpretation. They are also carried in messages, used to define precoordinated concepts and used to represent links between SNOMED CT and other terminologies.</p>\n <p>These expressions are generated as an example from the published concept definition, a Pre-coordinated Expression is direct reference to the concept, and Post-coordinated expressions are generated from the stated or inferred relationships. In a Sufficiently Defined concept, all three will be equivalent.</p>\n</div>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/attributes.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { var buffer = ""; return buffer; } function program3(depth0,data) { return "-empty"; } function program5(depth0,data) { return "\n &nbsp;&nbsp;\n "; } function program7(depth0,data) { return "\n &equiv;\n "; } buffer += "<h4 data-droppable=\"true\" ondrop=\"dropC(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\">\n <span class=\"pull-right\">\n <div class=\"dropdown\">\n <button class=\"btn btn-link dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\" style=\"padding: 0px;\">\n <i class=\"glyphicon glyphicon-export pull-right\" style=\"color: white;\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-icon\"></i>\n </button>\n <ul class=\"dropdown-menu small\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy ConceptId</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-term\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid-term\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " |" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "|\">Copy ConceptId + term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-link\" class=\"clip-btn\" data-clipboard-text=\""; if (helper = helpers.link) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.link); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Copy Link to share</a></li>\n </ul>\n </div>\n </span>\n <span class=\"pull-right\">\n <a href=\"javascript:void(0);\" style=\"font-size: 20px; color: white; padding: 5px;\">\n <span data-conceptId=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" class=\"glyphicon glyphicon-star"; stack1 = (helper = helpers.if_fav || (depth0 && depth0.if_fav),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), options) : helperMissing.call(depth0, "if_fav", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\"></span>\n </a>\n </span>\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">\n <span class=\"badge alert-warning\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </span>\n </a>\n &nbsp;&nbsp;\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n <span class=\"pull-right\">\n <div class=\"phoca-flagbox\" style=\"width:40px;height:40px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n </span>\n</h4>\n\n<h5>SCTID: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "<br><br><div id=\"copy-content-custom\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " | " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " |</div></h5>\n\n<div id=\"home-descriptions-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></div>\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/children.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", helper, options; buffer += "\n <span data-i18n-id=\"i18n_no_children\" class=\"text-muted i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_children", "No Children", options) : helperMissing.call(depth0, "i18n", "i18n_no_children", "No Children", options))) + "</span>\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 15px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.childrenResult), {hash:{},inverse:self.noop,fn:self.programWithDepth(5, program5, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program5(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth2 && depth2.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth2 && depth2.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", (depth2 && depth2.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(16, program16, data, depth1),fn:self.programWithDepth(14, program14, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span class=\"treeLabel selectable-row\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" id=\"" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n </li>\n "; return buffer; } function program7(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafInferred), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafInferred), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program8(depth0,data) { return "minus"; } function program10(depth0,data) { return "chevron-right"; } function program12(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafStated), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafStated), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program14(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program16(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program21(depth0,data) { var buffer = "", helper, options; buffer += "\n <span data-i18n-id=\"i18n_no_children\" class=\"text-muted i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_children", "No children", options) : helperMissing.call(depth0, "i18n", "i18n_no_children", "No children", options))) + "</span>\n "; return buffer; } function program23(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(26, program26, data),fn:self.program(24, program24, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 30, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 30, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program24(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <button id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-showChildren\" class=\"btn btn-link\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " <span data-i18n-id=\"i18n_children\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_children", "children", options) : helperMissing.call(depth0, "i18n", "i18n_children", "children", options))) + "</span></button>\n "; return buffer; } function program26(depth0,data) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 15px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.childrenResult), {hash:{},inverse:self.noop,fn:self.programWithDepth(27, program27, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program27(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(28, program28, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program28(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth2 && depth2.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth2 && depth2.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", (depth2 && depth2.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(31, program31, data, depth1),fn:self.programWithDepth(29, program29, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(33, program33, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span class=\"treeLabel selectable-row\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" id=\"" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n </li>\n "; return buffer; } function program29(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program31(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program33(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } stack1 = helpers['if'].call(depth0, (depth0 && depth0.displayChildren), {hash:{},inverse:self.program(20, program20, data),fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/parents.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, self=this, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(5, program5, data, depth0),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(28, program28, data, depth0),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program3(depth0,data) { return "\n <span class='text-muted'>No parents</span>\n "; } function program5(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 2px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedParents), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program6(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li class=\"treeLabel\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n <!--<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='text-warning' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>-->\n <!--"; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</span>&nbsp;&rArr;&nbsp;-->\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' data-first=\"true\" data-ind=\"" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(18, program18, data, depth1),fn:self.programWithDepth(16, program16, data, depth1),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "hasCountryIcon", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(24, program24, data, depth2),fn:self.programWithDepth(22, program22, data, depth2),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </span>\n </a>\n </li>\n "; return buffer; } function program7(depth0,data) { var buffer = "", stack1, helper, options; buffer += "-->\n <!--" + escapeExpression((helper = helpers.substr || (depth0 && depth0.substr),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options) : helperMissing.call(depth0, "substr", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options))) + "-->\n <!--"; return buffer; } function program9(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-->\n <!--"; return buffer; } function program11(depth0,data) { return "minus"; } function program13(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "9999999999", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "9999999999", options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program14(depth0,data) { return "chevron-right"; } function program16(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program20(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program22(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program24(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program26(depth0,data) { return "\n "; } function program28(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 2px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedParentsFromAxioms), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(33, program33, data, depth0),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.inferredParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.inferredParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program31(depth0,data) { return "\n <span class='text-muted'>No parents</span>\n "; } function program33(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 2px; padding-top: 0px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.inferredParents), {hash:{},inverse:self.noop,fn:self.programWithDepth(34, program34, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program34(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li class=\"treeLabel\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n <!--<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='text-warning' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>-->\n <!--" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-->\n <!--</span>&nbsp;&rArr;&nbsp;-->\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' data-first=\"true\" data-ind=\"" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(37, program37, data, depth1),fn:self.programWithDepth(35, program35, data, depth1),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "hasCountryIcon", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(41, program41, data, depth2),fn:self.programWithDepth(39, program39, data, depth2),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </span>\n </a>\n </li>\n "; return buffer; } function program35(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program37(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program39(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program41(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(30, program30, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n\n\n\n\n\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/roles.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedRoles), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n \n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(17, program17, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(30, program30, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <!--<br>-->\n "; stack1 = (helper = helpers.eqLastGroup || (depth0 && depth0.eqLastGroup),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "eqLastGroup", (depth0 && depth0.groupId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-attribute-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span>&nbsp;&rarr;&nbsp;\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "\n </span><br>\n "; return buffer; } function program3(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n </div>\n " + escapeExpression((helper = helpers.setLastGroup || (depth0 && depth0.setLastGroup),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "setLastGroup", (depth0 && depth0.groupId), options))) + "\n " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "random", options) : helperMissing.call(depth0, "lastColor", "random", options))) + "\n <div "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.groupId), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program4(depth0,data) { var buffer = ""; return buffer; } function program6(depth0,data) { return "style=\"border: 1px solid darkgrey; border-radius: 4px; padding: 3px; background-color: white; margin: 5px;\""; } function program8(depth0,data) { var buffer = "", helper, options; buffer += "\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program10(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.attributesFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.attributesFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program15(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n text-muted' data-i18n-id='i18n_no_attributes'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_attributes", "No relationships", options) : helperMissing.call(depth0, "i18n", "i18n_no_attributes", "No relationships", options))) + "</span>\n "; return buffer; } function program17(depth0,data) { var buffer = "", stack1; buffer += "\n <div>Axiom</div>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div> \n "; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(21, program21, data),fn:self.program(19, program19, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "116680003", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "116680003", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program19(depth0,data) { return "\n "; } function program21(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <!--<br>-->\n "; stack1 = (helper = helpers.eqLastGroup || (depth0 && depth0.eqLastGroup),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "eqLastGroup", (depth0 && depth0.groupId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-attribute-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span>&nbsp;&rarr;&nbsp;\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(28, program28, data),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "\n </span><br>\n "; return buffer; } function program22(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n </div>\n " + escapeExpression((helper = helpers.setLastGroup || (depth0 && depth0.setLastGroup),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "setLastGroup", (depth0 && depth0.groupId), options))) + "\n " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "random", options) : helperMissing.call(depth0, "lastColor", "random", options))) + "\n <div "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.groupId), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program24(depth0,data) { var buffer = "", helper, options; buffer += "\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program26(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program28(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1; buffer += "\n <div>GCI</div>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; return buffer; } function program32(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.inferredRoles), {hash:{},inverse:self.noop,fn:self.program(33, program33, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(38, program38, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.inferredRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.inferredRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program33(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <!--<br>inferred-->\n "; stack1 = (helper = helpers.eqLastGroup || (depth0 && depth0.eqLastGroup),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "eqLastGroup", (depth0 && depth0.groupId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;<span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "' draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-attribute-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span>&nbsp;&rarr;&nbsp;\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(36, program36, data),fn:self.program(34, program34, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n ' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span><br>\n "; return buffer; } function program34(depth0,data) { return "\n sct-primitive-concept-compact\n "; } function program36(depth0,data) { return "\n sct-defined-concept-compact\n "; } function program38(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n text-muted' data-i18n-id='i18n_no_attributes'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_attributes", "No relationships", options) : helperMissing.call(depth0, "i18n", "i18n_no_attributes", "No relationships", options))) + "</span>\n "; return buffer; } buffer += "<div style='line-height: 100%;'>\n " + escapeExpression((helper = helpers.setLastGroup || (depth0 && depth0.setLastGroup),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.null), options) : helperMissing.call(depth0, "setLastGroup", (depth0 && depth0.null), options))) + "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</div>\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/members.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { var buffer = "", helper, options; buffer += "\n <thead>\n <tr>\n <th><span data-i18n-id=\"i18n_term\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_term", "Term", options) : helperMissing.call(depth0, "i18n", "i18n_term", "Term", options))) + "</span></th>\n <th><span data-i18n-id=\"i18n_conceptId\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_conceptId", "Concept Id", options) : helperMissing.call(depth0, "i18n", "i18n_conceptId", "Concept Id", options))) + "</span></th>\n </tr>\n </thead>\n"; return buffer; } function program3(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class=\"member-row\">\n <td data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n\n "; return buffer; } function program4(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span></button>\n </td>\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program9(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <td class=\"text-muted\" class=\"text-center\" colspan=\"2\">"; if (helper = helpers.total) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.total); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_members\" class=\"i18n\">members</span></td>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.skipTo), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.skipTo), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.items), {hash:{},inverse:self.noop,fn:self.programWithDepth(3, program3, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <tr class=\"more-row\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), "asd", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), "asd", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tr>\n</tbody>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/product.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n </tr>\n "; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program10(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n <br>\n &nbsp;&nbsp;&nbsp;<span class=\"text-muted\"><em>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.boss)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</em></span>\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.numeratorValue), {hash:{},inverse:self.noop,fn:self.program(15, program15, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.numeratorUnit), {hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.denominatorValue), {hash:{},inverse:self.noop,fn:self.program(25, program25, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.denominatorUnit), {hash:{},inverse:self.noop,fn:self.program(30, program30, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n </tr>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program15(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(18, program18, data),fn:self.program(16, program16, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program21(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program23(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program25(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(28, program28, data),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program26(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program28(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(33, program33, data),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program31(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program33(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } buffer += "<br>\n<h4>&nbsp;&nbsp;&nbsp;" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.productData)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</h4>\n<br>\n<table class='table table-bordered' id = ''>\n <thead>\n <tr><th colspan=\"2\">Dose form</th></tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.productData)),stack1 == null || stack1 === false ? stack1 : stack1.forms), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n</table>\n<br>\n<table class='table table-bordered' id = ''>\n <thead>\n <tr>\n <th>Ingredient / BoSS</th>\n <th colspan=\"2\">Strength Numerator</th>\n <th colspan=\"2\">Strength Denominator</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.productData)),stack1 == null || stack1 === false ? stack1 : stack1.ingredients), {hash:{},inverse:self.noop,fn:self.program(10, program10, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n</table>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/references.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <div style=\"margin-top: 10px;\" class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h3 style=\"font-size: 12px\" class=\"panel-title\">\n <a style=\"text-decoration: inherit;\" data-toggle=\"collapse\" data-parent=\"#references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-accordion\" href=\"#references-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">\n <span id=\"references-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-span\" class=\"references glyphicon glyphicon-"; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.length), 10, options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.length), 10, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\"></span>\n </a>&nbsp;" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0[0])),stack1 == null || stack1 === false ? stack1 : stack1.relationship)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " ("; if (helper = helpers.length) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.length); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")\n </h3>\n </div>\n <div id=\"references-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" class=\"panel-collapse collapse "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.length), 10, options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.length), 10, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"panel-body\">\n <table class=\"table table-hover table-bordered\">\n <thead>\n <tr>\n <th>Term</th>\n <th>ConceptId</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, depth0, {hash:{},inverse:self.noop,fn:self.programWithDepth(10, program10, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n </div>\n </div>\n"; return buffer; } function program2(depth0,data) { return "chevron-right"; } function program4(depth0,data) { return "chevron-down"; } function program6(depth0,data) { var buffer = ""; return buffer; } function program8(depth0,data) { return "in"; } function program10(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n <td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n </tr>\n "; return buffer; } function program11(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program13(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "-->\n <!--<tr>-->\n <!--<td>-->\n <!--<span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>-->\n <!--"; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-->\n <!--</td>-->\n <!--<td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>-->\n <!--<td>-->\n <!--"; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(16, program16, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n\n <!--"; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedRelationships), {hash:{},inverse:self.noop,fn:self.program(16, program16, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</td>-->\n <!--</tr>-->\n <!--"; return buffer; } function program14(depth0,data) { var buffer = "", helper, options; buffer += "-->\n <!--<div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">-->\n <!--<span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>-->\n <!--</div>-->\n <!--"; return buffer; } function program16(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-->\n <!--"; return buffer; } stack1 = helpers.each.call(depth0, (depth0 && depth0.groups), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n<!--<thead>-->\n <!--<tr>-->\n <!--<th>Term</th>-->\n <!--<th>ConceptId</th>-->\n <!--<th>Relationships Type</th>-->\n <!--</tr>-->\n<!--</thead>-->\n<!--<tbody>-->\n <!--"; stack1 = helpers.each.call(depth0, (depth0 && depth0.result), {hash:{},inverse:self.noop,fn:self.programWithDepth(13, program13, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n</tbody>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/refset.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLE_REFSET", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLE_REFSET", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simple", true, options) : helperMissing.call(depth0, "refset", "simple", true, options))) + "\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLEMAP", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLEMAP", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program5(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simplemap", true, options) : helperMissing.call(depth0, "refset", "simplemap", true, options))) + "\n "; return buffer; } function program7(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "ATTRIBUTE_VALUE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "ATTRIBUTE_VALUE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program8(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "attr", true, options) : helperMissing.call(depth0, "refset", "attr", true, options))) + "\n "; return buffer; } function program10(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "assoc", true, options) : helperMissing.call(depth0, "refset", "assoc", true, options))) + "\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLE_REFSET", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLE_REFSET", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>"; if (helper = helpers.otherValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.otherValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'>\n <tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\"data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program14(depth0,data) { var buffer = ""; return buffer; } function program16(depth0,data) { return "danger"; } function program18(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program22(depth0,data) { return "\n </tbody>\n "; } function program24(depth0,data) { return "\n <tr><td><span class='i18n text-muted' data-i18n-id='i18n_no_memberships'>No memberships</span></td></tr>\n </tbody>\n "; } function program26(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(27, program27, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLEMAP", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLEMAP", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program27(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(30, program30, data),fn:self.program(28, program28, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td class=\"refset-simplemap\" data-refsetId=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-conceptId=\""; if (helper = helpers.otherValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.otherValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.otherValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.otherValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program28(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program32(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(33, program33, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "ATTRIBUTE_VALUE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "ATTRIBUTE_VALUE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program33(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(36, program36, data),fn:self.program(34, program34, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program34(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program36(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program38(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(39, program39, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "ASSOCIATION", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "ASSOCIATION", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program39(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(42, program42, data),fn:self.program(40, program40, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr>\n <td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program40(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program42(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } buffer += escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simple", false, options) : helperMissing.call(depth0, "refset", "simple", false, options))) + "\n" + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simplemap", false, options) : helperMissing.call(depth0, "refset", "simplemap", false, options))) + "\n" + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "attr", false, options) : helperMissing.call(depth0, "refset", "attr", false, options))) + "\n" + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "assoc", false, options) : helperMissing.call(depth0, "refset", "assoc", false, options))) + "\n\n"; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n<div style=\"margin: 10px;\">\n <a class=\"btn btn-primary btn-sm pull-right\" href=\"https://mapping.ihtsdotools.org/#/record/conceptId/" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "/autologin?refSetId=P447562003\" target=\"_blank\" role=\"button\">Open maps for this concept</a>\n</div>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_simple_refset_memberships'>Simple Refsets Membership</span></th>\n </tr></thead>\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(12, program12, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "simple", "get", options) : helperMissing.call(depth0, "refset", "simple", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_simple_map_refset_name'>Simple Map Refset name</span></th>\n </tr></thead>\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(26, program26, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "simplemap", "get", options) : helperMissing.call(depth0, "refset", "simplemap", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_attribute_value_refset_name'>Attribute Value Refset name</span></th>\n </tr></thead>\n<tbody>\n\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(32, program32, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "attr", "get", options) : helperMissing.call(depth0, "refset", "attr", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_association_refset_name'>Association Refset name</span></th>\n </tr></thead>\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(38, program38, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "assoc", "get", options) : helperMissing.call(depth0, "refset", "assoc", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n"; return buffer; }); this["JST"]["views/developmentQueryPlugin/andCriteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { return "Conjunction"; } function program3(depth0,data) { var stack1, helper; if (helper = helpers.typeSelected) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeSelected); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } return escapeExpression(stack1); } function program5(depth0,data) { return "\n and\n "; } function program7(depth0,data) { return "\n attribute\n "; } function program9(depth0,data) { var buffer = ""; return buffer; } function program11(depth0,data) { return "style=\"display: none;\""; } function program13(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <li role=\"presentation\"><a class=\"selectTypeOpt\" data-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a></li>\n "; return buffer; } buffer += "<div class=\"addedCriteria\" data-typeSelected=\""; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.typeSelected), "false", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.typeSelected), "false", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"form-group text-center\" style=\"width: 75px;\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.typeSelected), "Conjunction", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.typeSelected), "Conjunction", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <div data-type-concept-id=\"false\" class=\"form-group typeCritCombo\" "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.typeSelected), "Refinement", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.typeSelected), "Refinement", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <div class=\"dropdown\">\n <button style=\"width: 147px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span>Select type&nbsp;</span>\n <span class=\"caret\"></span>\n </button>\n <ul style=\"max-height: 400px; overflow: auto;\" class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a class=\"selectTypeOpt\" data-id=\"*\" data-term=\"Any\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">Any</a></li>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.types), {hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n </div>\n </div>\n <div class=\"form-group\">\n <div class=\"dropdown\">\n <button style=\"width: 147px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span class=\"addSelectCriteria\">"; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOf</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOrSelfOf</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">self</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">isMemberOf</a></li>\n </ul>\n </div>\n </div>\n <div class=\"form-group\">\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control andCriteriaConcept\" placeholder=\"Drag a concept here\" readonly>\n </div>\n <div class=\"form-group\"><button type=\"button\" class=\"btn btn-link glyphicon glyphicon-remove removeCriteria\" style=\"text-decoration: none;\"></button></div>\n <div class=\"form-group\"><button type=\"button\" class=\"btn btn-link glyphicon glyphicon-plus addCriteria\" style=\"text-decoration: none;\"></button></div>\n</div>"; return buffer; }); this["JST"]["views/developmentQueryPlugin/criteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, self=this, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; function program1(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (data == null || data === false ? data : data.index), 0, options) : helperMissing.call(depth0, "if_eq", (data == null || data === false ? data : data.index), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <span class=\"constraint\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-criteria=\""; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <!--"; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;-->\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.noop,fn:self.program(15, program15, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <div style=\"display: inline-block;\" class=\"dropdown\">\n <button style=\"text-decoration: inherit; color: inherit; display: inline-block; padding: 0px;\" class=\"btn btn-link dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n "; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\">\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOf</a></li>\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOrSelfOf</a></li>\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">self</a></li>\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">isMemberOf</a></li>\n </ul>\n </div>\n <span style=\"color: forestgreen;\">"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>&nbsp;\n |\n <span style=\"color: firebrick;\">"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n |"; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = ((stack1 = (depth1 && depth1.criterias)),stack1 == null || stack1 === false ? stack1 : stack1[1])),stack1 == null || stack1 === false ? stack1 : stack1.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.noop,fn:self.programWithDepth(17, program17, data, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </span>\n "; return buffer; } function program2(depth0,data) { return "\n "; } function program4(depth0,data) { var buffer = "", stack1; buffer += "\n <br>\n <div style=\"margin-left: "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "px; display: inline-block\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; return buffer; } function program5(depth0,data) { return "68"; } function program7(depth0,data) { return "43"; } function program9(depth0,data) { var buffer = ""; return buffer; } function program11(depth0,data) { return "AND"; } function program13(depth0,data) { var buffer = "", stack1; buffer += "data-type-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-type-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\""; return buffer; } function program15(depth0,data) { var buffer = "", stack1; buffer += "\n <span style=\"color: forestgreen;\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span> |\n <span style=\"color: firebrick;\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span> | =\n "; return buffer; } function program17(depth0,data,depth2) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eqInd || (depth2 && depth2.if_eqInd),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, (data == null || data === false ? data : data.index), ((stack1 = (depth2 && depth2.criterias)),stack1 == null || stack1 === false ? stack1 : stack1.length), options) : helperMissing.call(depth0, "if_eqInd", (data == null || data === false ? data : data.index), ((stack1 = (depth2 && depth2.criterias)),stack1 == null || stack1 === false ? stack1 : stack1.length), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program18(depth0,data) { return "\n "; } function program20(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (data == null || data === false ? data : data.index), {hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program21(depth0,data) { return "\n ,\n "; } function program23(depth0,data) { return "\n :\n "; } buffer += "<li data-modifier=\""; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"list-group-item clearfix query-condition\">\n <span class=\"text-muted line-number\" style=\"font-size: 200%;\"></span>&nbsp;&nbsp;\n <span style=\"position: relative; top: -5px;\">\n <div style=\"width: 45px;display: inline-block;\">"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ":</div>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.criterias), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </span>\n <button class='pull-right btn btn-link removeLi' style=\"position: relative; top: 3px;\">\n <i class='glyphicon glyphicon-remove'></i>\n </button>\n </li>"; return buffer; }); this["JST"]["views/developmentQueryPlugin/examples.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var stack1, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <br>\n <div id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-modal-examples\" "; stack1 = (helper = helpers.if_eqInd || (depth1 && depth1.if_eqInd),options={hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (data == null || data === false ? data : data.index), ((stack1 = (depth1 && depth1.examples)),stack1 == null || stack1 === false ? stack1 : stack1.length), options) : helperMissing.call(depth0, "if_eqInd", (data == null || data === false ? data : data.index), ((stack1 = (depth1 && depth1.examples)),stack1 == null || stack1 === false ? stack1 : stack1.length), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <h4>"; if (helper = helpers.title) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.title); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</h4>\n <span data-htmlValue=\""; if (helper = helpers.htmlValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.htmlValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"pull-right btn btn-primary btn-xs loadExample\" style=\"padding: 0px; display: inline-block;\">Load instructions</span>\n <br>\n <div class=\"contentExamples\" style=\"margin: 10px;\">"; if (helper = helpers.htmlValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.htmlValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n <br>\n </div>\n"; return buffer; } function program2(depth0,data) { return "style=\"min-height: 450px;\""; } stack1 = helpers.each.call(depth0, (depth0 && depth0.examples), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } }); this["JST"]["views/developmentQueryPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data,depth1) { var buffer = "", stack1, helper; buffer += "\n <li><a contenteditable=\"false\" href=\"#" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-modal-examples\" class=\"list-group-item\">"; if (helper = helpers.title) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.title); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a></li>\n "; return buffer; } buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong>"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_terminology_content_selection", "Terminology content selections", options) : helperMissing.call(depth0, "i18n", "i18n_terminology_content_selection", "Terminology content selections", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</strong></div>\n <div class='col-md-6 text-right'>\n <!--<a class=\"btn btn-link\" href=\"help/topics/creating-queries.html\" target=\"_blank\" title=\"Help\" role=\"button\"><i class='glyphicon glyphicon-question-sign'></i></a>-->\n </div>\n </div>\n </div>\n <div class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <!--<p style=\"margin: 10px;\">Create a query, conditions are evaluated in order:</p>-->\n <div class=\"row container-fluid\" style=\"margin: 10px;\">\n <p class=\"lead col-md-6\">Enter an expression</p>\n <button type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-helpButton\" class=\"btn btn-default pull-right\" style=\"margin: 10px;\" data-toggle=\"modal\" data-target=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-queryHelpModal\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_help", "Help", options) : helperMissing.call(depth0, "i18n", "i18n_help", "Help", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <button type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-clearButton\" class=\"btn btn-default pull-right\" style=\"margin: 10px;\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_clear", "Clear", options) : helperMissing.call(depth0, "i18n", "i18n_clear", "Clear", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <!--<p><strong>This will execute against the current MAIN branch of the authoring platform. Please make sure you have logged into the authoring platform to be able to run any queries.</strong></p> -->\n </div>\n <div>\n <ul class=\"nav nav-tabs\">\n <li class=\"active\"><a href=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExpTab\" data-toggle=\"tab\"><span class=\"i18n\" data-i18n-id=\"i18n_expression\">Enter an existing expression</span></a></li>\n <!-- <li><a href=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-BuilderTab\" data-toggle=\"tab\"><span class=\"i18n\" data-i18n-id=\"i18n_builder\">Build a simple expression</span></a></li>\n-->\n </ul>\n <div class=\"tab-content\">\n <div class=\"tab-pane\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-BuilderTab\" style=\"padding: 0px;margin: 0;\">\n <div class=\"row container-fluid\" style=\"margin: 10px;\">\n <form class=\"form-inline\" role=\"form\">\n <div class=\"form-group\">\n <div class=\"dropdown\">\n <button style=\"width: 75px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modifierButton\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedModifier\">Include</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modifierButton\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"modifier-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">Include</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"modifier-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">Exclude</a></li>\n </ul>\n </div>\n </div>\n <div class=\"form-group\">\n <div class=\"dropdown\">\n <button style=\"width: 147px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedCriteria\">descendantOf</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOf</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOrSelfOf</a></li>\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">ancestorOf</a></li>-->\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">ancestorOrSelfOf</a></li>-->\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">self</a></li>\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">childrenOf</a></li>-->\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">parentsOf</a></li>-->\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">isMemberOf</a></li>\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">hasDescription</a></li>-->\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">hasRelationship</a></li>-->\n </ul>\n </div>\n </div>\n <div class=\"form-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-conceptField\">\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedConcept\" placeholder=\"Drag a concept here\" readonly>\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedType\" placeholder=\"Drag a type here\" readonly>\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedTarget\" placeholder=\"Drag a destination here\" readonly>\n <input type=\"text\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchTerm\" placeholder=\"Type search string\">\n <span class=\"dropdown\">\n <button class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-formdropdown\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedForm\">stated</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-formdropdown\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"form-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">stated</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"form-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">inferred</a></li>\n </ul>\n </span>\n </div>\n <div style=\"margin-left: 41px;\" class=\"form-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addCriteriaAnd\">\n <div class=\"dropdown\">\n <button style=\"text-decoration: none;\" class=\"btn btn-link dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\" aria-expanded=\"true\"><span data-toggle=\"tooltip\" data-placement=\"top\" title=\"More\" class=\"glyphicon glyphicon-plus\"></span></button>\n <ul class=\"dropdown-menu pull-right\" role=\"menu\">\n <li role=\"presentation\"><a class=\"addCriteria\" data-type=\"Conjunction\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">Add AND</a></li>\n <li role=\"presentation\"><a class=\"addCriteria\" data-type=\"Refinement\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">Add Refinement</a></li>\n </ul>\n </div>\n </div>\n </form>\n <form class=\"form-inline\" role=\"form\">\n <div class=\"form-group\">\n <button type=\"button\" class=\"btn btn-primary\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addCriteriaButton' style=\"margin: 10px;\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_add_condition", "Add instruction", options) : helperMissing.call(depth0, "i18n", "i18n_add_condition", "Add instruction", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <!--<button type=\"button\" class=\"btn btn-primary\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-cloudResults' style=\"margin: 10px; position: relative;\" title=\"Open Cloud Queries Processor\" data-toggle=\"modal\" data-target=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-cloudModal\"><i class='glyphicon glyphicon-cloud' style=\"position: relative; top: 3px;\"></i> <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-cloudCount\"></span></button>-->\n\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addmsg\" for=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addCriteriaButton\" class=\"small text-danger\"></span>\n </div>\n </form>\n <ul class=\"list-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-listGroup\">\n </ul>\n <div class=\"btn btn-success\" style=\"margin: 10px;\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-computeInferredButton'>"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_run_query", "Execute", options) : helperMissing.call(depth0, "i18n", "i18n_run_query", "Execute", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n <button type=\"button\" class=\"btn btn-primary pull-right\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-open-grammar' style=\"margin: 10px; position: relative;\" data-toggle=\"modal\" data-target=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammarModal\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_constraint_grammar", "Constraint Grammar", options) : helperMissing.call(depth0, "i18n", "i18n_constraint_grammar", "Constraint Grammar", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <br>\n <br>\n </div>\n </div>\n <div class=\"tab-pane active\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExpTab\" style=\"padding: 15px;margin: 0;\">\n <textarea rows=\"5\" class=\"form-control\" placeholder=\"Expression...\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExpText\"></textarea>\n <div class=\"btn btn-success\" style=\"margin: 10px;\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-computeInferredButton2'>"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_run_query", "Execute", options) : helperMissing.call(depth0, "i18n", "i18n_run_query", "Execute", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n <div class=\"btn btn-success\" style=\"display: none; margin: 10px;\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-computeOntoserver2'>Run on Ontoserver</div>\n <br>\n </div>\n </form>\n <!-- <ul class=\"list-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-listGroup\">\n </ul>\n "; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_results", "Results", options) : helperMissing.call(depth0, "i18n", "i18n_results", "Results", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ": <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultInfo\" class=\"text-muted small\"></span>\n-->\n <div class=\"row container-fluid\" style=\"margin: 10px;\">\n <p class=\"lead\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_results", "Results", options) : helperMissing.call(depth0, "i18n", "i18n_results", "Results", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ": <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultInfo\"></p></span>\n </div>\n\n <div class=\"row container-fluid\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-output\" style=\"margin: 10px;\">\n <table class=\"table table-bordered\">\n <thead>\n <tr>\n <th>Concept</th>\n <th>Id</th>\n </tr>\n </thead>\n <tbody id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-outputBody\"></tbody>\n <tfoot>\n <tr>\n <td colspan=\"2\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-footer\" class=\"text-center text-muted small\"></td>\n </tr>\n </tfoot>\n </table>\n <table id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-output2\" style=\"display: none\">\n <thead>\n <tr>\n <th>Concept</th>\n <th>Id</th>\n </tr>\n </thead>\n <tbody id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-outputBody2\">\n </tbody>\n </table>\n\n </div>\n </div>\n <br><br><br><br><br><br><br><br><br><br><br><br><br><br>\n </div>\n </div>\n <!-- Modals -->\n <div class=\"modal fade\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExamplesModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-myCloudModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg\" style=\"width: 80%;\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n <h4 class=\"modal-title\">Terminology content selections examples</h4>\n </div>\n <div class=\"modal-body\" style=\"max-height: 450px; overflow: auto;\">\n <div class=\"row\">\n <div class=\"col-md-4\">\n <div class=\"list-group navbar\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-sidebar\">\n <ul id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mynav\" data-spy=\"affix\" data-offset-top=\"280\" class=\"nav\" style=\"position: fixed; width: 30%;\">\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.examples), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n </div>\n </div>\n <div class=\"col-md-8\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mycontentExamples\">\n\n </div>\n </div>\n </div>\n <div class=\"modal-footer\">\n <button id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExamplesModal-close\" type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"modal fade\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-queryHelpModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-myCloudModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n <h4 class=\"modal-title\">Terminology content selections help</h4>\n </div>\n <div class=\"modal-body\" style=\"max-height: 450px; overflow: auto;\">\n <h2>SNOMED CT Expression Constraint Language</h2>\n <p>This tool implements the full set of ECL v1.3 functions from the \"SNOMED CT Expression Constraint Language Specification and Guide\" (<a href=\"http://snomed.org/expressionconstraint\" target=\"_blank\">http://snomed.org/expressionconstraint)</a>. </p>\n <p>The goal of this tool is to enable the creation of a terminology constraint for the selection of content in SNOMED CT, with a user friendly UI designed to support the most common real world use cases for content selection, like the creation\n of reference sets to support implementation.</p>\n <p class=\"lead\">Reference</p>\n <table class=\"c0\">\n <tbody>\n <tr class=\"c15\">\n <td class=\"c18 c24\" colspan=\"2\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">ECL Operator</span></p>\n </td>\n <td class=\"c13 c18\" colspan=\"1\" rowspan=\"2\">\n <p class=\"c3\"><span class=\"c2\">Summary</span></p>\n </td>\n <td class=\"c6 c18\" colspan=\"1\" rowspan=\"2\">\n <p class=\"c3\"><span class=\"c2\">Example</span></p>\n </td>\n </tr>\n <tr class=\"c15\">\n <td class=\"c7\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">Symbol</span></p>\n </td>\n <td class=\"c10\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">Name</span></p>\n </td>\n </tr>\n <tr class=\"c16\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&lt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Descendant of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all subtypes of the given concept</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 404684003 |Clinical finding|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&lt;&lt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Descendant or self of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all subtypes of the given concept plus the concept itself</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c23\">&lt;&lt; </span><span class=\"c20\">73211009 |Diabetes mellitus|</span></p>\n </td>\n </tr>\n <tr class=\"c16\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&gt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Ancestor of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all supertypes of the given concept</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&gt; 40541001 |Acute pulmonary edema|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&gt;&gt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Ancestor or self of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all supertypes of the given concept plus the concept itself</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&gt;&gt; 40541001 |Acute pulmonary edema|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&lt;!</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Child of</span></p> \n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all children of the given concept</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">! 195967001 |Asthma|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">^</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Member of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of referenced components in the given reference set</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">^ 733990004 |Nursing activities reference set|</span></p>\n </td>\n </tr>\n <tr class=\"c16\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">*</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Any</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Any concept in the given SNOMED CT edition</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">*</span></p>\n </td>\n </tr>\n <tr class=\"c21\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">:</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Refinement</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Only those concepts whose defining relationships match the given attribute value pairs</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 404684003 |clinical finding|: 116676008 |associated morphology| = *</span></p>\n </td>\n </tr>\n <tr class=\"c19\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">AND</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Conjunction</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Only those concepts in both sets</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 19829001 |disorder of lung| AND &lt; 301867009 |edema of trunk|</span></p>\n </td>\n </tr>\n <tr class=\"c19\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">OR</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Disjunction</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Any concept that belongs to either set</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 19829001 |disorder of lung| OR &lt; 301867009 |edema of trunk|</span></p>\n </td>\n </tr>\n <tr class=\"c19\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">MINUS</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Exclusion</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Concepts in the first set that do not belong to the second set</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 19829001 |disorder of lung| MINUS &lt; 301867009 |edema of trunk|</span></p>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n\n\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"modal fade\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammarModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"constraintGrammarModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg\" style=\"max-height: 450px;\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n <h4 class=\"modal-title\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammarModalLabel\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_constraint_grammar", "Constraint Grammar", options) : helperMissing.call(depth0, "i18n", "i18n_constraint_grammar", "Constraint Grammar", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</h4>\n </div>\n <div class=\"modal-body\" style=\"max-height: 450px; overflow: auto;\">\n <div class=\"row\">\n <div class=\"expression-code col-md-11\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammar\">\n\n </div>\n <div class=\"col-md-1\">\n <small><i class=\"glyphicon glyphicon-export pull-right\" style=\"font-size: 14px;cursor: pointer;\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copyConstraint\"></i></small>\n </div>\n </div>\n </div>\n <div class=\"modal-footer\">\n <div class=\"btn-group pull-left\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-full-syntax-button\">Full</button>\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-brief-syntax-button\">Brief</button>\n </div>\n &nbsp;&nbsp;\n <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n"; return buffer; }); this["JST"]["views/developmentQueryPlugin/relsCriteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<li data-modifier=\""; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-criteria=\""; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-type-id=\""; if (helper = helpers.typeId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-type-term=\""; if (helper = helpers.typeTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-target-term=\""; if (helper = helpers.targetTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.targetTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-target-id=\""; if (helper = helpers.targetId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.targetId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-form=\""; if (helper = helpers.form) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.form); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"list-group-item clearfix query-condition\">\n <span class=\"text-muted line-number\" style=\"font-size: 200%;\"></span>&nbsp;&nbsp;\n <span style=\"position: relative; top: -5px;\">\n "; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ", "; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;\n <span style=\"color: forestgreen;\">"; if (helper = helpers.typeId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>&nbsp;\n |\n <span style=\"color: firebrick;\">" + escapeExpression((helper = helpers.isEmptyString || (depth0 && depth0.isEmptyString),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.typeTerm), "Any", options) : helperMissing.call(depth0, "isEmptyString", (depth0 && depth0.typeTerm), "Any", options))) + "</span>\n |\n &nbsp;->&nbsp;\n <span style=\"color: forestgreen;\">"; if (helper = helpers.targetId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.targetId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>&nbsp;\n |\n <span style=\"color: firebrick;\">" + escapeExpression((helper = helpers.isEmptyString || (depth0 && depth0.isEmptyString),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.targetTerm), "Any", options) : helperMissing.call(depth0, "isEmptyString", (depth0 && depth0.targetTerm), "Any", options))) + "</span>\n |&nbsp;&nbsp;"; if (helper = helpers.form) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.form); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </span>\n <button class='pull-right btn btn-link removeLi' style=\"position: relative; top: 3px;\">\n <i class='glyphicon glyphicon-remove'></i>\n </button>\n </li>"; return buffer; }); this["JST"]["views/developmentQueryPlugin/searchCriteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<li data-modifier=\""; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-criteria=\""; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-search-term=\""; if (helper = helpers.searchTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.searchTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"list-group-item clearfix query-condition\">\n <span class=\"text-muted line-number\" style=\"font-size: 200%;\"></span>&nbsp;&nbsp;\n <span style=\"position: relative; top: -5px;\">\n "; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ", "; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;\n <span style=\"color: firebrick;\">"; if (helper = helpers.searchTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.searchTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </span>\n <button class='pull-right btn btn-link removeLi' style=\"position: relative; top: 3px;\">\n <i class='glyphicon glyphicon-remove'></i>\n </button>\n</li>"; return buffer; }); this["JST"]["views/favorites/body.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <tr>\n <td>"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n </tr>\n "; return buffer; } function program3(depth0,data) { return "\n <tr>\n <td>\n <span class=\"text-muted\"> No favorites</span>\n </td>\n </tr>\n "; } function program5(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.concepts), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n <a class=\"fav-item\" href=\"javascript:void(0);\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style=\"color: inherit; text-decoration: inherit;\">\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </a>\n </td>\n <td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n <a href=\"javascript:void(0);\" style=\"text-decoration: inherit;\">\n <span data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class=\"pull-right glyphicon glyphicon-remove-circle\"></span>\n </a>\n </td>\n </tr>\n "; return buffer; } function program7(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } buffer += "<div style=\"margin-top: 10px\" class=\"panel panel-default\">\n <div class=\"panel-body\">\n <table id=\"tableFavs\" style=\"display: none;\">\n <thead>\n <tr>\n <td>Term</td>\n <td>Concept ID</td>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.concepts), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n <table id=\"\" class=\"table table-hover table-bordered\">\n <tbody>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.concepts)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.concepts)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n</div>\n"; return buffer; }); this["JST"]["views/favorites/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_favorites'>Favorites</span></strong></div>\n <!--<div class='col-md-6 text-right'>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resetButton' class='btn btn-link' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-repeat'></i></button>-->\n <!--&lt;!&ndash;<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>&ndash;&gt;-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>-->\n <!--</div>-->\n </div>\n </div>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n </div>\n</div>\n<!--<div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>-->\n <!--<div class='modal-dialog'>-->\n <!--<div class='modal-content'>-->\n <!--<div class='modal-header'>-->\n <!--<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>-->\n <!--<h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>-->\n <!--</div>-->\n <!--<div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>-->\n <!--<p></p>-->\n <!--</div>-->\n <!--<div class='modal-footer'>-->\n <!--<button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>-->\n <!--</div>-->\n <!--</div>-->\n <!--</div>-->\n<!--</div>-->"; return buffer; }); this["JST"]["views/refsetPlugin/body.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { return "\n <tr>\n <td colspan=\"3\">\n <span class=\"text-muted\"> No refsets</span>\n </td>\n </tr>\n "; } function program3(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.refsets), {hash:{},inverse:self.noop,fn:self.programWithDepth(4, program4, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program4(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>"; if (helper = helpers.type) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.type); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <a class=\"refset-item\" href=\"javascript:void(0);\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style=\"color: inherit; text-decoration: inherit;\">\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </a>\n </td>\n <td>\n "; if (helper = helpers.count) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.count); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n "; return buffer; } function program5(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } buffer += "<div style=\"margin-top: 10px\" class=\"panel panel-default\">\n <div class=\"panel-body\">\n <div class=\"row container-fluid\" style=\"max-height: 260px; overflow-y: scroll; margin: 10px;\">\n <table class=\"table table-hover table-bordered\">\n <thead>\n <tr>\n <th>Type</th>\n <th>Refset</th>\n <th>Members count</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refsets)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refsets)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n <div class=\"row container-fluid\">\n <table id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable\" class=\"table table-hover table-bordered\">\n\n </table>\n </div>\n </div>\n</div>"; return buffer; }); this["JST"]["views/refsetPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_refsets'>Refsets</span></strong></div>\n </div>\n </div>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n </div>\n</div>"; return buffer; }); this["JST"]["views/refsetPlugin/members.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <thead>\n <tr>\n <th colspan=\"2\">Members of "; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " (<span>" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>)</th>\n </tr>\n <tr>\n <th><span data-i18n-id=\"i18n_term\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_term", "Term", options) : helperMissing.call(depth0, "i18n", "i18n_term", "Term", options))) + "</span></th>\n <th><span data-i18n-id=\"i18n_conceptId\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_conceptId", "Concept Id", options) : helperMissing.call(depth0, "i18n", "i18n_conceptId", "Concept Id", options))) + "</span></th>\n </tr>\n </thead>\n"; return buffer; } function program3(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class=\"member-concept-row\">\n <td>\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n </tr>\n "; return buffer; } function program4(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span></button>\n </td>\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program9(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <td class=\"text-muted\" class=\"text-center\" colspan=\"2\">"; if (helper = helpers.total) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.total); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_members\" class=\"i18n\">members</span></td>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.skipTo), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.skipTo), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.items), {hash:{},inverse:self.noop,fn:self.programWithDepth(3, program3, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <tr class=\"more-row\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), "asd", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), "asd", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tr>\n</tbody>"; return buffer; }); this["JST"]["views/searchPlugin/aux.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<div style='margin: 5px; height:95%;' class='panel panel-default'>\n <div class='panel-heading'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 15px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-8' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_search'>Search</span></span></strong></div>\n <div class='col-md-4 text-right'>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div class='panel-body' style='height:86%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <div style=\"display: inline;width: 34%;height: 100%; float: left; border: 1px solid lightgray; border-radius: 4px; padding: 5px; \">\n <h4><span>Options</span></h4>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchConfigBar' style='margin-bottom: 10px;'>\n <div style=\"margin-top: 5px\" class=\"btn-group\">\n <button style=\"white-space: normal;\" type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\">\n <span class='i18n' data-i18n-id='i18n_status'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_status", "Status", options) : helperMissing.call(depth0, "i18n", "i18n_status", "Status", options))) + "</span>: <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchStatus\"></span>&nbsp;<span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\">\n <li>\n <a href=\"#\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeOnlyButton' data-i18n-id='i18n_active_only'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_active_only", "Active components only", options) : helperMissing.call(depth0, "i18n", "i18n_active_only", "Active components only", options))) + "</a>\n </li>\n <li>\n <a href=\"#\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeInactiveButton' data-i18n-id='i18n_active_and_inactive'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_active_and_inactive", "Active and inactive components", options) : helperMissing.call(depth0, "i18n", "i18n_active_and_inactive", "Active and inactive components", options))) + "</a>\n </li>\n <li>\n <a href=\"#\"id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inactiveOnlyButton' data-i18n-id='i18n_inactive_only'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_inactive_only", "Inactive components only", options) : helperMissing.call(depth0, "i18n", "i18n_inactive_only", "Inactive components only", options))) + "</a>\n </li>\n </ul>\n </div>\n <div style=\"margin-top: 5px; \" class=\"checkbox\">\n <label>\n <input id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-groupConcept\" type=\"checkbox\"><span class='i18n' data-i18n-id='i18n_group_by_concept'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group_by_concept", "Group by concept", options) : helperMissing.call(depth0, "i18n", "i18n_group_by_concept", "Group by concept", options))) + "</span>\n </label>\n </div>\n </div>\n </div>\n <div style=\"display: inline; width: 66%; float: right; padding: 5px;\">\n <form>\n <div class=\"form-group\" style=\"margin-bottom: 2px;\">\n <label for=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\">\n <span class=\"i18n\" data-i18n-id=\"i18n_type_3_chars\">Type at least 3 characters</span> <i class=\"glyphicon glyphicon-remove text-danger\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-typeIcon\"></i> <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchExample\"></span></label>\n <br><div class=\"btn-group\" style=\"width: 100%;\"><input data-droppable=\"true\" ondrop=\"dropS(event);\" ondragover=\"removeHighlight();\" ondragstart=\"allowDrop(event);\" type=\"search\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\" placeholder=\"Search...\" autocomplete=\"off\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-clearButton\" class=\"searchclear glyphicon glyphicon-remove-circle\"></span></div>\n </div>\n </form>\n <div class='panel panel-default' style='height:70%;overflow:auto;margin-bottom: 15px;min-height: 300px;' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsScrollPane'>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBar\"></div>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFilters\"></div>\n <table class='table table-bordered'>\n <tbody id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable'>\n </tbody>\n </table>\n </div>\n <div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>\n"; return buffer; }); this["JST"]["views/searchPlugin/body/0.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data,depth1) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='resultRow selectable-row "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.danger), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td class='col-md-7'>\n <div class='result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(6, program6, data, depth1),fn:self.programWithDepth(4, program4, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href='javascript:void(0);' style='color: inherit;text-decoration: inherit;' draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a>\n </div>\n </td>\n <td class='text-muted small-text col-md-5 result-item' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n " + escapeExpression(((stack1 = ((stack1 = (depth1 && depth1.result)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n </tr>\n"; return buffer; } function program2(depth0,data) { return "danger"; } function program4(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program6(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:20px;height:20px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program10(depth0,data) { var buffer = "", helper, options; buffer += "\n <tr><td class='text-muted'><span data-i18n-id=\"i18n_no_results\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_results", "No results", options) : helperMissing.call(depth0, "i18n", "i18n_no_results", "No results", options))) + "</span></td></tr>\n"; return buffer; } stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.descriptions), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.descriptions)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.descriptions)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/body/1.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data,depth1) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, self=this, helperMissing=helpers.helperMissing, functionType="function", escapeExpression=this.escapeExpression; function program1(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='resultRow selectable-row"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.active), false, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.active), false, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td class='col-md-7'>\n <div class='result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(8, program8, data, depth0),fn:self.programWithDepth(6, program6, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href='javascript:void(0);' style='color: inherit;text-decoration: inherit;' draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a>\n </div>\n </td>\n <td class='text-muted small-text col-md-5 result-item' data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; if (helper = helpers.fsn) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.fsn); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n"; return buffer; } function program2(depth0,data) { return "danger"; } function program4(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.concept)),stack1 == null || stack1 === false ? stack1 : stack1.active), false, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.concept)),stack1 == null || stack1 === false ? stack1 : stack1.active), false, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program6(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(11, program11, data, depth1),fn:self.programWithDepth(9, program9, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "900000000000074008", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "900000000000074008", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program9(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program11(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program13(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:20px;height:20px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/body/bar.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class='text-muted'>" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " matches found in "; if (helper = helpers.elapsed) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.elapsed); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " seconds.</span>\n"; return buffer; } function program3(depth0,data) { return "-->\n<!--"; } function program5(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--&nbsp;&nbsp;<span class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-semtag'>&times;</a></span>&nbsp;&nbsp;-->\n<!--"; return buffer; } function program7(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--&nbsp;&nbsp;<span class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-lang'>&times;</a></span>&nbsp;&nbsp;-->\n<!--"; return buffer; } function program9(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--&nbsp;&nbsp;<span class='label label-danger'>"; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), {hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " &nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-module'>&times;</a></span>&nbsp;&nbsp;-->\n<!--"; return buffer; } function program10(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program12(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program14(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--<li><a class='lang-link' href='javascript:void(0);' data-lang='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " (" + escapeExpression((typeof depth0 === functionType ? depth0.apply(depth0) : depth0)) + ")</a></li>-->\n <!--"; return buffer; } function program16(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--<li><a class='semtag-link' href='javascript:void(0);' data-semtag='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " (" + escapeExpression((typeof depth0 === functionType ? depth0.apply(depth0) : depth0)) + ")</a></li>-->\n <!--"; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper, options; buffer += "-->\n <!--<li><a class='module-link' href='javascript:void(0);' data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-module='"; if (helper = helpers.value) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.value); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.term), {hash:{},inverse:self.program(21, program21, data),fn:self.program(19, program19, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " ("; if (helper = helpers.cant) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.cant); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")-->\n <!--"; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(23, program23, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.value), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.value), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</a></li>-->\n <!--"; return buffer; } function program19(depth0,data) { var stack1, helper; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } return escapeExpression(stack1); } function program21(depth0,data) { var stack1, helper; if (helper = helpers.value) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.value); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } return escapeExpression(stack1); } function program23(depth0,data) { var buffer = "", helper, options; buffer += "-->\n <!--<div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">-->\n <!--<span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.value), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.value), options))) + "\"></span>-->\n <!--</div>-->\n <!--"; return buffer; } stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n<!--<span class='pull right'>-->\n<!--<a class='btm btn-xs' style='margin: 3px; color: #777; background-color: #fff; border: 1px #ccc solid; margin-left: 25px;' data-toggle='collapse' href='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFiltersPanel'>-->\n <!--<span class='i18n' data-i18n-id='i18n_filters'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters", "Filters", options) : helperMissing.call(depth0, "i18n", "i18n_filters", "Filters", options))) + "</span>-->\n<!--</a>-->\n<!--"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n<!--"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n<!--"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n<!--</span>-->\n<!--<div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFiltersPanel' class='panel-collapse collapse'>-->\n <!--<div class='tree'>-->\n <!--<ul>-->\n <!--<li><a><span data-i18n-id=\"i18n_filters_language\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters_language", "Filter results by Language", options) : helperMissing.call(depth0, "i18n", "i18n_filters_language", "Filter results by Language", options))) + "</span></a>-->\n <!--<ul>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.filters)),stack1 == null || stack1 === false ? stack1 : stack1.lang), {hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</ul>-->\n <!--</li>-->\n <!--</ul>-->\n <!--<ul>-->\n <!--<li><a><span data-i18n-id=\"i18n_filters_semtag\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters_semtag", "Filter results by Semantic Tag", options) : helperMissing.call(depth0, "i18n", "i18n_filters_semtag", "Filter results by Semantic Tag", options))) + "</span></a>-->\n <!--<ul>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.filters)),stack1 == null || stack1 === false ? stack1 : stack1.semTag), {hash:{},inverse:self.noop,fn:self.program(16, program16, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</ul>-->\n <!--</li>-->\n <!--</ul>-->\n <!--<ul>-->\n <!--<li><a><span data-i18n-id=\"i18n_filters_module\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters_module", "Filter results by Module", options) : helperMissing.call(depth0, "i18n", "i18n_filters_module", "Filter results by Module", options))) + "</span></a>-->\n <!--<ul>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.filters)),stack1 == null || stack1 === false ? stack1 : stack1.module), {hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</ul>-->\n <!--</li>-->\n <!--</ul>-->\n <!--</div>-->\n<!--</div>-->"; return buffer; }); this["JST"]["views/searchPlugin/body/bar2.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { return "\n"; } function program3(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moduleResumed\" style=\"font-size: 12px;white-space: normal\" class='label label-danger' data-name=\""; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), {hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">"; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), {hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " &nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-module'>&times;</a></span>\n </h3>\n"; return buffer; } function program4(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program6(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program8(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), options))); } function program10(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), options))); } function program12(depth0,data) { var buffer = "", stack1; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span style=\"font-size: 12px; margin-top: 5px;\" class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-lang'>&times;</a></span>\n </h3>\n"; return buffer; } function program14(depth0,data) { var buffer = "", stack1; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span style=\"font-size: 12px; margin-top: 5px;\" class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-semtag'>&times;</a></span>\n </h3>\n"; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-refsetResumed\" style=\"font-size: 12px; margin-top: 5px;\" class='label label-danger' data-name=\""; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), {hash:{},inverse:self.program(19, program19, data),fn:self.program(17, program17, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">"; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), {hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " &nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-refset'>&times;</a></span>\n </h3>\n"; return buffer; } function program17(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program19(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program21(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), options))); } function program23(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), options))); } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(1, program1, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/body/default.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gre || (depth0 && depth0.if_gre),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, "0", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches)),stack1 == null || stack1 === false ? stack1 : stack1.length), options) : helperMissing.call(depth0, "if_gre", "0", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches)),stack1 == null || stack1 === false ? stack1 : stack1.length), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-muted'><span data-i18n-id=\"i18n_no_results\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_results", "No results", options) : helperMissing.call(depth0, "i18n", "i18n_no_results", "No results", options))) + "</span></td></tr>\n "; stack1 = (helper = helpers.hasFilters || (depth0 && depth0.hasFilters),options={hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.options), options) : helperMissing.call(depth0, "hasFilters", (depth0 && depth0.options), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program3(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-center'><span data-i18n-id=\"i18n_remove_filters\" class=\"i18n\">\n " + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options) : helperMissing.call(depth0, "i18n", "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options))) + "</span><br>\n <button class=\"btn btn-danger btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-remove-all-filters\"><span data-i18n-id=\"i18n_remove_filters_button\" class=\"i18n\">Remove all filters</span></button>\n </td></tr> "; return buffer; } function program5(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(22, program22, data),fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), 0, options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.remaining), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='resultRow selectable-row"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.active), false, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.active), false, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td class='col-md-6'>\n <div class='result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(13, program13, data, depth0),fn:self.programWithDepth(11, program11, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href='javascript:void(0);' style='color: inherit;text-decoration: inherit;' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a>\n </div>\n </td>\n <td class='text-muted small-text col-md-6 result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.fsn) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.fsn); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n "; return buffer; } function program7(depth0,data) { return " danger"; } function program9(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptActive), false, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.conceptActive), false, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program11(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program13(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(16, program16, data, depth1),fn:self.programWithDepth(14, program14, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "900000000000074008", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "900000000000074008", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program14(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program16(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:20px;height:20px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='more-row'><td colspan='2' class='text-center'><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-more'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining_server\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining_server", "remaining on server", options) : helperMissing.call(depth0, "i18n", "i18n_remaining_server", "remaining on server", options))) + "</span>)</button></td></tr>\n "; return buffer; } function program22(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='more-row'><td colspan='2' class='text-center text-muted'><span data-i18n-id=\"i18n_all_res\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_all_res", "All", options) : helperMissing.call(depth0, "i18n", "i18n_all_res", "All", options))) + "</span> " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " <span data-i18n-id=\"i18n_results_displayed\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_results_displayed", "results are displayed", options) : helperMissing.call(depth0, "i18n", "i18n_results_displayed", "results are displayed", options))) + "</span></td></tr>\n "; return buffer; } function program24(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-muted'><span data-i18n-id=\"i18n_no_results\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_results", "No results", options) : helperMissing.call(depth0, "i18n", "i18n_no_results", "No results", options))) + "</span></td></tr>\n "; stack1 = (helper = helpers.hasFilters || (depth0 && depth0.hasFilters),options={hash:{},inverse:self.noop,fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.options), options) : helperMissing.call(depth0, "hasFilters", (depth0 && depth0.options), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program25(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-center'><span data-i18n-id=\"i18n_remove_filters\" class=\"i18n\">\n " + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options) : helperMissing.call(depth0, "i18n", "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options))) + "</span><br>\n <button class=\"btn btn-danger btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-remove-all-filters\"><span data-i18n-id=\"i18n_remove_filters_button\" class=\"i18n\">Remove all filters</span></button>\n </td></tr>\n "; return buffer; } stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches), {hash:{},inverse:self.program(24, program24, data),fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='margin: 5px; height:95%;' class='panel panel-default'>\n <div class='panel-heading'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 15px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-8' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_search'>Search</span></span></strong></div>\n <div class='col-md-4 text-right'>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div class='panel-body' style='height:86%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <form>\n <div class=\"form-group\" style=\"margin-bottom: 2px;\">\n <label for=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\">\n <span class=\"i18n\" data-i18n-id=\"i18n_type_3_chars\">Type at least 3 characters</span> <i class=\"glyphicon glyphicon-remove text-danger\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-typeIcon\"></i> <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchExample\"></span></label>\n <br><div class=\"btn-group\" style=\"width: 100%;\"><input data-droppable=\"true\" ondrop=\"dropS(event);\" ondragover=\"removeHighlight();\" ondragstart=\"allowDrop(event);\" type=\"search\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\" placeholder=\"Search...\" autocomplete=\"off\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-clearButton\" class=\"searchclear glyphicon glyphicon-remove-circle\"></span></div>\n </div>\n </form>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchConfigBar' style='margin-bottom: 10px;'><nav class='navbar navbar-default' role='navigation' style='min-height: 28px;border-radius: 0px;border-bottom: 1px lightgray solid;'>\n <ul class='nav navbar-nav navbar-left'>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-navSearchModeLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-fullTextButton'><span class='i18n' data-i18n-id='i18n_full_text_search_mode'>Full text search mode</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-partialMatchingButton'><span class='i18n' data-i18n-id='i18n_partial_match_search_mode'>Partial matching search mode</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-regexButton'><span class='i18n' data-i18n-id='i18n_regex_search_mode'>Regular Expressions search mode</span></button></li>\n </ul>\n </li>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-navLanguageLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-danishLangButton'><span class='i18n' data-i18n-id='i18n_danish_stemmer'>Danish language stemmer</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-englishLangButton'><span class='i18n' data-i18n-id='i18n_english_stemmer'>English language stemmer</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-spanishLangButton'><span class='i18n' data-i18n-id='i18n_spanish_stemmer'>Spanish language stemmer</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-swedishLangButton'><span class='i18n' data-i18n-id='i18n_swedish_stemmer'>Swedish language stemmer</span></button></li>\n </ul>\n </li>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-navStatusFilterLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeOnlyButton'><span class='i18n' data-i18n-id='i18n_active_only'>Active components only</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeInactiveButton'><span class='i18n' data-i18n-id='i18n_active_and_inactive'>Active and inactive components</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inactiveOnlyButton'><span class='i18n' data-i18n-id='i18n_inactive_only'>Inactive components only</span></button></li>\n </ul>\n </li>\n </ul>\n </nav></div>\n <div class='panel panel-default' style='height:70%;overflow:auto;margin-bottom: 15px;min-height: 300px;' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsScrollPane'>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBar\"></div>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFilters\"></div>\n <table class='table table-bordered'>\n <tbody id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable'>\n </tbody>\n </table>\n </div>\n <div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>\n "; return buffer; }); this["JST"]["views/taxonomyPlugin/body/children.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, self=this, helperMissing=helpers.helperMissing, functionType="function", escapeExpression=this.escapeExpression; function program1(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(2, program2, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program2(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " data-statedDescendants='"; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'>\n <i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth2 && depth2.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, (depth2 && depth2.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", (depth2 && depth2.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i>\n </button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(12, program12, data, depth1),fn:self.programWithDepth(10, program10, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span class=\"treeLabel selectable-row\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-statedDescendants=\""; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" id=\"" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n " + escapeExpression((helper = helpers.push || (depth0 && depth0.push),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptId), options) : helperMissing.call(depth0, "push", (depth0 && depth0.conceptId), options))) + "\n </li>\n "; return buffer; } function program3(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafInferred), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafInferred), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program4(depth0,data) { return "minus"; } function program6(depth0,data) { return "chevron-right"; } function program8(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafStated), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafStated), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program10(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program12(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program14(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } buffer += "<ul style='list-style-type: none; padding-left: 15px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.result), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</ul>\n"; return buffer; }); this["JST"]["views/taxonomyPlugin/body/parents.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-statedDescendants='"; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'>\n <i class='glyphicon glyphicon-chevron-"; stack1 = (helper = helpers.if_def || (depth0 && depth0.if_def),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptId), options) : helperMissing.call(depth0, "if_def", (depth0 && depth0.conceptId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i>\n </button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-statedDescendants=\""; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"treeLabel selectable-row\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n "; return buffer; } function program2(depth0,data) { return "down"; } function program4(depth0,data) { return "up"; } function program6(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program10(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:33px;height:33px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program12(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.slice || (depth0 && depth0.slice),options={hash:{},data:data},helper ? helper.call(depth0, 0, -5, options) : helperMissing.call(depth0, "slice", 0, -5, options))) + "\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:33px;height:33px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program20(depth0,data) { return "\n </li>\n "; } buffer += "<div style='height:100%;margin-bottom: 15px;'>\n <ul style='list-style-type: none; padding-left: 5px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.parents), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.noop,fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <ul style='list-style-type: none; padding-left: 15px;'>\n <li data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-statedDescendants='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendants)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-chevron-right treeButton' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "hasCountryIcon", ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-statedDescendants=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendants)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" class=\"treeLabel selectable-row\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-treenode-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n </a>\n </li>\n </ul>\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n</div>"; return buffer; }); this["JST"]["views/taxonomyPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div ondrop=\"dropT(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 15px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_taxonomy'>Taxonomy</span></strong></div>\n <div class='col-md-6 text-right'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resetButton' class='btn btn-link' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-repeat'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-taxonomyConfigBar' style='margin-bottom: 10px;'><nav class='navbar navbar-default' role='navigation' style='min-height: 28px;border-radius: 0px;border-bottom: 1px lightgray solid;'>\n <ul class='nav navbar-nav navbar-left'>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-txViewLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferredViewButton'><span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-statedViewButton'><span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span></button></li>\n </ul>\n </li>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-txViewLabel2'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descendantsCountTrue'><span class='i18n' data-i18n-id='i18n_on'>On</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descendantsCountFalse'><span class='i18n' data-i18n-id='i18n_off'>Off</span></button></li>\n </ul>\n </li>\n </ul>\n </nav></div>\n <div ondrop=\"dropT(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n </div>\n</div>\n<div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n</div>"; return buffer; }); this["JST"]["views/taxonomyPlugin/options.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data,depth1) { var buffer = "", stack1, helper; buffer += "\n <tr>\n <td>"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <div class=\"checkbox\">\n <label>\n <input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscribeTo-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscribed), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> <span class=\"i18n\"></span>\n </label>\n </div>\n </td>\n <td>\n <div class=\"checkbox\">\n <label>\n <input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscriptor-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscriptor), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> <span class=\"i18n\"></span>\n </label>\n </div>\n </td>\n </tr>\n "; return buffer; } function program2(depth0,data) { return "checked"; } buffer += "<form role=\"form\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-options-form\">\n <div class=\"form-group\">\n <table class='table table-bordered table-hover'>\n <thead>\n <tr>\n <th>Panel</th>\n <th><span class=\"i18n\" data-i18n-id=\"i18n_subscribed\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_subscribe", "Subscribed", options) : helperMissing.call(depth0, "i18n", "i18n_subscribe", "Subscribed", options))) + "</span></th>\n <th><span class=\"i18n\" data-i18n-id=\"i18n_subscriptor\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_subscriptor", "Subscriptor", options) : helperMissing.call(depth0, "i18n", "i18n_subscriptor", "Subscriptor", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.possibleSubscribers), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n</form>"; return buffer; }); /** * Created by alo on 5/9/15. */ var e_openCurlyBraces = '<span class="exp-brackets">{</span>'; var e_closeCurlyBraces = '<span class="exp-brackets">}</span>'; var e_colon = '<span class="exp-operators">:</span>'; var e_plus = '<span class="exp-operators">+</span>'; var e_equals = '<span class="exp-operators">=</span>'; var e_pipe = '<span class="exp-pipes">|</span>'; var panel = {}; var referenceToExpression = function(conceptReference) { return conceptReference.conceptId + " " + e_pipe + "<span class='exp-term'>" + conceptReference.defaultTerm + "</span>" + e_pipe; }; var conceptToPostCoordinatedExpression = function(concept, relsProperty, div, options) { var expression = ""; var tab = "&nbsp;&nbsp;&nbsp;&nbsp;"; if (concept.definitionStatus == "Fully defined" || concept.definitionStatus == "Sufficiently defined") { expression += "<span class='exp-operators'>===</span> "; } else { expression += "<span class='exp-operators'>&lt;&lt;&lt;</span> "; } if (concept[relsProperty] && concept[relsProperty].length > 0) { //expression += ' <span class="exp-brackets">{</span>'; var firstParent = true; var attributes = {}; $.each(concept[relsProperty], function(i, rel){ if (rel.active == true && rel.type.conceptId == "116680003") { if (!firstParent) { expression += " " + e_plus + " <br>"; expression += tab + referenceToExpression(rel.target); } else { expression += referenceToExpression(rel.target); } firstParent = false; } else if (rel.active == true && rel.type.conceptId != "116680003") { if (!attributes[rel.groupId]) { attributes[rel.groupId] = []; } attributes[rel.groupId].push(rel); } }); //console.log(attributes); var groups = Object.keys(attributes); if (groups.length > 0) { expression += " " + e_colon; } $.each(groups, function(i, group){ expression += "<br>"; var firstInGroup = true; $.each(attributes[group], function(i, rel){ if (!firstInGroup) { expression += ", <br>"; } if (group > 0) { expression += tab + tab + tab; } else { expression += tab + tab; } if (firstInGroup && group > 0) { expression += e_openCurlyBraces + " "; } else if (group > 0){ expression += "&nbsp;&nbsp;"; } firstInGroup = false; expression += referenceToExpression(rel.type) + " " + e_equals + " " + referenceToExpression(rel.target); }); if (group != 0) { expression += " " + e_closeCurlyBraces; } }); } return expression; }; var renderExpression = function(concept, inferredConcept, div, options) { var preCoordinatedHtml = referenceToExpression(concept); var tmp = document.createElement("DIV"); tmp.innerHTML = preCoordinatedHtml; var plainPreCoordinatedExpression = tmp.textContent || tmp.innerText || ""; plainPreCoordinatedExpression = plainPreCoordinatedExpression.replace(/\s\s+/g, ' '); var statedHtml = conceptToPostCoordinatedExpression(concept, "statedRelationships", div, options); var tmp = document.createElement("DIV"); tmp.innerHTML = statedHtml; var plainStatedExpression = tmp.textContent || tmp.innerText || ""; plainStatedExpression = plainStatedExpression.replace(/\s\s+/g, ' '); var inferredHtml = conceptToPostCoordinatedExpression(concept, "relationships", div, options); var tmp = document.createElement("DIV"); tmp.innerHTML = inferredHtml; var plainInferredExpression = tmp.textContent || tmp.innerText || ""; plainInferredExpression = plainInferredExpression.replace(/\s\s+/g, ' '); //console.log(div); var context = { divElementId: div.attr('id'), preCoordinatedExpressionHtml: preCoordinatedHtml, statedExpressionHtml: statedHtml, inferredExpressionHtml: inferredHtml, plainPreCoordinatedExpression: plainPreCoordinatedExpression, plainStatedExpression: plainStatedExpression, plainInferredExpression: plainInferredExpression }; div.html(JST["views/conceptDetailsPlugin/tabs/expression.hbs"](context).trim()); if (panel.clipboard) panel.clipboard.destroy(); panel.clipboard = new Clipboard('.clip-btn-exp'); panel.clipboard.on('success', function(e) { // console.info('Action:', e.action); // console.info('Text:', e.text); // console.info('Trigger:', e.trigger); alertEvent("Copied!", "info"); e.clearSelection(); }); panel.clipboard.on('error', function(e) { console.log("Error!"); alertEvent("Error", "error"); }); }; $(function() { $.extend($.fn.disableTextSelect = function() { return this.each(function() { $(this).mousedown(function() { return false; }); }); }); $('.noSelect').disableTextSelect(); //No text selection on elements with a class of 'noSelect' }); function conceptDetails(divElement, conceptId, options) { if (typeof componentsRegistry == "undefined") { componentsRegistry = []; } var languageNameOfLangRefset = { "20581000087109": "fr-CA", "19491000087109": "en-CA", "900000000000508004": "en-GB", "900000000000509007": "en-US", "450828004": "es", "900000701000122101": "es-ES", "554461000005103": "DA", "46011000052107": "SV", "32570271000036106": "AU", "999001251000000103": "UK", "11000146104": "NL" }; if (options.languageNameOfLangRefset) languageNameOfLangRefset = options.languageNameOfLangRefset; var panel = this; this.type = "concept-details"; this.conceptId = conceptId; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); this.attributesPId = ""; this.descsPId = ""; this.relsPId = ""; this.history = []; this.color = "white"; panel.preferred = false; panel.acceptable = false; panel.included = false; panel.refset = {}; panel.refset.simple = false; panel.refset.simplemap = false; panel.refset.attr = false; panel.refset.assoc = false; this.lastGroup = null; this.subscription = null; var xhr = null; var xhrChildren = null; var xhrReferences = null; var xhrParents = null; var xhrMembers = null; var componentConceptPanel = null; var conceptRequested = 0; panel.subscriptionsColor = []; panel.subscriptions = []; panel.subscribers = []; componentLoaded = false; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } this.getConceptId = function() { return this.conceptId; } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setupCanvas = function() { panel.attributesPId = panel.divElement.id + "-attributes-panel"; panel.descsPId = panel.divElement.id + "-descriptions-panel"; panel.relsPId = panel.divElement.id + "-rels-panel"; panel.childrenPId = panel.divElement.id + "-children-panel"; panel.defaultTerm = ""; $(divElement).html(); var context = { divElementId: panel.divElement.id, }; // options statedParents inferredParents firstMatch statedRoles inferredRoles allDescriptions // dataContentValue = document.URL.split("?")[0].split("#")[0] $(divElement).html(JST["views/conceptDetailsPlugin/main.hbs"](context)); // $("#" + panel.divElement.id + "-linkerButton").disableTextSelect(); $("#" + panel.divElement.id + "-subscribersMarker").disableTextSelect(); $("#" + panel.divElement.id + "-configButton").disableTextSelect(); $("#" + panel.divElement.id + "-historyButton").disableTextSelect(); $("#" + panel.divElement.id + "-collapseButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").disableTextSelect(); $("#" + panel.divElement.id + "-closeButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-subscribersMarker").hide(); $("#" + panel.divElement.id + "-closeButton").click(function(event) { $(divElement).remove(); }); $("#" + panel.divElement.id + "-configButton").click(function(event) { panel.setupOptionsPanel(); }); if (typeof panel.options.closeButton != "undefined" && panel.options.closeButton == false) { $("#" + panel.divElement.id + "-closeButton").hide(); } // if (typeof panel.options.linkerButton != "undefined" && panel.options.linkerButton == false) { // $("#" + panel.divElement.id + "-linkerButton").hide(); // } if (typeof panel.options.subscribersMarker != "undefined" && panel.options.subscribersMarker == false) { $("#" + panel.divElement.id + "-subscribersMarker").remove(); } if (typeof panel.options.collapseButton != "undefined" && panel.options.collapseButton == false) { $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").hide(); } $("#" + panel.divElement.id + "-expandButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideDown("fast"); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").show(); $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp<strong>Concept Details</strong>"); }); $("#" + panel.divElement.id + "-collapseButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideUp("fast"); $("#" + panel.divElement.id + "-expandButton").show(); $("#" + panel.divElement.id + "-collapseButton").hide(); //if (panel.defaultTerm.length > 25) { // $("#" + panel.divElement.id + "-panelTitle").html("<strong>Concept Details: " + panel.defaultTerm.substring(0, 24).trim() + "...</strong>"); //} else { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp<strong>Concept Details: " + panel.defaultTerm + "</strong>"); //} }); $('#' + panel.divElement.id).click(function(event) { if (!$(event.target).hasClass('glyphicon')) { $('#' + panel.divElement.id).find('.more-fields-button').popover('hide'); } }); $("#" + panel.divElement.id + "-historyButton").click(function(event) { $("#" + panel.divElement.id + "-historyButton").popover({ trigger: 'manual', placement: 'bottomRight', html: true, content: function() { var historyHtml = '<div style="height:100px;overflow:auto;">'; historyHtml = historyHtml + '<table>'; var reversedHistory = panel.history.slice(0); reversedHistory.reverse(); //console.log(JSON.stringify(reversedHistory)); $.each(reversedHistory, function(i, field) { var d = new Date(); var curTime = d.getTime(); var ago = curTime - field.time; var agoString = ""; if (ago < (1000 * 60)) { if (Math.round((ago / 1000)) == 1) { agoString = Math.round((ago / 1000)) + ' second ago'; } else { agoString = Math.round((ago / 1000)) + ' seconds ago'; } } else if (ago < (1000 * 60 * 60)) { if (Math.round((ago / 1000) / 60) == 1) { agoString = Math.round((ago / 1000) / 60) + ' minute ago'; } else { agoString = Math.round((ago / 1000) / 60) + ' minutes ago'; } } else if (ago < (1000 * 60 * 60 * 60)) { if (Math.round(((ago / 1000) / 60) / 60) == 1) { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hour ago'; } else { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hours ago'; } } historyHtml = historyHtml + '<tr><td><a href="javascript:void(0);" onclick="updateCD(\'' + panel.divElement.id + '\',' + field.conceptId + ');">' + field.defaultTerm + '</a>'; historyHtml = historyHtml + ' <span class="text-muted" style="font-size: 80%"><em>' + agoString + '<em></span>'; historyHtml = historyHtml + '</td></tr>'; }); historyHtml = historyHtml + '</table>'; historyHtml = historyHtml + '</div>'; return historyHtml; } }); $("#" + panel.divElement.id + "-historyButton").popover('toggle'); }); if (typeof i18n_panel_options == "undefined") { i18n_panel_options = "Panel options"; } $("#" + panel.divElement.id + "-configButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_panel_options, animation: true, delay: 1000 }); if (typeof i18n_history == "undefined") { i18n_history = 'History'; } $("#" + panel.divElement.id + "-historyButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_history, animation: true, delay: 1000 }); if (typeof i18n_panel_links == "undefined") { i18n_panel_links = 'Panel links'; } // $("#" + panel.divElement.id + "-linkerButton").tooltip({ // placement : 'left', // trigger: 'hover', // title: i18n_panel_links, // animation: true, // delay: 1000 // }); $("#" + panel.divElement.id + "-apply-button").click(function() { //console.log("apply!"); panel.readOptionsPanel(); // panel.updateCanvas(); }); // $("#" + panel.divElement.id + "-linkerButton").click(function(event) { // $("#" + panel.divElement.id + "-linkerButton").popover({ // trigger: 'manual', // placement: 'bottomRight', // html: true, // content: function() { // if (panel.subscriptions.length == 0) { // linkerHtml = '<div class="text-center text-muted"><em>Not linked yet<br>Drag to link with other panels</em></div>'; // } else { // var linkHtml = ''; // $.each(panel.subscriptions, function(i, field){ // var panelLink = {}; // $.each(componentsRegistry, function(i, panl){ // if (panl.divElement.id == field.topic){ // panelLink = panl; // } // }); // linkHtml = linkHtml + '<div class="text-center"><a href="javascript:void(0);" onclick="\'' + panel.unsubscribe(panelLink) + '\'">Clear link with '+ field.topic +'</a><br></div>'; // }); // linkHtml = linkHtml + ''; // linkerHtml = linkHtml; // } // return linkerHtml; // } // }); // $("#" + panel.divElement.id + "-linkerButton").popover('toggle'); // }); panel.updateCanvas(); channel.publish(panel.divElement.id, { term: panel.term, module: panel.module, conceptId: panel.conceptId, source: panel.divElement.id }); panel.setupOptionsPanel(); if (panel.subscriptions.length > 0 || panel.subscribers.length > 0) { $("#" + panel.divElement.id + "-subscribersMarker").show(); } $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor); } this.updateCanvas = function() { // $("#members-" + panel.divElement.id).html(""); $("#home-children-cant-" + panel.divElement.id).html(""); $('.more-fields-button').popover('hide'); if (conceptRequested == panel.conceptId) { return; } conceptRequested = panel.conceptId; $("#home-children-" + panel.divElement.id + "-body").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.attributesPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#home-attributes-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.descsPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.relsPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#home-parents-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#home-roles-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.childrenPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $("#diagram-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#refsets-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#product-details-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); // load attributes if (xhr != null) { xhr.abort(); //console.log("aborting call..."); } xhr = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/concepts/" + panel.conceptId, function(result) { }).done(function(result) { setDefaultTerm(result); var firstMatch = result; xhr = null; panel.attributesPId = divElement.id + "-attributes-panel"; panel.defaultTerm = firstMatch.defaultTerm; var d = new Date(); var time = d.getTime(); panel.history.push({ defaultTerm: firstMatch.defaultTerm, conceptId: firstMatch.conceptId, time: time }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); panel.statedParents = []; panel.inferredParents = []; panel.statedRoles = []; panel.inferredRoles = []; panel.statedParentsFromAxioms = []; panel.attributesFromAxioms = []; firstMatch.relationships.forEach(function(loopRel) { if (loopRel.characteristicType == "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId != "116680003") { panel.inferredRoles.push(loopRel); } else if(loopRel.characteristicType == "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId === "116680003"){ panel.inferredParents.push(loopRel); } else if(loopRel.characteristicType != "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId === "116680003"){ panel.statedRoles.push(loopRel); } else if (loopRel.characteristicType != "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId != "116680003") { panel.statedRoles.push(loopRel); } }); function sortAxiomRelationships (relationships){ relationships.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.type.conceptId == 116680003) { return -1; } if (b.type.conceptId == 116680003) { return 1; } if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); }; firstMatch.classAxioms.forEach(function(axiom) { if(axiom.active){ axiom.relationships.forEach(function(rel) { if(rel.active && rel.type.conceptId === "116680003"){ panel.statedParentsFromAxioms.push(rel); } else{ rel.axiomId = axiom.axiomId; panel.attributesFromAxioms.push(rel); } }); } sortAxiomRelationships(axiom.relationships); }); firstMatch.gciAxioms.forEach(function(axiom) { if(axiom.active){ axiom.relationships.forEach(function(rel) { if(rel.active && rel.type.conceptId !== "116680003"){ rel.axiomId = axiom.axiomId; panel.attributesFromAxioms.push(rel); } }); } sortAxiomRelationships(axiom.relationships); }); if (firstMatch.statedDescendants) { firstMatch.statedDescendantsString = firstMatch.statedDescendants.toLocaleString(); } if (firstMatch.inferredDescendants) { firstMatch.inferredDescendantsString = firstMatch.inferredDescendants.toLocaleString(); } var context = { options: panel.options, firstMatch: firstMatch, divElementId: panel.divElement.id, edition: options.edition, release: options.release, server: options.serverUrl.substr(0, options.serverUrl.length - 10), langRefset: panel.options.langRefset, link: document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset, // dataContentValue: options.serverUrl.substr(0, options.serverUrl.length - 10) dataContentValue: document.URL.split("?")[0].split("#")[0] }; $('#' + panel.attributesPId).html(JST["views/conceptDetailsPlugin/tabs/details/attributes-panel.hbs"](context)); $('#' + 'share-link-' + panel.divElement.id).disableTextSelect(); $('#' + 'share-link-' + panel.divElement.id).click(function(event) { setTimeout(function() { $('#' + 'share-field-' + panel.divElement.id).select(); }, 300); }); // load home-attributes Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper("if_fav", function(concept, opts) { var favs = stringToArray(localStorage.getItem("favs")); var found = false; if (favs) { $.each(favs, function(i, field) { if (field == concept) { found = true; } }); if (found) { return opts.fn(this); } else { return opts.inverse(this); } } else { return opts.inverse(this); } }); var context = { panel: panel, firstMatch: firstMatch, divElementId: panel.divElement.id, link: document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset }; $('#home-attributes-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/attributes.hbs"](context)); // Update browser history var historyUrl = "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + options.edition + "&release=" + options.release + "&server=" + options.serverUrl + "&langRefset=" + options.langRefset; manualStateChange = false; var state = { name: firstMatch.defaultTerm, conceptId: firstMatch.conceptId, url: historyUrl }; History.pushState(state, "SNOMED CT - " + firstMatch.defaultTerm, historyUrl); $(".glyphicon-star-empty").click(function(e) { var concept = { module: firstMatch.module, conceptId: firstMatch.conceptId, defaultTerm: firstMatch.defaultTerm }; if ($(e.target).hasClass("glyphicon-star")) { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); localStorage.setItem("favs", auxFavs); localStorage.removeItem("conceptId:" + $(e.target).attr("data-conceptId")); $(e.target).addClass("glyphicon-star-empty"); $(e.target).removeClass("glyphicon-star"); // console.log("removed from favs"); } else { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; if (!favs) { favs = []; favs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", favs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } else { $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); auxFavs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", auxFavs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } $(e.target).addClass("glyphicon-star"); $(e.target).removeClass("glyphicon-star-empty"); } channel.publish("favsAction"); }); // console.log("paso"); //$('.clip-btn').unbind(); if (panel.clipboard) panel.clipboard.destroy(); panel.clipboard = new Clipboard('.clip-btn'); panel.clipboard.on('success', function(e) { // console.info('Action:', e.action); // console.info('Text:', e.text); // console.info('Trigger:', e.trigger); alertEvent("Copied!", "info"); e.clearSelection(); }); panel.clipboard.on('error', function(e) { console.log("Error!"); alertEvent("Error", "error"); }); //var ctrlDown = false, // ctrlKey = 17, // cmdKey = 91, // vKey = 86, // cKey = 67; // //$(document).keydown(function(e) { // if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true; //}).keyup(function(e) { // if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false; //}); // //$(document).keydown(function(e) { // if (ctrlDown && e.keyCode == cKey){ // //var copyContent = document.getElementById("copy-content"); // e.clipboardData.setData('text/plain', firstMatch.term); // e.preventDefault(); // //$("#" + panel.divElement.id + "-copy-sctid-term-details").click(); // //console.log("asd"); // } //}); document.addEventListener("copy", copyHandler, false); function copyHandler(e) { if (window.getSelection().isCollapsed) { if (e.srcElement && e.srcElement.value) {} else { e.clipboardData.setData('text/plain', firstMatch.conceptId + " | " + firstMatch.defaultTerm + " |"); e.preventDefault(); alertEvent("Copied!", "info"); } } } //Swedish extension; capture synonyms using JIRA issue collector //start var scriptUrl = "https://jira.ihtsdotools.org/s/9152b378d577114d19d6cfdcdfdeb45e-T/en_US-i9n6p8/70120/a1623a9e469981bb7c457209f1507980/2.0.8/_/download/batch/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector.js?locale=en-US&collectorId=41bec258"; $.getScript(scriptUrl); window.ATL_JQ_PAGE_PROPS = { "triggerFunction": function(showCollectorDialog) { //Requires that jQuery is available! jQuery("#fh-cd1_canvas-addsyn-sctid-details").click(function(e) { e.preventDefault(); showCollectorDialog(); }); }, fieldValues: { 'summary': 'Förslag på synonymer för begreppet: ' + state.conceptId, 'customfield_10602': state.conceptId, 'customfield_10601': state.name } }; //end $(".glyphicon-star").click(function(e) { var concept = { module: firstMatch.module, conceptId: firstMatch.conceptId, defaultTerm: firstMatch.defaultTerm }; if ($(e.target).hasClass("glyphicon-star")) { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); localStorage.setItem("favs", auxFavs); localStorage.removeItem("conceptId:" + $(e.target).attr("data-conceptId")); $(e.target).addClass("glyphicon-star-empty"); $(e.target).removeClass("glyphicon-star"); // console.log("removed from favs"); } else { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; if (!favs) { favs = []; favs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", favs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } else { $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); auxFavs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", auxFavs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } $(e.target).addClass("glyphicon-star"); $(e.target).removeClass("glyphicon-star-empty"); } channel.publish("favsAction"); }); if (!firstMatch.active) { $('#home-attributes-' + panel.divElement.id).css("background-color", "LightPink"); } else { $('#home-attributes-' + panel.divElement.id).css("background-color", "#428bca"); } if ($("#" + panel.divElement.id + "-expandButton").is(":visible")) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp;&nbsp;&nbsp;<strong>Concept Details: " + panel.defaultTerm + "</strong>"); } if (typeof i18n_drag_this == "undefined") { i18n_drag_this = "Drag this"; } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); // load descriptions panel panel.descsPId = divElement.id + "-descriptions-panel"; var languageName = ""; if (panel.options.langRefset == "900000000000508004") { languageName = "(GB)"; } else if (panel.options.langRefset == "900000000000509007") { languageName = "(US)"; } else if (panel.options.langRefset == "450828004") { languageName = "(ES)"; } else if (panel.options.langRefset == "554461000005103") { languageName = "(DA)"; } else if (panel.options.langRefset == "46011000052107") { languageName = "(SV)"; } else if (panel.options.langRefset == "32570271000036106") { languageName = "(AU)"; } else if (panel.options.langRefset == "999001251000000103") { languageName = "(UK)"; } else if (panel.options.langRefset == "31000146106") { languageName = "(NL)"; } // START FOR var allLangsHtml = ""; $.each(panel.options.langRefset, function(i, loopSelectedLangRefset) { var allDescriptions = firstMatch.descriptions.slice(0); var homeDescriptionsHtml = ""; $.each(allDescriptions, function(i, field) { field.included = false; field.preferred = false; field.acceptable = false; if (panel.options.displayInactiveDescriptions || field.active == true) { if (field.active == true) { if (homeDescriptionsHtml != "") { homeDescriptionsHtml = homeDescriptionsHtml + "<br>"; } homeDescriptionsHtml = homeDescriptionsHtml + "&nbsp;&nbsp;<i>" + field.lang + "</i>&nbsp;&nbsp;&nbsp;" + field.term; } } }); Handlebars.registerHelper('removeSemtag', function(term) { return panel.removeSemtag(term); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); var auxDescriptions = []; $.each(allDescriptions, function(i, description) { var included = false; if (description.acceptabilityMap) { $.each(description.acceptabilityMap, function(langref, acceptability) { acceptabilityPair = description.acceptabilityMap[i]; if (langref == loopSelectedLangRefset) { included = true; if (acceptability == "PREFERRED") { description.preferred = true; } else { if (acceptability == "ACCEPTABLE") { description.acceptable = true; } } } }); } if (included) { auxDescriptions.push(description); } else { description.acceptable = false; if (panel.options.hideNotAcceptable) { if (panel.options.displayInactiveDescriptions) { auxDescriptions.push(description); } } else { if (options.displayInactiveDescriptions) { auxDescriptions.push(description); } else { if (description.active) { auxDescriptions.push(description); } } } } }); allDescriptions = auxDescriptions.slice(0); allDescriptions.sort(function(a, b) { if (a.active && !b.active) return -1; if (!a.active && b.active) return 1; if (a.active == b.active) { if ((a.acceptable || a.preferred) && (!b.preferred && !b.acceptable)) return -1; if ((!a.preferred && !a.acceptable) && (b.acceptable || b.preferred)) return 1; if (a.type.conceptId < b.type.conceptId) return -1; if (a.type.conceptId > b.type.conceptId) return 1; if (a.type.conceptId == b.type.conceptId) { if (a.preferred && !b.preferred) return -1; if (!a.preferred && b.preferred) return 1; if (a.preferred == b.preferred) { if (a.term < b.term) return -1; if (a.term > b.term) return 1; } } } return 0; }); var context = { options: panel.options, languageName: "(" + languageNameOfLangRefset[loopSelectedLangRefset] + ")", longLangName: loopSelectedLangRefset, divElementId: panel.divElement.id, allDescriptions: allDescriptions }; if (panel.options.manifest) { $.each(panel.options.manifest.languageRefsets, function(i, looplr) { if (looplr.conceptId == loopSelectedLangRefset) { context.longLangName = looplr.defaultTerm; } }); } allLangsHtml += JST["views/conceptDetailsPlugin/tabs/details/descriptions-panel.hbs"](context); //if (panel.options.displaySynonyms) { $('#home-descriptions-' + panel.divElement.id).html(homeDescriptionsHtml); //} }); // END FOR $("#" + panel.descsPId).html(allLangsHtml); if (panel.options.displaySynonyms != true) { // hide synonyms $('#' + panel.descsPId).find('.synonym-row').each(function(i, val) { $(val).toggle(); }); $(this).toggleClass('glyphicon-plus'); $(this).toggleClass('glyphicon-minus'); } $("#" + panel.descsPId + "-descButton").disableTextSelect(); $("#" + panel.descsPId + "-descButton").click(function() { table = $(this).closest("table").first(); $(this).toggleClass('glyphicon-plus'); $(this).toggleClass('glyphicon-minus'); table.find('.synonym-row').each(function(i, val) { $(val).toggle(); }); }); $('#' + panel.descsPId).find("[rel=tooltip-right]").tooltip({ placement: 'right' }); // load relationships panel and home parents/roles if (panel.options.selectedView == "stated") { //$('#home-' + panel.divElement.id + '-viewLabel').html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); //$('#home-' + panel.divElement.id + '-diagram-viewLabel').html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); $('#home-' + panel.divElement.id + '-stated-button').unbind(); $('#home-' + panel.divElement.id + '-inferred-button').unbind(); $('#details-' + panel.divElement.id + '-stated-button').unbind(); $('#details-' + panel.divElement.id + '-inferred-button').unbind(); $('#home-' + panel.divElement.id + '-stated-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-stated-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-inferred-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-inferred-button').removeClass("btn-primary"); $('#details-' + panel.divElement.id + '-stated-button').addClass("btn-primary"); $('#details-' + panel.divElement.id + '-stated-button').removeClass("btn-default"); $('#details-' + panel.divElement.id + '-inferred-button').addClass("btn-default"); $('#details-' + panel.divElement.id + '-inferred-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-inferred-button').click(function(event) { panel.options.selectedView = "inferred"; panel.updateCanvas(); }); $('#details-' + panel.divElement.id + '-inferred-button').click(function(event) { panel.options.selectedView = "inferred"; panel.updateCanvas(); }); } else { //$('#home-' + panel.divElement.id + '-viewLabel').html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); //$('#home-' + panel.divElement.id + '-diagram-viewLabel').html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); $('#home-' + panel.divElement.id + '-stated-button').unbind(); $('#home-' + panel.divElement.id + '-inferred-button').unbind(); $('#home-' + panel.divElement.id + '-inferred-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-inferred-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-stated-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-stated-button').removeClass("btn-primary"); $('#details-' + panel.divElement.id + '-stated-button').unbind(); $('#details-' + panel.divElement.id + '-inferred-button').unbind(); $('#details-' + panel.divElement.id + '-inferred-button').addClass("btn-primary"); $('#details-' + panel.divElement.id + '-inferred-button').removeClass("btn-default"); $('#details-' + panel.divElement.id + '-stated-button').addClass("btn-default"); $('#details-' + panel.divElement.id + '-stated-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-stated-button').click(function(event) { panel.options.selectedView = "stated"; panel.updateCanvas(); }); $('#details-' + panel.divElement.id + '-stated-button').click(function(event) { panel.options.selectedView = "stated"; panel.updateCanvas(); }); } panel.relsPId = divElement.id + "-rels-panel"; if (firstMatch.relationships) { firstMatch.relationships.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.type.conceptId == 116680003) { return -1; } if (b.type.conceptId == 116680003) { return 1; } if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); } if (firstMatch.statedRelationships) { firstMatch.statedRelationships.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.type.conceptId == 116680003) { return -1; } if (b.type.conceptId == 116680003) { return 1; } if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); } Handlebars.registerHelper('push', function(element, array) { array.push(element); // return ; }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); var additionalRels; if (firstMatch.additionalRelationships) { $.each(firstMatch.additionalRelationships, function(i, looplr) { if (looplr.active) { if (typeof additionalRels == "undefined") additionalRels = []; additionalRels.push(looplr); } }); } var context = { options: panel.options, firstMatch: firstMatch, inferredParents: panel.inferredParents, inferredRoles: panel.inferredRoles, statedParents: panel.statedParents, statedRoles: panel.statedRoles, additionalRels: additionalRels, statedParentsFromAxioms: panel.statedParentsFromAxioms, attributesFromAxioms : panel.attributesFromAxioms }; $("#" + panel.relsPId).html(JST["views/conceptDetailsPlugin/tabs/details/rels-panel.hbs"](context)); panel.inferredParents.sort(function(a, b) { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; }); panel.statedParents.sort(function(a, b) { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; }); panel.statedParentsFromAxioms.sort(function(a, b) { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; }); panel.attributesFromAxioms.sort(function(a, b) { if (a.target.axiomId < b.target.axiomId) return -1; if (a.target.axiomId > b.target.axiomId) return 1; return 0; }); panel.inferredRoles.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); panel.statedRoles.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); Handlebars.registerHelper('substr', function(string, start) { var l = string.lastIndexOf("(") - 1; return string.substr(start, l); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { var s = a.lastIndexOf("("); if (s > b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); var axioms = false; if(firstMatch.classAxioms.length > 0 || firstMatch.gciAxioms.length > 0) { axioms = true; } else { axioms = false; } var context = { divElementId: panel.divElement.id, statedParents: panel.statedParents, inferredParents: panel.inferredParents, options: panel.options, firstMatch: firstMatch, statedParentsFromAxioms: panel.statedParentsFromAxioms, attributesFromAxioms : panel.attributesFromAxioms, axioms: axioms }; $('#home-parents-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/parents.hbs"](context)); if (!panel.options.diagrammingMarkupEnabled) { $('#home-parents-' + panel.divElement.id).html(panel.stripDiagrammingMarkup($('#home-parents-' + panel.divElement.id).html())); } $(".treeButton").disableTextSelect(); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); $("#home-parents-" + panel.divElement.id).unbind(); $("#home-parents-" + panel.divElement.id).click(function(event) { if ($(event.target).hasClass("treeButton")) { var ev = event.target; //firefox issue! if (navigator.userAgent.indexOf("Firefox") > -1) { ev = $(ev).context.children; } var conceptId = $(ev).closest("li").attr('data-concept-id'); event.preventDefault(); if ($(ev).hasClass("glyphicon-chevron-up")) { $(ev).closest("li").find("ul").remove(); $(ev).removeClass("glyphicon-chevron-up"); $(ev).addClass("glyphicon-chevron-right"); } else if ($(ev).hasClass("glyphicon-chevron-right")) { $(ev).removeClass("glyphicon-chevron-right"); $(ev).addClass("glyphicon-refresh"); $(ev).addClass("icon-spin"); panel.getParent(conceptId, ev); } else if ($(ev).hasClass("glyphicon-minus")) { // $("#" + iconId).removeClass("glyphicon-minus"); // $("#" + iconId).addClass("glyphicon-chevron-right"); } } else if ($(event.target).hasClass("treeLabel")) { var selectedId = $(event.target).attr('data-concept-id'); if (typeof selectedId != "undefined") { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: selectedId, source: panel.divElement.id }); } } }); $("#home-parents-" + panel.divElement.id).dblclick(function(event) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); panel.conceptId = conceptId; panel.updateCanvas(); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: conceptId, source: panel.divElement.id }); }); Handlebars.registerHelper('eqLastGroup', function(a, opts) { // console.log(a, panel.lastGroup); if (panel.lastGroup == null) { panel.lastGroup = a; return opts.fn(this); } if (a != panel.lastGroup) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('removeSemtag', function(term) { return panel.removeSemtag(term); }); Handlebars.registerHelper('setLastGroup', function(a) { panel.lastGroup = a; }); Handlebars.registerHelper('lastColor', function(a) { if (a == "get") { return ""; // return panel.color; } else { if (a == "random") { panel.color = getRandomColor(); } else { panel.color = a; } } }); Handlebars.registerHelper('getRandomColor', function() { // return getRandomColor(); return ""; }); var context = { options: panel.options, statedRoles: panel.statedRoles, inferredRoles: panel.inferredRoles, firstMatch: firstMatch, statedParentsFromAxioms: panel.statedParentsFromAxioms, attributesFromAxioms : panel.attributesFromAxioms }; // console.log(panel.statedRoles); // console.log(panel.inferredRoles); $('#home-roles-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/roles.hbs"](context)); if (!panel.options.diagrammingMarkupEnabled) { $('#home-roles-' + panel.divElement.id).html(panel.stripDiagrammingMarkup($('#home-roles-' + panel.divElement.id).html())); } Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('refset', function(type, data, opts) { if (data == "get") { if (panel.refset[type]) { return opts.fn(this); } else { return opts.inverse(this); } } else { panel.refset[type] = data; } }); var context = { firstMatch: firstMatch }; $('#refsets-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/refset.hbs"](context)); $.each($("#refsets-" + panel.divElement.id).find('.refset-simplemap'), function(i, field) { // console.log(field); // console.log($(field).attr('data-refsetId')); if ($(field).attr('data-refsetId') == "467614008") { channel.publish("refsetSubscription-467614008", { conceptId: $(field).attr('data-conceptId') }); } }); if ($('ul#details-tabs-' + panel.divElement.id + ' li.active').attr('id') == "references-tab") { $("#references-" + panel.divElement.id + "-resultsTable").html(""); panel.getReferences(firstMatch.conceptId); } if ($('ul#details-tabs-' + panel.divElement.id + ' li.active').attr('id') == "diagram-tab") { drawConceptDiagram(firstMatch, $("#diagram-canvas-" + panel.divElement.id), panel.options, panel); } if ($('ul#details-tabs-' + panel.divElement.id + ' li.active').attr('id') == "expression-tab") { $("#expression-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); setTimeout(function() { renderExpression(firstMatch, firstMatch, $("#expression-canvas-" + panel.divElement.id), options); }, 300); } $("#references-tab-link-" + panel.divElement.id).unbind(); $("#references-tab-link-" + panel.divElement.id).click(function(e) { $("#references-" + panel.divElement.id + "-resultsTable").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); panel.getReferences(firstMatch.conceptId); }); $("#diagram-tab-link-" + panel.divElement.id).unbind(); $("#diagram-tab-link-" + panel.divElement.id).click(function(e) { $("#diagram-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); setTimeout(function() { $("#diagram-canvas-" + panel.divElement.id).html(""); drawConceptDiagram(firstMatch, $("#diagram-canvas-" + panel.divElement.id), panel.options, panel); }, 1000); }); $("#expression-tab-link-" + panel.divElement.id).unbind(); $("#expression-tab-link-" + panel.divElement.id).click(function(e) { $("#expression-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); setTimeout(function() { $("#expression-canvas-" + panel.divElement.id).html(""); renderExpression(firstMatch, firstMatch, $("#expression-canvas-" + panel.divElement.id), options); }, 1000) }); if (firstMatch.defaultTerm.endsWith("(clinical drug)")) { $("#product-details-tab").show(); var productData = { defaultTerm: firstMatch.defaultTerm, forms: [], groups: {}, ingredients: [] }; firstMatch.relationships.forEach(function(loopRel) { if (loopRel.type.conceptId == "411116001" && loopRel.active) { productData.forms.push(loopRel); } else if (loopRel.active && loopRel.groupId != 0) { if (typeof productData.groups[loopRel.groupId] == "undefined") { productData.groups[loopRel.groupId] = []; } productData.groups[loopRel.groupId].push(loopRel); } }); Object.keys(productData.groups).forEach(function(loopKey) { var loopGroup = productData.groups[loopKey]; var loopIngredient = {}; loopGroup.forEach(function(loopRel) { if (loopRel.type.conceptId == "127489000") { loopIngredient.ingredient = loopRel.target; } else if (loopRel.type.conceptId == "732946004") { loopIngredient.denominatorValue = loopRel.target; } else if (loopRel.type.conceptId == "732944001") { loopIngredient.numeratorValue = loopRel.target; } else if (loopRel.type.conceptId == "732943007") { loopIngredient.boss = loopRel.target; } else if (loopRel.type.conceptId == "732947008") { loopIngredient.denominatorUnit = loopRel.target; } else if (loopRel.type.conceptId == "732945000") { loopIngredient.numeratorUnit = loopRel.target; } }); productData.ingredients.push(loopIngredient); // var demoIngredient1 = { // ingredient: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Atenolol (substance)"}, // boss: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Atenolol (substance)"}, // numeratorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"50 (qualifier value)"}, // numeratorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"milligram (qualifier value)"}, // denominatorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"1 (qualifier value)"}, // denominatorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Tablet (unit of presentation)"} // }; // var demoIngredient2 = { // ingredient: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Chlorthalidone (substance)"}, // boss: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Chlorthalidone (substance)"}, // numeratorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"12.5 (qualifier value)"}, // numeratorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"milligram (qualifier value)"}, // denominatorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"1 (qualifier value)"}, // denominatorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Tablet (unit of presentation)"} // }; //productData.ingredients = [demoIngredient1, demoIngredient2]; }); console.log(productData); var context = { productData: productData }; $('#product-details-' + panel.divElement.id).html( JST["views/conceptDetailsPlugin/tabs/product.hbs"](context)); } else { $("#product-details-tab").hide(); $('#details-tabs-' + panel.divElement.id + ' a:first').tab('show') } $('.more-fields-button').disableTextSelect(); $('.more-fields-button').popover(); // firefox popover if (navigator.userAgent.indexOf("Firefox") > -1) { $(".more-fields-button").optionsPopover({ contents: "", disableBackButton: true }); $(".more-fields-button").click(function(e) { var auxHtml = $(e.target).attr('data-content'); $("#popoverContent").html(auxHtml); }); } if (panel.options.selectedView == "stated") { $('#' + panel.relsPId).find('.inferred-rel').each(function(i, val) { $(val).toggle(); }); } else if (panel.options.selectedView == "inferred") { $('#' + panel.relsPId).find('.stated-rel').each(function(i, val) { $(val).toggle(); }); } else if (panel.options.selectedView != "all") { // show all } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); if (typeof(switchLanguage) == "function") { switchLanguage(selectedLanguage, selectedFlag, false); } conceptRequested = 0; // membersUrl = options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + panel.conceptId + "/members"; }).fail(function() { panel.relsPId = divElement.id + "-rels-panel"; panel.attributesPId = divElement.id + "-attributes-panel"; panel.descsPId = divElement.id + "-descriptions-panel"; $("#home-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#diagram-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#members-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#references-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#refsets-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $('#' + panel.attributesPId).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $('#' + panel.descsPId).html(""); $('#' + panel.relsPId).html(""); }); // if (typeof xhr != "undefined") { // console.log("aborting call..."); // // } if (panel.options.displayChildren) { var context = { }; } else {} // if (panel.options.displayChildren == false) { //// $("#home-children-" + panel.divElement.id).hide(); // $('#' + panel.childrenPId).html(""); // $('#' + panel.childrenPId).hide(); // } else { // $("#home-children-" + panel.divElement.id).show(); // $('#' + panel.childrenPId).show(); if (xhrChildren != null) { xhrChildren.abort(); //console.log("aborting children call..."); } xhrChildren = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + panel.conceptId + "/children?form=" + panel.options.selectedView, function(result) { //$.getJSON(panel.url + "rest/browser/concepts/" + panel.conceptId + "/children", function(result) { }).done(function(result) { result.forEach(function(c) { setDefaultTerm(c) }); // load relationships panel result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); xhrChildren = null; panel.childrenPId = divElement.id + "-children-panel"; // console.log(result); var context = { displayChildren: panel.options.displayChildren, divElementId: panel.divElement.id, childrenResult: result, selectedView: panel.options.selectedView }; $("#home-children-cant-" + panel.divElement.id).html("(" + result.length + ")"); $('#' + panel.childrenPId).html(JST["views/conceptDetailsPlugin/tabs/details/children-panel.hbs"](context)); $("#home-children-" + panel.divElement.id + "-body").html(JST["views/conceptDetailsPlugin/tabs/home/children.hbs"](context)); $(".treeButton").disableTextSelect(); if (typeof i18n_drag_this == "undefined") { i18n_drag_this = "Drag this"; } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); $("#home-children-" + panel.divElement.id + "-body").unbind(); $("#home-children-" + panel.divElement.id + "-body").click(function(event) { if ($(event.target).hasClass("treeButton")) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); var iconId = panel.divElement.id + "-treeicon-" + conceptId; event.preventDefault(); if ($("#" + iconId).hasClass("glyphicon-chevron-down")) { //console.log("close"); $(event.target).closest("li").find("ul").remove(); $("#" + iconId).removeClass("glyphicon-chevron-down"); $("#" + iconId).addClass("glyphicon-chevron-right"); } else if ($("#" + iconId).hasClass("glyphicon-chevron-right")) { //console.log("open"); $("#" + iconId).removeClass("glyphicon-chevron-right"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); panel.getChildren($(event.target).closest("li").attr('data-concept-id'), true); } else if ($("#" + iconId).hasClass("glyphicon-minus")) { // $("#" + iconId).removeClass("glyphicon-minus"); // $("#" + iconId).addClass("glyphicon-chevron-right"); } } else if ($(event.target).hasClass("treeLabel")) { var selectedId = $(event.target).attr('data-concept-id'); if (typeof selectedId != "undefined") { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: selectedId, source: panel.divElement.id }); } } }); $("#home-children-" + panel.divElement.id + "-body").dblclick(function(event) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); panel.conceptId = conceptId; panel.updateCanvas(); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: conceptId, source: panel.divElement.id }); }); if (typeof i18n_display_children == "undefined") { i18n_display_children = "Display Children"; } $("#" + panel.divElement.id + "-showChildren").tooltip({ placement: 'right', trigger: 'hover', title: i18n_display_children, animation: true, delay: 500 }); $("#" + panel.divElement.id + "-showChildren").click(function() { panel.options.displayChildren = true; panel.updateCanvas(); }); }).fail(function() { $('#' + panel.childrenPId).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); }); // } panel.loadMembers(100, 0); } this.getReferences = function(conceptId) { $("#references-" + panel.divElement.id + "-accordion").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); //console.log(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/references"); if (xhrReferences != null) { xhrReferences.abort(); //console.log("aborting references call..."); } xhrReferences = $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/references?form=" + panel.options.selectedView, function(result) { }).done(function(result) { Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); $.each(result, function(i, field) { if (field.statedRelationships) { field.relationship = field.statedRelationships[0].type.defaultTerm; } else { field.relationship = field.relationships[0].type.defaultTerm; } }); result.sort(function(a, b) { if (a.relationship < b.relationship) return -1; if (a.relationship > b.relationship) return 1; if (a.relationship == b.relationship) { if (a.defaultTerm < b.defaultTerm) return -1; if (a.defaultTerm > b.defaultTerm) return 1; } return 0; }); result.groups = []; var lastR = "", auxArray = []; $.each(result, function(i, field) { if (lastR == "") { auxArray.push(field); lastR = field.relationship; } else { if (lastR == field.relationship) { auxArray.push(field); } else { result.groups.push(auxArray); auxArray = []; auxArray.push(field); lastR = field.relationship; } } }); result.groups.push(auxArray); // console.log(result.groups); var context = { divElementId: panel.divElement.id, result: result, groups: result.groups }; // $("#references-" + panel.divElement.id + "-total").html(result.length + " references"); $("#references-" + panel.divElement.id + "-accordion").html(JST["views/conceptDetailsPlugin/tabs/references.hbs"](context)); $("#references-" + panel.divElement.id + "-accordion").click(function(e) { if ($($(e.target).closest("a").attr("href")).hasClass("collapse")) { //console.log("finded"); var target = $($(e.target).closest("a").attr("href") + "-span"); if (target.hasClass("glyphicon-chevron-right")) { target.removeClass("glyphicon-chevron-right"); target.addClass("glyphicon-chevron-down"); } else { target.addClass("glyphicon-chevron-right"); target.removeClass("glyphicon-chevron-down"); } } }); // console.log(result, result.length); }).fail(function() { $("#references-" + panel.divElement.id + "-accordion").html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); }); } this.getChildren = function(conceptId, forceShow) { if (typeof panel.options.selectedView == "undefined") { panel.options.selectedView = "inferred"; } if (panel.options.selectedView == "inferred") { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); } else { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); } if (xhrChildren != null) { xhrChildren.abort(); //console.log("aborting children call..."); } xhrChildren = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/children?form=" + panel.options.selectedView, function(result) {}).done(function(result) { result.forEach(function(c) { setDefaultTerm(c) }); result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); //console.log(JSON.stringify(result)); var listIconIds = []; //console.log(JSON.stringify(listIconIds)); var context = { displayChildren: panel.options.displayChildren, childrenResult: result, divElementId: panel.divElement.id, selectedView: panel.options.selectedView }; if (typeof forceShow != "undefined") { if (forceShow) { context.displayChildren = forceShow; } } Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('push', function(element) { listIconIds.push(element); }); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); if (result.length > 0) { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down"); } else { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); } $("#" + panel.divElement.id + "-treenode-" + conceptId).closest("li").append(JST["views/conceptDetailsPlugin/tabs/home/children.hbs"](context)); $(".treeButton").disableTextSelect(); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() { $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); }); } this.getParent = function(conceptId, target) { if (xhrParents != null) { xhrParents.abort(); //console.log("aborting children call..."); } xhrParents = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/parents?form=" + panel.options.selectedView, function(result) { //$.getJSON(panel.url + "rest/browser/concepts/" + panel.conceptId + "/children", function(result) { }).done(function(result) { result.forEach(function(c) { setDefaultTerm(c) }); result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); var auxHtml = ""; var ind = $(target).attr('data-ind'); if (result.length > 0) { if ($(target).attr('data-firstt')) { auxHtml = "<ul style='margin-left: 95px; list-style-type: none; padding-left: 15px'>"; } else { auxHtml = "<ul style='list-style-type: none; padding-left: 15px'>"; } $.each(result, function(i, field) { // console.log(field); auxHtml = auxHtml + "<li class='treeLabel' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'><button class='btn btn-link btn-xs treeButton' style='padding:2px'>"; if (field.conceptId == "138875005" || field.conceptId == "9999999999") { auxHtml = auxHtml + "<i class='glyphicon glyphicon-minus treeButton' data-ind='" + ind + "'></i></button>"; } else { auxHtml = auxHtml + "<i class='glyphicon glyphicon-chevron-right treeButton' data-ind='" + ind + "'></i></button>"; } if (field.definitionStatus == "PRIMITIVE") { auxHtml = auxHtml + "<span class='badge alert-warning' draggable='true' ondragstart='drag(event)' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'>&nbsp;&nbsp;</span>&nbsp;&nbsp"; } else { auxHtml = auxHtml + "<span class='badge alert-warning' draggable='true' ondragstart='drag(event)' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'>&equiv;</span>&nbsp;&nbsp"; } if (countryIcons[field.module]) { auxHtml = auxHtml + "<div class='phoca-flagbox' style='width:26px;height:26px'><span class='phoca-flag " + countryIcons[field.module] + "'></span></div>&nbsp"; } auxHtml = auxHtml + "<a id='" + ind + panel.divElement.id + "-treeicon-" + field.conceptId + "' href='javascript:void(0);' style='color: inherit;text-decoration: inherit;'>"; auxHtml = auxHtml + "<span class='treeLabel selectable-row' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'>" + field.defaultTerm + "</span></a></li>"; }); auxHtml = auxHtml + "</ul>"; } $(target).removeClass("glyphicon-refresh"); $(target).removeClass("icon-spin"); if (result.length > 0) { $(target).addClass("glyphicon-chevron-up"); } else { $(target).addClass("glyphicon-minus"); } $(target).closest("li").prepend(auxHtml); // $("#" + ind + panel.divElement.id + "-treeicon-" + conceptId).after(auxHtml); $(".treeButton").disableTextSelect(); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() {}); } this.loadMembers = function(returnLimit, skipTo, paginate) { var membersUrl = options.serverUrl + "/" + options.edition + "/" + options.release + "/members?referenceSet=" + panel.conceptId + "&limit=100"; if (skipTo > 0) { membersUrl = membersUrl + "&offset=" + skipTo; } else { $('#members-' + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><i class='glyphicon glyphicon-refresh icon-spin'></i></td></tr>"); } var total; if (panel.options.manifest) { // console.log(panel.options.manifest); $.each(panel.options.manifest.refsets, function(i, field) { if (field.conceptId == panel.conceptId) { if (field.count) { total = field.count; } } }); } if (typeof total != "undefined") { // console.log(total); // if (total < 25000){ paginate = 1; membersUrl = membersUrl + "&paginate=1"; //} } // console.log(membersUrl); if (xhrMembers != null) { xhrMembers.abort(); //console.log("aborting call..."); } xhrMembers = $.getJSON(membersUrl, function(result) { }).done(function(result) { var remaining = "asd"; if (typeof total == "undefined") total = result.total; if (total == skipTo) { remaining = 0; } else { if (total > (skipTo + returnLimit)) { remaining = total - (skipTo + returnLimit); } else { // if (result.details.total < returnLimit && skipTo != 0){ remaining = 0; // }else{ // remaining = result.details.total; // } } } if (remaining < returnLimit) { var returnLimit2 = remaining; } else { if (remaining != 0) { var returnLimit2 = returnLimit; } else { var returnLimit2 = 0; } } var context = { result: result, returnLimit: returnLimit2, remaining: remaining, divElementId: panel.divElement.id, skipTo: skipTo, panel: panel }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); if (result.total != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#members-" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#members-' + panel.divElement.id + "-resultsTable").html(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } else { $('#members-' + panel.divElement.id + "-resultsTable").append(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); panel.loadMembers(returnLimit2, skipTo + returnLimit, paginate); }); $("#members-" + panel.divElement.id + "-sort").unbind(); $("#members-" + panel.divElement.id + "-sort").click(function() { $("#members-" + panel.divElement.id + "-sort").blur(); panel.loadMembers(returnLimit, 0, 1); }); } else { if (skipTo != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#members-" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#members-' + panel.divElement.id + "-resultsTable").html(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } else { $('#members-' + panel.divElement.id + "-resultsTable").append(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); panel.loadMembers(returnLimit2, skipTo + returnLimit, paginate); }); $("#members-" + panel.divElement.id + "-sort").unbind(); $("#members-" + panel.divElement.id + "-sort").click(function() { $("#members-" + panel.divElement.id + "-sort").blur(); panel.loadMembers(returnLimit, 0, 1); }); } else { $('#members-' + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } } $('#members-' + panel.divElement.id).find(".member-row").unbind(); $('#members-' + panel.divElement.id).find(".member-row").click(function(e) { var clickedConceptId = $(e.target).data("concept-id"); //var clickedTerm = $(e.target).data("term"); panel.conceptId = clickedConceptId; $('#details-tabs-' + panel.divElement.id + ' a:first').tab('show'); panel.updateCanvas(); }); }).fail(function() { $('#members-' + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); }); }; this.stripDiagrammingMarkup = function(htmlString) { if (!htmlString) htmlString = ""; htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-primitive-concept-compact"), 'g'), ""); htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-defined-concept-compact"), 'g'), ""); htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-attribute-compact"), 'g'), ""); return htmlString; }; this.escapeRegExp = function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }; // this.setSubscription = function(subscriptionPanel) { // panel.subscription = subscriptionPanel; // $("#" + panel.divElement.id + "-subscribersMarker").css('color', subscriptionPanel.markerColor); // $("#" + panel.divElement.id + "-subscribersMarker").show(); // } // this.clearSubscription = function() { // panel.subscription = null; // $("#" + panel.divElement.id + "-subscribersMarker").hide(); // } this.removeSemtag = function(term) { if (term) { if (term.lastIndexOf("(") > 0) { return term.substr(0, term.lastIndexOf("(") - 1) } else { return term; } } } this.loadMarkers = function() { var auxMarker = "", right = 0, top = 0, aux = false, visible = false; $.each(componentsRegistry, function(i, field) { var panelId = field.divElement.id; if ($("#" + panelId + "-subscribersMarker").is(':visible')) { visible = true; } }); if (panel.subscribers.length == 0) { right = 14; $("#" + panel.divElement.id + "-ownMarker").hide(); } else { if (!visible) { $("#" + panel.divElement.id + "-ownMarker").hide(); } aux = true; } if ($("#" + panel.divElement.id + "-subscribersMarker").is(':visible')) { $("#" + panel.divElement.id + "-panelTitle").html($("#" + panel.divElement.id + "-panelTitle").html().replace(/&nbsp;/g, '')); if (aux) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); } $.each(panel.subscriptionsColor, function(i, field) { auxMarker = auxMarker + "<i class='glyphicon glyphicon-bookmark' style='color: " + field + "; top:" + top + "px; right: " + right + "px;'></i>"; $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); top = top + 5; right = right + 10; }); $("#" + panel.divElement.id + "-subscribersMarker").html(auxMarker); } } // Subsription methods this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; var alreadySubscribed = false; $.each(panel.subscriptionsColor, function(i, field) { if (field == panelToSubscribe.markerColor) { alreadySubscribed = true; } }); //console.log('Subscribing to id: ' + panelId, !alreadySubscribed); if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { // console.log("listening in " + panel.divElement.id); panel.conceptId = data.conceptId; if (data.showConcept) { $('a[href="#fh-cd1_canvas-pane"]').click(); } if ($("#home-children-" + panel.divElement.id + "-body").length > 0) {} else { panel.setupCanvas(); if (panel.loadMarkers) panel.loadMarkers(); } panel.updateCanvas(); // This creates a cycle // channel.publish(panel.divElement.id, { // term: data.term, // conceptId: data.conceptId, // source: data.source // }); }); panel.subscriptions.push(subscription); panelToSubscribe.subscribers.push(panel.divElement.id); panel.subscriptionsColor.push(panelToSubscribe.markerColor); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-ownMarker").show(); } this.unsubscribe = function(panelToUnsubscribe) { var aux = [], colors = [], unsubscribed = true; $.each(panel.subscriptionsColor, function(i, field) { if (field != panelToUnsubscribe.markerColor) { colors.push(field); } else { unsubscribed = false; } }); if (!unsubscribed) { panel.subscriptionsColor = colors; // console.log(panel.divElement.id); // console.log(panel.subscriptionsColor); colors = []; $.each(panelToUnsubscribe.subscribers, function(i, field) { if (field != panel.divElement.id) { aux.push(field); } }); panelToUnsubscribe.subscribers = aux; $.each(panelToUnsubscribe.subscriptionsColor, function(i, field) { colors.push(field); }); if (panelToUnsubscribe.subscribers.length == 0) { if (panelToUnsubscribe.subscriptions.length == 0) { $("#" + panelToUnsubscribe.divElement.id + "-subscribersMarker").hide(); } } else { // colors.push(panelToUnsubscribe.markerColor); } panelToUnsubscribe.subscriptionsColor = colors; // console.log(panelToUnsubscribe.divElement.id); // console.log(panelToUnsubscribe.subscriptionsColor); aux = []; $.each(panel.subscriptions, function(i, field) { if (panelToUnsubscribe.divElement.id == field.topic) { field.unsubscribe(); } else { aux.push(field); } }); panel.subscriptions = aux; if (panel.subscriptions.length == 0 && panel.subscribers.length == 0) { $("#" + panel.divElement.id + "-subscribersMarker").hide(); } } } this.setupOptionsPanel = function() { //var possibleSubscribers = []; //$.each(componentsRegistry, function(i, field){ // if (field.divElement.id != panel.divElement.id){ // var object = {}; // object.subscriptions = field.subscriptions; // object.id = field.divElement.id; // possibleSubscribers.push(object); // } //}); //var aux = false; //$.each(possibleSubscribers, function(i, field){ // aux = false; // $.each(panel.subscriptions, function(j, subscription){ // if (field.id == subscription.topic){ // aux = true; // } // }); // field.subscribed = aux; // aux = false; // $.each(field.subscriptions, function(i, subscription){ // if (subscription.topic == panel.divElement.id){ // aux = true; // } // }); // field.subscriptor = aux; //}); //panel.options.possibleSubscribers = possibleSubscribers; if (!panel.options.manifest) { $("#" + panel.divElement.id + "-modal-body").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); xhr = $.getJSON(options.serverUrl.replace("snomed", "") + "server/releases", function(result) { // nothing }).done(function(result) { $.each(result, function(i, field) { manifests.push(field); if (field.databaseName == options.edition) { panel.options.manifest = field; } }); var context = { options: panel.options, divElementId: panel.divElement.id }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('ifIn', function(elem, list, options) { if (list.indexOf(elem) > -1) { return options.fn(this); } return options.inverse(this); }); $("#" + panel.divElement.id + "-modal-body").html(JST["views/conceptDetailsPlugin/options.hbs"](context)); }); } else { var context = { options: panel.options, divElementId: panel.divElement.id }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('ifIn', function(elem, list, options) { if (list.indexOf(elem) > -1) { return options.fn(this); } return options.inverse(this); }); $("#" + panel.divElement.id + "-modal-body").html(JST["views/conceptDetailsPlugin/options.hbs"](context)); } } this.readOptionsPanel = function() { panel.options.displaySynonyms = $("#" + panel.divElement.id + "-displaySynonymsOption").is(':checked'); panel.options.showIds = $("#" + panel.divElement.id + "-displayIdsOption").is(':checked'); panel.options.displayChildren = $("#" + panel.divElement.id + "-childrenOption").is(':checked'); panel.options.hideNotAcceptable = $("#" + panel.divElement.id + "-hideNotAcceptableOption").is(':checked'); panel.options.displayInactiveDescriptions = $("#" + panel.divElement.id + "-displayInactiveDescriptionsOption").is(':checked'); panel.options.diagrammingMarkupEnabled = $("#" + panel.divElement.id + "-diagrammingMarkupEnabledOption").is(':checked'); panel.options.selectedView = $("#" + panel.divElement.id + "-relsViewOption").val(); panel.options.langRefset = []; $.each($("#" + panel.divElement.id).find(".langOption"), function(i, field) { if ($(field).is(':checked')) { panel.options.langRefset.push($(field).val()); } }); //console.log(panel.options.langRefset); //panel.options.langRefset = $("#" + panel.divElement.id + "-langRefsetOption").val(); panel.options.displayChildren = $("#" + panel.divElement.id + "-displayChildren").is(':checked'); //$.each(panel.options.possibleSubscribers, function (i, field){ // field.subscribed = $("#" + panel.divElement.id + "-subscribeTo-" + field.id).is(':checked'); // field.subscriptor = $("#" + panel.divElement.id + "-subscriptor-" + field.id).is(':checked'); // var panelToSubscribe = {}; // $.each(componentsRegistry, function(i, panelS){ // if (panelS.divElement.id == field.id){ // panelToSubscribe = panelS; // } // }); // if (field.subscribed){ // panel.subscribe(panelToSubscribe); // }else{ // panel.unsubscribe(panelToSubscribe); // } // if (field.subscriptor){ // panelToSubscribe.subscribe(panel); // }else{ // panelToSubscribe.unsubscribe(panel); // } //}); $.each(componentsRegistry, function(i, field) { if (field.loadMarkers) field.loadMarkers(); }); panel.updateCanvas(); } } function updateCD(divElementId, conceptId) { $.each(componentsRegistry, function(i, field) { //console.log(field.divElement.id + ' == ' + divElementId.id); if (field.divElement.id == divElementId) { field.conceptId = conceptId; field.updateCanvas(); channel.publish(field.divElement.id, { term: field.term, conceptId: field.conceptId, module: field.module, source: field.divElement.id }); } }); $('.history-button').popover('hide'); } //function cancelSubscription(divElementId1, divElementId2) { // var d1; // var d2; // $.each(componentsRegistry, function(i, field) { // if (field.divElement.id == divElementId1) { // d1 = field; // } else if (field.divElement.id == divElementId2) { // d2 = field; // } // }); // d1.unsubscribe(d2); // $(d2.divElement).find('.linker-button').popover('toggle'); //} function getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.round(Math.random() * 15)]; } return color; } (function($) { $.fn.addConceptDetails = function(conceptId, options) { this.filter("div").each(function() { var cd = new conceptDetails(this, conceptId, options); cd.setupCanvas(); }); }; }(jQuery)); $(document).keypress(function(event) { if (event.which == '13') { event.preventDefault(); } }); /** * Updated by rda on 2017-12-15. */ countryIcons = { '999000041000000102': 'gb', '999000011000000103': 'gb', '999000021000000109': 'gb', '999000031000000106': 'gb', '450829007': 'es', '11000221109': 'ar', '11000220105': 'ie', "900000001000122104": "es-ES", '731000124108': 'us', '5991000124107': 'us', '161771000036108': 'au', '32570231000036109': 'au', '32506021000036107': 'au', '32570491000036106': 'au', '45991000052106': 'se', '554471000005108': 'dk', '9999999998': 'gmdn', '466707005': 'mdp', '11000146104': 'nl', '20621000087109': 'ca', '19481000087107': 'ca', '20611000087101': 'ca', '22091000087100': 'ca', '5641000179103': 'uy', '5631000179106': 'uy', '11000172109': 'be', '21000210109': 'nz', '51000202101': 'no' }; Handlebars.registerHelper('countryIcon', function(moduleId) { return countryIcons[moduleId]; }); function drawConceptDiagram (concept, div, options, panel) { var svgIsaModel = []; var svgAttrModel = []; var axioms = []; if (options.selectedView == "stated") { $.each(concept.statedRelationships, function(i, field) { if (field.active == true) { if (field.type.conceptId == 116680003) { svgIsaModel.push(field); } else { svgAttrModel.push(field); } } }); $.each(concept.gciAxioms, function (i, axiom) { var axiomToPush = {}; axiomToPush.relationships = []; axiomToPush.type = 'gci'; $.each(axiom.relationships, function (i, field) { if (field.type.conceptId === '116680003') { axiomToPush.relationships.push(field); } else { axiomToPush.relationships.push(field); } }); axioms.push(axiomToPush); }); $.each(concept.classAxioms, function (i, axiom) { var axiomToPush = { relationships : [], type : 'add', definitionStatus: axiom.definitionStatus }; $.each(axiom.relationships, function (i, field) { if (field.type.conceptId === '116680003') { axiomToPush.relationships.push(field); } else { axiomToPush.relationships.push(field); } }); axioms.push(axiomToPush); }); } else { if (concept.relationships) { $.each(concept.relationships, function (i, field) { if (field.active == true) { if (field.type.conceptId == 116680003) { svgIsaModel.push(field); } else { svgAttrModel.push(field); } } }); } } var context = { divElementId: div.attr('id') }; //console.log(context); div.html(JST["views/conceptDetailsPlugin/tabs/details/diagram.hbs"](context)); var parentDiv = $("#" + div.attr('id') + "-diagram-body"); var height = 350; var width = 700; $.each(svgIsaModel, function (i, field) { height = height + 50; width = width + 80; }); $.each(svgAttrModel, function (i, field) { height = height + 65; width = width + 110; }); if(options.selectedView === 'stated'){ $.each(concept.classAxioms, function (i, axiom) { height = height + 40; width = width + 80; $.each(axiom.relationships, function (i, field) { height = height + 55; width = width + 110; }); }); $.each(concept.gciAxioms, function (i, axiom) { height = height + 40; width = width + 80; $.each(axiom.relationships, function (i, field) { height = height + 55; width = width + 110; }); }); } // parentDiv.svg('destroy'); parentDiv.svg({ settings: { width: width + 'px', height: height + 'px'}}); var svg = parentDiv.svg('get'); loadDefs(svg); var x = 10; var y = 10; var maxX = 10; var sctClass = ""; if (concept.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } //console.log("In draw: " + concept.defaultTerm + " " + concept.conceptId + " " + sctClass); var rect1 = drawSctBox(svg, x, y, concept.fsn, concept.conceptId, sctClass); x = x + 90; y = y + rect1.getBBox().height + 40; if(options.selectedView === 'stated' && svgIsaModel && svgIsaModel.length > 0 || options.selectedView != 'stated'){ var circle1; if (concept.definitionStatus == "PRIMITIVE") { circle1 = drawSubsumedByNode(svg, x, y); } else { circle1 = drawEquivalentNode(svg, x, y); } connectElements(svg, rect1, circle1, 'bottom-50', 'left'); x = x + 55; var circle2 = drawConjunctionNode(svg, x, y); connectElements(svg, circle1, circle2, 'right', 'left', 'LineMarker'); x = x + 40; y = y - 18; } if (!svgIsaModel || svgIsaModel.length === 0) { x = x + 20; y = y + 3; } maxX = ((maxX < x) ? x : maxX); // load stated parents sctClass = "sct-defined-concept"; $.each(svgIsaModel, function(i, relationship) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectParent = drawSctBox(svg, x, y, relationship.target.fsn.term, relationship.target.conceptId, sctClass); // $("#" + rectParent.id).css({"top": // (rectParent.outerHeight()/2) + "px"}); connectElements(svg, circle2, rectParent, 'center', 'left', 'ClearTriangle'); y = y + rectParent.getBBox().height + 25; maxX = ((maxX < x + rectParent.getBBox().width + 50) ? x + rectParent.getBBox().width + 50 : maxX); }); // load ungrouped attributes var maxRoleNumber = 0; $.each(svgAttrModel, function(i, relationship) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } if (relationship.groupId == 0) { var rectAttr = drawSctBox(svg, x, y, relationship.type.fsn.term,relationship.type.conceptId, "sct-attribute"); connectElements(svg, circle2, rectAttr, 'center', 'left'); var rectTarget = drawSctBox(svg, x + rectAttr.getBBox().width + 50, y, relationship.target.fsn.term,relationship.target.conceptId, sctClass); connectElements(svg, rectAttr, rectTarget, 'right', 'left'); y = y + rectTarget.getBBox().height + 25; maxX = ((maxX < x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50) ? x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50 : maxX); } else { if (relationship.groupId > maxRoleNumber) { maxRoleNumber = relationship.groupId; } } }); y = y + 15; for (var i = 1; i <= maxRoleNumber; i++) { var groupNode = drawAttributeGroupNode(svg, x, y); connectElements(svg, circle2, groupNode, 'center', 'left'); var conjunctionNode = drawConjunctionNode(svg, x + 55, y); connectElements(svg, groupNode, conjunctionNode, 'right', 'left'); $.each(svgAttrModel, function(m, relationship) { if (relationship.groupId == i) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectRole = drawSctBox(svg, x + 85, y - 18, relationship.type.fsn.term, relationship.type.conceptId,"sct-attribute"); connectElements(svg, conjunctionNode, rectRole, 'center', 'left'); var rectRole2 = drawSctBox(svg, x + 85 + rectRole.getBBox().width + 30, y - 18, relationship.target.fsn.term,relationship.target.conceptId, sctClass); connectElements(svg, rectRole, rectRole2, 'right', 'left'); y = y + rectRole2.getBBox().height + 25; maxX = ((maxX < x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50) ? x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50 : maxX); } }); } $.each(axioms, function (i, axiom) { console.log(axiom); x = 100; y = y -3; var circle1; if(axiom.type === "gci"){ circle1 = drawSubsumesNode(svg, x, y); } else if(axiom.type !== "gci" && axiom.definitionStatus === "FULLY_DEFINED"){ circle1 = drawEquivalentNode(svg, x, y); } else{ console.log('drawing 2'); circle1 = drawSubsumedByNode(svg, x, y); } connectElements(svg, rect1, circle1, 'bottom-50', 'left'); x = x + 55; var circle2 = drawConjunctionNode(svg, x, y); connectElements(svg, circle1, circle2, 'right', 'left', 'LineMarker'); x = x + 40; y = y - 18; maxX = ((maxX < x) ? x : maxX); var axiomRoleNumber = 0; $.each(axiom.relationships, function (i, relationship) { console.log('here'); if(relationship.type.conceptId === '116680003'){ if (relationship.target.definitionStatus === "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectParent = drawSctBox(svg, x, y, relationship.target.fsn.term, relationship.target.conceptId, sctClass); // $("#" + rectParent.id).css({"top": // (rectParent.outerHeight()/2) + "px"}); connectElements(svg, circle2, rectParent, 'center', 'left', 'ClearTriangle'); y = y + rectParent.getBBox().height + 25; maxX = ((maxX < x + rectParent.getBBox().width + 50) ? x + rectParent.getBBox().width + 50 : maxX); } else{ if (relationship.target.definitionStatus === "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } if (relationship.groupId === 0) { var rectAttr = drawSctBox(svg, x, y, relationship.type.fsn.term, relationship.type.conceptId, "sct-attribute"); connectElements(svg, circle2, rectAttr, 'center', 'left'); var rectTarget = drawSctBox(svg, x + rectAttr.getBBox().width + 50, y, relationship.target.fsn.term, relationship.target.conceptId, sctClass); connectElements(svg, rectAttr, rectTarget, 'right', 'left'); y = y + rectTarget.getBBox().height + 25; maxX = ((maxX < x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50) ? x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50 : maxX); } else { if (relationship.groupId > axiomRoleNumber) { axiomRoleNumber = relationship.groupId; } } } }); y = y + 15; for (var i = 1; i <= axiomRoleNumber; i++) { var groupNode = drawAttributeGroupNode(svg, x, y); connectElements(svg, circle2, groupNode, 'center', 'left'); var conjunctionNode = drawConjunctionNode(svg, x + 55, y); connectElements(svg, groupNode, conjunctionNode, 'right', 'left'); $.each(axiom.relationships, function (m, relationship) { if (relationship.groupId === i) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectRole = drawSctBox(svg, x + 85, y - 18, relationship.type.fsn.term, relationship.type.conceptId, "sct-attribute"); connectElements(svg, conjunctionNode, rectRole, 'center', 'left'); var rectRole2 = drawSctBox(svg, x + 85 + rectRole.getBBox().width + 30, y - 18, relationship.target.fsn.term, relationship.target.conceptId, sctClass); connectElements(svg, rectRole, rectRole2, 'right', 'left'); y = y + rectRole2.getBBox().height + 25; maxX = ((maxX < x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50) ? x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50 : maxX); } }); } }); var svgCode = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' + parentDiv.html(); svgCode = svgCode.substr(0, svgCode.indexOf("svg") + 4) + ' xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://web.resource.org/cc/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" ' + svgCode.substr(svgCode.indexOf("svg") + 4) svgCode = svgCode.replace('width="1000px" height="2000px"', 'width="' + maxX + '" height="' + y + '"'); var b64 = Base64.encode(svgCode); $("#" + div.attr('id') + "-download-button").disableTextSelect(); $("#" + div.attr('id') + "-progress-button").disableTextSelect(); $("#" + div.attr('id') + "-png-button").disableTextSelect(); $("#" + div.attr('id') + "-svg-button").disableTextSelect(); $("#" + div.attr('id') + "-download-button").removeClass('disabled'); $("#" + div.attr('id') + "-download-button").unbind().click(function(event) { $("#" + div.attr('id') + "-download-button").hide(); $("#" + div.attr('id') + "-progress-button").show(); $.post(options.serverUrl.replace("snomed", "") + "util/svg2png", { svgContent: svgCode}).done(function( response ) { //console.log(response); $("#" + div.attr('id') + "-progress-button").hide(); $("#" + div.attr('id') + "-png-button").show(); $("#" + div.attr('id') + "-svg-button").show(); $("#" + div.attr('id') + "-png-button").unbind().click(function(event) { window.open(options.serverUrl.replace("snomed", "") + response); }); $("#" + div.attr('id') + "-svg-button").unbind().click(function(event) { window.open(options.serverUrl.replace("snomed", "") + response.replace(".png", ".svg")); }); //$(div).prepend($("<a href-lang='image/svg+xml' href=options.serverUrl.replace("snomed", "")+response+"' download='diagram.png'>Download as PNG</a>&nbsp;&nbsp;&nbsp;")); }).fail(function() { //console.log("Error"); }); }); if (panel.options.selectedView == "stated") { $("#" + div.attr('id') + '-stated-button-d').unbind(); $("#" + div.attr('id') + '-inferred-button-d').unbind(); $("#" + div.attr('id') + '-stated-button-d').addClass("btn-primary"); $("#" + div.attr('id') + '-stated-button-d').removeClass("btn-default"); $("#" + div.attr('id') + '-inferred-button-d').addClass("btn-default"); $("#" + div.attr('id') + '-inferred-button-d').removeClass("btn-primary"); $("#" + div.attr('id') + '-inferred-button-d').click(function (event) { panel.options.selectedView = "inferred"; panel.updateCanvas(); }); } else { $("#" + div.attr('id') + '-stated-button-d').unbind(); $("#" + div.attr('id') + '-inferred-button-d').unbind(); $("#" + div.attr('id') + '-inferred-button-d').addClass("btn-primary"); $("#" + div.attr('id') + '-inferred-button-d').removeClass("btn-default"); $("#" + div.attr('id') + '-stated-button-d').addClass("btn-default"); $("#" + div.attr('id') + '-stated-button-d').removeClass("btn-primary"); $("#" + div.attr('id') + '-stated-button-d').click(function (event) { panel.options.selectedView = "stated"; panel.updateCanvas(); }); } //$(div).prepend($("<a href-lang='image/svg+xml' href='data:image/svg+xml;base64,\n"+b64+"' download='diagram.svg'>Download as SVG</a>")); } function saveAsPng(svg) { //Create PNG Image //Get the svg //Create the canvas element var canvas = document.createElement('canvas'); canvas.id = "canvas"; document.body.appendChild(canvas); //Load the canvas element with our svg canvg(document.getElementById('canvas'), svg); //Save the svg to png Canvas2Image.saveAsPNG(canvas); //Clear the canvas canvas.width = canvas.width; } !function ($) { /* ======================= * Popover jQuery Plugin * ======================= * Current version: v1.0.0, Last updated: 01-28-2013 * Description: Cross-browser, mobile compatible popover. * * Author: Jordan Kelly * Github: https://github.com/FoundOPS/popover * * Compatible browsers: IE 9+, Chrome ?+, FF 3.6+, Android 2.3+, iOS 4+ * * jQuery functions: * $(selector).popover([methods] or [config]); * $(selector).optionsPopover([methods] or [config]); * * Config parameters: Example usage - $(selector).popover({..., fontColor: "#000", ...}); * id - When passed for initial menu, id must be the same as the id/class used in selector. * eg) "#popoverButton" * * title - Title to be displayed on header. * * contents - popover: An html string to be inserted. * - optionsPopover: An array of row data. * //TODO: Document more. * * backgroundColor - Sets the background color for all popups. Accepts hex and color keywords. * eg) "#000000", "black", etc. * * fontColor - Sets the font color for all popups. Accepts hex and color keywords. * eg) "#000000", "black", etc. * * borderColor - Sets the border color for all popups. Accepts hex and color keywords. * eg) "#000000", "black", etc. * * keepData - Boolean that indicates if header and content should be cleared/set on visible. * WARNING: MAY BE REMOVED IN FUTURE VERSIONS. * eg) truthy or falsesy values * * childToAppend - A documentFragment or dom element to be appended after content is set. * WARNING: MAY BE REMOVED IN FUTURE VERSIONS. * eg) * * onCreate - A function to be called after popover is created. * eg) function(){ console.log("popover has been created!"); } * * onVisible - A function to be called after popover is visible. * eg) function(){ console.log("popover is visible!"); } * * disableHeader - Boolean that indicates if a header should not be used on parent listener. * eg) Truthy/Falsey values * * Methods: Example usage - $(selector).popover("methodName", argument1, argument2 ...); * [Internal] - Functions needed for setup/initialization. * _popoverInit - Internal function used to setup popover. * Arguments: options_config, popover_instance * _optionsPopoverInit - Internal function used to setup optionsPopover. * Arguments: options_config, popover_instance * [Public] * disableHeader - Function used to disable header for a popover instance. * Arguments: popover_instance * enableHeader - Function used to enable header for a popover instance. * Arguments: popover_instance * lockPopover - Function used to lock all popovers. Prevents popover from opening/closing. * Arguments: none * unlockPopover - Function used to unlock all popovers. * Arguments: none * addMenu - Function used to add a new menu. Menus can be accessed by all popover instances. * Arguments: id, title, contents * closePopover - Function used to close popover. * Arguments: none * [Private] - Note: Only use if you have to. * _getPopoverClass - Function used to return internal Popover class. * Arguments: none * * Triggers: Currently all events are namespaced under popover.* This may change in future versions. * popover.created - Fired when popup is created and placed in DOM. * popover.listenerClicked - Fired when root popup listener is clicked. * popover.action - Fired when a menu changes. * Arguments: DOM Element causing action. * popover.visible - Fired when popover is visible. * popover.updatePositions - Fired when left and top positions are updated. * popover.resize - Fired when popover is resized. * popover.closing - Fired before popover closes. * popover.setContent - Fired after popover's contenet is set. ================================================================================================================*/ var methods = { _init: function(options, popover) { //Theme modifiers if(typeof(options.backgroundColor) !== 'undefined'){ Popover.setBackgroundColor(options.backgroundColor); } if(typeof(options.fontColor) !== 'undefined'){ Popover.setFontColor(options.fontColor); } if(typeof(options.borderColor) !== 'undefined'){ Popover.setBorderColor(options.borderColor); } //Functionality modifiers //TODO: Rename disableBackButton option. if(typeof(options.disableBackButton) !== "undefined"){ if(options.disableBackButton === true){ popover.disableBackButton(); }else if(options.disableBackButton === false){ popover.enableBackButton(); } } if(typeof(options.enableBackButton) !== "undefined"){ if(options.enableBackButton === true){ popover.enableBackButton(); }else if(options.enableBackButton === false){ popover.disableBackButton(); } } if(typeof(options.disableHeader) !== 'undefined'){ if(options.disableHeader === true){ popover.disableHeader(); }else if(options.disableHeader === false){ popover.enableHeader(); } } if(typeof(options.keepData) !== 'undefined'){ popover.keepData(options.keepData); } if(typeof(options.childToAppend) !== 'undefined'){ popover.childToAppend = options.childToAppend; } //Callbacks if(typeof(options.onCreate) !== 'undefined'){ popover._onCreate = options.onCreate; } if(typeof(options.onVisible) !== 'undefined'){ popover._onVisible = options.onVisible; } Popover.addMenu(options.id, options.title, options.contents); }, _popoverInit: function(options) { var popover = new Popover(this.selector); methods._init(options, popover); return popover; }, _optionsPopoverInit: function (options) { var popover = new OptionsPopover(this.selector); methods._init(options, popover); return popover; }, //Requires instance to be passed. disableHeader: function(popover) { popover.disableHeader(); }, //Requires instance to be passed. enableHeader: function(popover) { popover.enableHeader(); }, //Static functions lockPopover: function() { Popover.lockPopover(); }, unlockPopover: function() { Popover.unlockPopover(); }, addMenu: function (menu) { Popover.addMenu(menu.id, menu.title, menu.contents); }, closePopover: function () { Popover.closePopover(); }, _getPopoverClass: function() { return Popover; } }; $.fn.optionsPopover = function (method) { // Create some defaults, extending them with any options that were provided //var settings = $.extend({}, options); // Method calling logic if (methods[method]) { return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods._optionsPopoverInit.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.optionsPopover'); } return this.each(function () {}); }; $.fn.ppopover = function (method) { // Create some defaults, extending them with any options that were provided //var settings = $.extend({}, options); // Method calling logic if (methods[method]) { return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods._popoverInit.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.popover'); } return this.each(function () {}); }; //////////////////////////////////////////////////////////// // Popover Block //////////////////////////////////////////////////////////// /** Popover CONSTRUCTOR **/ function Popover(popoverListener) { this.constructor = Popover; //Set this popover's number and increment Popover count. this.popoverNumber = ++Popover.popoverNum; //Class added to detect clicks on primary buttons triggering popovers. this.popoverListenerID = "popoverListener"+this.popoverNumber; this.isHeaderDisabled = true; this.isDataKept = false; this.hasBeenOpened = false; var thisPopover = this; var listenerElements = $(popoverListener); listenerElements.addClass(this.popoverListenerID); listenerElements.css("cursor", "pointer"); listenerElements.click(function (e) { thisPopover.toggleVisible(e, $(this)); $(document).trigger("popover.listenerClicked"); }); } Popover.prototype.disableHeader = function() { this.isHeaderDisabled = true; }; Popover.prototype.enableHeader = function() { this.isHeaderDisabled = false; }; Popover.prototype.disablePopover = function() { this.isDisabled = true; }; Popover.prototype.enablePopover = function() { this.isDisabled = false; }; Popover.prototype.keepData = function(bool){ this.isDataKept = bool; }; Popover.prototype.appendChild = function(){ var child = this.childToAppend; if(!child)return; $("#popoverContent")[0].appendChild(child); }; Popover.prototype.toggleVisible = function (e, clicked) { Popover.lastPopoverClicked = this; var clickedDiv = $(clicked); if (!clickedDiv) { //console.log("ERROR: No element clicked!"); return; } var popoverWrapperDiv = $("#popoverWrapper"); if (popoverWrapperDiv.length === 0) { //console.log("Popover not initialized; initializing."); popoverWrapperDiv = this.createPopover(); if (popoverWrapperDiv.length === 0) { //console.log("ERROR: Failed to create Popover!"); return; } } //TODO: In the future, add passed id to selected div's data-* or add specific class. var id = clickedDiv.attr("id"); var identifierList = clickedDiv.attr('class').split(/\s+/); //NOTE: identifierList contains the clicked element's id and class names. This is used to find its // associated menu. The next version will have a specialized field to indicate this. identifierList.push(id); //console.log("List: "+identifierList); //TODO: Fix repetition. if ($("#popover").is(":visible") && Popover.lastElementClick) { if (clickedDiv.is("#" + Popover.lastElementClick)) { //console.log("Clicked on same element!"); //console.log("Last clicked: " + Popover.lastElementClick); Popover.closePopover(); return; } //console.log("Clicked on different element!"); Popover.closePopover(); } //Blocking statement that waits until popover closing animation is complete. $("#popover").promise().done(function () {}); //If popover is locked, don't continue actions. if(Popover.isLocked||this.isDisabled)return; //Update content this.populate(identifierList); clickedDiv.trigger("popover.action", clickedDiv); if(Popover.backgroundColor){ $("#popoverHeader").css("backgroundColor", Popover.backgroundColor); $("#popoverContent").css("backgroundColor", Popover.backgroundColor); } if(Popover.fontColor){ $("#popover").css("color", Popover.fontColor); //TODO: Trigger color change event and move to OptionsPopover. $("#popover a").css("color", Popover.fontColor); } if(Popover.borderColor){ $("#popoverHeader").css("border-color", Popover.borderColor); $("#popoverContent").css("border-color", Popover.borderColor); $(".popoverContentRow").css("border-color", Popover.borderColor); } //Make popover visible $("#popover").stop(false, true).fadeIn('fast'); $("#popoverWrapper").css("visibility", "visible"); $("#popover").promise().done(function () {}); popoverWrapperDiv.trigger("popover.visible"); if(this._onVisible){ //console.log("LOG: Executing onVisible callback."); this._onVisible(); } if((this.isDataKept && !this.hasBeenOpened) || (!this.isDataKept)){ var child = this.childToAppend; if(child){ this.appendChild(child); } } this.hasBeenOpened = true; //Update left, right and caret positions for popover. //NOTE: Must be called after popover.visible event, in order to trigger jspScrollPane update. Popover.updatePositions(clickedDiv); Popover.lastElementClick = clickedDiv.attr("id"); }; Popover.updatePositions = function(target){ Popover.updateTopPosition(target); Popover.updateLeftPosition(target); $(document).trigger("popover.updatePositions"); }; Popover.updateTopPosition = function(target){ var top = Popover.getTop(target); $("#popoverWrapper").css("padding-top", top + "px"); }; Popover.updateLeftPosition = function(target){ var offset = Popover.getLeft(target); $("#popoverWrapper").css("left", offset.popoverLeft); Popover.setCaretPosition(offset.targetLeft - offset.popoverLeft + Popover.padding); }; //Function returns the left offset of the popover and target element. Popover.getLeft = function (target) { var popoverWrapperDiv = $("#popoverWrapper"); Popover.currentTarget = target; var targetLeft = target.offset().left + target.outerWidth() / 2; var rightOffset = targetLeft + popoverWrapperDiv.outerWidth() / 2; var offset = targetLeft - popoverWrapperDiv.outerWidth() / 2 + Popover.padding + 1; var windowWidth = $(window).width(); Popover.offScreenX = false; if (offset < 0) { Popover.offScreenX = true; offset = Popover.padding; } else if (rightOffset > windowWidth) { Popover.offScreenX = true; offset = windowWidth - popoverWrapperDiv.outerWidth(); } //Returns left offset of popover from window. return {targetLeft: targetLeft, popoverLeft: offset}; }; Popover.getTop = function(target){ var caretHeight = $("#popoverArrow").height(); //TODO: Make more readable. //If absolute position from mobile css, don't offset from scroll. var scrollTop = ($("#popoverWrapper").css("position")==="absolute")?0:$(window).scrollTop(); var targetTop = target.offset().top - scrollTop; var targetBottom = targetTop + target.outerHeight(); var popoverTop = targetBottom + caretHeight; var windowHeight = $(window).height(); var popoverContentHeight = $("#popoverContent").height(); var popoverHeight = popoverContentHeight + $("#popoverHeader").outerHeight() + caretHeight; Popover.above = false; Popover.offScreenY = false; //If popover is past the bottom of the screen. //else if popover is above the top of the screen. if (windowHeight < targetBottom + popoverHeight) { Popover.offScreenY = true; //If there is room above, move popover above target //else keep popover bottom at bottom of screen. if(targetTop >= popoverHeight){ popoverTop = targetTop - popoverHeight; Popover.above = true; }else{ popoverTop = windowHeight - popoverHeight; } } else if (popoverTop < 0) { Popover.offScreenY = true; popoverTop = Popover.padding + caretHeight; } /* //Debug logs console.log("------------------------------------------------------------"); console.log("Caret Height: " + caretHeight); console.log("TargetTop: " + targetTop); console.log("Popover Cont Height: " + popoverContentHeight); console.log("Cont Height: " + $("#popoverContent").height()); console.log("Header Height: " + $("#popoverHeader").outerHeight()); console.log("targetBottom: " + targetBottom); console.log("popoverHeight: " + popoverHeight); console.log("popoverBottom: " + (targetBottom + popoverHeight)); console.log("Popover Height: " + $("#popover").height()); console.log("PopoverWrapper Height: " + $("#popoverWrapper").height()); console.log("PopoverWrapper2 Height: " + $("#popoverWrapper").height(true)); console.log("popoverTop: " + popoverTop); console.log("windowHeight: " + windowHeight); console.log("offScreenY: " + Popover.offScreenY); console.log("Popover.above: " + Popover.above); console.log("\n"); */ return popoverTop; }; Popover.setCaretPosition = function(offset){ //console.log("LOG: Setting caret position."); var caretPos = "50%"; var caret = $("#popoverArrow"); if (Popover.offScreenX) { caretPos = offset; } //Moves carrot on popover div. caret.css("left", caretPos); //console.log("LOG: Popover.above: "+Popover.above); if(Popover.above){ var popoverHeight = $("#popoverContent").outerHeight() - 4; $("#popoverArrow").css("margin-top", popoverHeight+"px") .addClass("flipArrow") .html("▼"); }else{ $("#popoverArrow").css("margin-top", "") .removeClass("flipArrow") .html("▲"); } Popover.caretLeftOffset = caretPos; }; // createPopover: Prepends popover to dom Popover.prototype.createPopover = function () { //Creates popover div that will be populated in the future. var popoverWrapperDiv = $(document.createElement("div")); popoverWrapperDiv.attr("id", "popoverWrapper"); var s = "<div id='popover'>" + "<div id='popoverArrow'>▲</div>" + "<div id='currentPopoverAction' style='display: none;'></div>" + "<div id='popoverContentWrapper'>" + "<div id='popoverContent'></div>" + "</div>" + "</div>"; popoverWrapperDiv.html(s); popoverWrapperDiv.find("#popover").css("display", "none"); //Appends created div to page. $("body").prepend(popoverWrapperDiv); //Window resize listener to check if popover is off screen. $(window).on('resize', function () { if ($("#popover").is(":visible")) { Popover.updatePositions(Popover.currentTarget); } var popoverWrapperDiv = $("#popoverWrapper"); if(popoverWrapperDiv.css("position")==="absolute"){ popoverWrapperDiv.css("height", $(document).height()); }else{ popoverWrapperDiv.css("height", ""); } }); //Click listener to detect clicks outside of popover $('html') .on('click touchend', function (e) { var clicked = $(e.target); //TODO: Return if not visible. var popoverHeaderLen = clicked.parents("#popoverHeader").length + clicked.is("#popoverHeader") ? 1 : 0; var popoverContentLen = (clicked.parents("#popoverContentWrapper").length && !clicked.parent().is("#popoverContentWrapper")) ? 1 : 0; var isListener = clicked.parents("."+Popover.lastPopoverClicked.popoverListenerID).length + clicked.is("."+Popover.lastPopoverClicked.popoverListenerID) ? 1 : 0; if (popoverHeaderLen === 0 && popoverContentLen === 0 && isListener === 0) { Popover.closePopover(); } } ); var popoverContentWrapperDiv = $("#popoverContentWrapper"); var throttleTimeout; $(window).bind('resize', function () { if ($.browser.msie) { if (!throttleTimeout) { throttleTimeout = setTimeout(function () { popoverContentWrapperDiv.trigger("popover.resize"); throttleTimeout = null; }, 50 ); } } else { popoverContentWrapperDiv.trigger("popover.resize"); } }); popoverContentWrapperDiv.trigger("popover.created"); if(this._onCreate)this._onCreate(); //Function also returns the popover div for ease of use. return popoverWrapperDiv; }; //Closes the popover Popover.closePopover = function () { if(Popover.isLocked)return; Popover.lastElementClick = null; $(document).trigger("popover.closing"); Popover.history = []; $("#popover").stop(false, true).fadeOut('fast'); $("#popoverWrapper").css("visibility", "hidden"); }; Popover.getAction = function () { return $("#currentPopoverAction").html(); }; Popover.setAction = function (id) { $("#currentPopoverAction").html(id); }; Popover.prototype.disableBackButton = function(){ this.isBackEnabled = false; }; Popover.prototype.enableBackButton = function(){ this.isBackEnabled = true; }; Popover.prototype.previousPopover = function(){ Popover.history.pop(); if (Popover.history.length <= 0) { Popover.closePopover(); return; } var menu = Popover.history[Popover.history.length - 1]; this.populateByMenu(menu); }; //Public setter function for static var title and sets title of the html popover element. Popover.setTitle = function (t) { Popover.title = t; $("#popoverTitle").html(t); }; // Public getter function that returns a popover menu. // Returns: Popover menu object if found, null if not. // Arguments: id - id of menu to lookup Popover.getMenu = function (id) { //Searches for a popover data object by the id passed, returns data object if found. var i; for (i = 0; i < Popover.menus.length; i += 1) { //console.log("LOG: getMenu - Popover.menus["+i+"]: "+Popover.menus[i].id); if (Popover.menus[i].id === id) { return Popover.menus[i]; } } //Null result returned if popover data object is not found. //console.log("LOG: getMenu - No data found, returning null."); return null; }; Popover.addMenu = function (id, title, contents) { Popover.menus.push({'id': id, 'title': title, 'contents': contents}); }; Popover.prototype.populateByMenu = function(menu){ $(document).trigger('popover.populating'); this.lastContentHeight = Popover.getPopoverContentHeight(); if(!this.isDataKept){ this.clearData(); } //If data is kept, header and other content will still be in dom, so don't do either. if(!this.isHeaderDisabled && !this.isDataKept) { this.insertHeader(); }else{ this.removeHeader(); } var popoverDisplay = $("#popover").css("display"); if(!this.isDataKept || !this.hasBeenOpened)this.setData(menu); this.currentContentHeight = Popover.getPopoverContentHeight(); if(Popover.above && popoverDisplay!=="none"){ var oldPopoverTop = parseInt($("#popoverWrapper").css("padding-top"), 10); var contentHeightDelta = this.currentContentHeight - this.lastContentHeight; var popoverTop = oldPopoverTop - (contentHeightDelta); $("#popoverWrapper").css("padding-top", popoverTop + "px"); Popover.setCaretPosition(Popover.caretLeftOffset); } return true; }; //Public void function that populates setTitle and setContent with data found by id passed. Popover.prototype.populate = function(identifierList){ //console.log(identifierList); var newMenu = null; var i=0; for(i; i<identifierList.length; i++){ newMenu = Popover.getMenu(identifierList[i]); if(newMenu){ //console.log("Found menu! id: "+identifierList[i]); break; } } if (!newMenu) { //console.log("ID not found."); return false; } Popover.history.push(newMenu); return this.populateByMenu(newMenu); }; Popover.getPopoverContentHeight = function(){ var popoverDisplay = $("#popover").css("display"); $("#popover").show(); var popoverHeight = $("#popoverContent").height(); $("#popover").css("display",popoverDisplay); return popoverHeight; }; Popover.prototype.insertHeader = function (){ var header = "<div id='popoverHeader'>" + "<div id='popoverTitle'></div>" + "<a id='popoverClose'><span id='popoverCloseIcon'>✕</span></a>" + "</div>"; $("#popoverContentWrapper").before(header); //Create back button //Don't create back button or listener if disabled. if(this.isBackEnabled){ //console.log("LOG: Creating back button."); var thisPopover = this; $("#popoverHeader").prepend("<a id='popoverBack'><span id='popoverBackIcon'>◄</span></a>"); $("#popoverBack").on("click", function () { thisPopover.previousPopover(); }); } //Click listener for popover close button. $("#popoverClose").on("click", function () { Popover.closePopover(); }); $("#popoverContent").css("paddingTop", "47px"); }; Popover.prototype.removeHeader = function() { $("#popoverBack").off("click"); $("#popoverClose").off("click"); $("#popoverHeader").remove(); $("#popoverContent").css("paddingTop", ""); }; Popover.prototype.clearData = function (){ this.removeHeader(); $("#popoverTitle").html(""); $("#popoverContent").html(""); }; Popover.prototype.setData = function (data) { Popover.setAction(data.id); Popover.setTitle(data.title); Popover.setContent(data.contents); }; Popover.prototype.replaceMenu = function (menu, newMenu){ var property; for(property in menu){ delete menu[property]; } for(property in newMenu){ menu[property] = newMenu[property]; } }; //Public setter function for private var content and sets content of the html popover element. Popover.setContent = function (cont) { Popover.content = cont; //$("#popoverContentWrapper").data('jsp').getContentPane().find("#popoverContent").html(cont); //Note: Popover content set without using jscrollpane api. $("#popoverContent").html(cont); //Note: Removed 'this' reference passed. $("#popoverContentWrapper").trigger("popover.setContent"); }; /** STATIC VARIABLES **/ Popover.popoverNum = 0; Popover.lastElementClick = null; Popover.currentTarget = null; Popover.title = ""; Popover.content = ""; Popover.menus = []; Popover.history = []; Popover.backgroundColor = null; Popover.fontColor = null; Popover.borderColor = null; Popover.padding = 3; Popover.offScreenX = false; Popover.offScreenY = false; Popover.isLocked = false; Popover.above = false; Popover.caretLeftOffset = "50%"; Popover.lastPopoverClicked = null; /** STATIC FUNCTIONS **/ Popover.setBackgroundColor = function(color){ Popover.backgroundColor = color; }; Popover.setFontColor = function(color){ Popover.fontColor = color; }; Popover.setBorderColor = function(color){ Popover.borderColor = color; }; Popover.lockPopover = function(){ Popover.isLocked = true; }; Popover.unlockPopover = function(){ Popover.isLocked = false; }; //////////////////////////////////////////////////////////// // OptionsPopover Block //////////////////////////////////////////////////////////// /** OptionsPopover CONSTRUCTOR **/ function OptionsPopover(popoverListener){ //Super constructor call. Popover.apply(this, [popoverListener]); this.constructor = OptionsPopover; this.superConstructor = Popover; this.isHeaderDisabled = false; this.isBackEnabled = true; if(!OptionsPopover.hasRun){ this.init(); OptionsPopover.hasRun = true; } } //Inherit Popover OptionsPopover.prototype = new Popover(); OptionsPopover.constructor = OptionsPopover; /** STATIC VARIABLES **/ OptionsPopover.hasRun = false; /** PROTOTYPE FUNCTIONS **/ //Run-once function for listeners OptionsPopover.prototype.init = function(){ $(document) .on('touchstart mousedown', '#popover a', function () { $(this).css({backgroundColor: "#488FCD"}); }) .on('touchend mouseup mouseout', '#popover a', function () { $(this).css({backgroundColor: ""}); }) .on('click', '.popoverContentRow', function () { var newId = []; newId.push($(this).attr('id')); if ($(this).hasClass("popoverEvent")) { $(this).trigger("popover.action", $(this)); } var keepOpen = Popover.lastPopoverClicked.populate(newId); if (!keepOpen) Popover.closePopover(); }); }; OptionsPopover.prototype.setData = function (data) { var contArray = data.contents; var c = ""; var i; for (i = 0; i < contArray.length; i++) { var lastElement = ""; var popoverEvent = ""; var menuId = ""; var menuUrl = ""; if (i === contArray.length - 1) { lastElement = " last"; } //Links are given the popoverEvent class if no url passed. If link has popoverEvent, // event is fired based on currentPopoverAction. if (typeof(contArray[i].id) !== 'undefined') { menuId = " id='" + contArray[i].id + "'"; } if (typeof(contArray[i].url) !== 'undefined') { menuUrl = " href='" + contArray[i].url + "'"; } else { popoverEvent = " popoverEvent"; } c += "<a" + menuUrl + menuId + " class='popoverContentRow" + popoverEvent + lastElement + "'>" + contArray[i].name + "</a>"; } Popover.setAction(data.id); Popover.setTitle(data.title); Popover.setContent(c); }; }(window.jQuery); /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function searchPanel(divElement, options) { var thread = null; var panel = this; var lastT = ""; var xhr = null; if (typeof componentsRegistry == "undefined") { componentsRegistry = []; } this.markerColor = 'black'; if (typeof globalMarkerColor == "undefined") { globalMarkerColor = 'black'; } this.type = "search"; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var componentLoaded = false; panel.shown0 = false; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } panel.subscribers = []; panel.subscriptions = []; panel.subscriptionsColor = []; this.history = []; this.setupCanvas = function() { var context = { divElementId: panel.divElement.id }; $(divElement).html(JST["views/searchPlugin/aux.hbs"](context)); $('#' + panel.divElement.id + '-searchBox').keyup(function() { clearTimeout(thread); var $this = $(this); thread = setTimeout(function() { panel.search($this.val(), 0, 100, false); }, 500); }); // $("#" + panel.divElement.id + "-linkerButton").disableTextSelect(); $("#" + panel.divElement.id + "-subscribersMarker").disableTextSelect(); $("#" + panel.divElement.id + "-configButton").disableTextSelect(); $("#" + panel.divElement.id + "-historyButton").disableTextSelect(); $("#" + panel.divElement.id + "-collapseButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").disableTextSelect(); $("#" + panel.divElement.id + "-closeButton").disableTextSelect(); $("#" + panel.divElement.id + "-clearButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-subscribersMarker").hide(); $("#" + panel.divElement.id).find('.semtag-button').click(function(event) { //console.log("Semtag click: " + $(this).html()); }); //$("#" + panel.divElement.id + "-searchConfigBar").slideUp('fast'); if (options.searchMode != "fullText") { $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').hide(); } $("#" + panel.divElement.id + "-configButton").click(function(event) { panel.setupOptionsPanel(); // $("#" + panel.divElement.id + "-searchConfigBar").slideToggle('slow'); }); if (typeof panel.options.closeButton != "undefined" && panel.options.closeButton == false) { $("#" + panel.divElement.id + "-closeButton").hide(); } // if (typeof panel.options.linkerButton != "undefined" && panel.options.linkerButton == false) { // $("#" + panel.divElement.id + "-linkerButton").hide(); // } if (typeof panel.options.subscribersMarker != "undefined" && panel.options.subscribersMarker == false) { $("#" + panel.divElement.id + "-subscribersMarker").remove(); } if (typeof panel.options.collapseButton != "undefined" && panel.options.collapseButton == false) { $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").hide(); } $("#" + panel.divElement.id + "-expandButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideDown("fast"); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").show(); }); $("#" + panel.divElement.id + "-collapseButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideUp("fast"); $("#" + panel.divElement.id + "-expandButton").show(); $("#" + panel.divElement.id + "-collapseButton").hide(); }); if (typeof i18n_panel_options == "undefined") { i18n_panel_options = "Panel options"; } $("#" + panel.divElement.id + "-configButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_panel_options, animation: true, delay: 1000 }); if (typeof i18n_history == "undefined") { i18n_history = 'History'; } $("#" + panel.divElement.id + "-historyButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_history, animation: true, delay: 1000 }); if (typeof i18n_panel_links == "undefined") { i18n_panel_links = 'Panel links'; } // $("#" + panel.divElement.id + "-linkerButton").tooltip({ // placement : 'left', // trigger: 'hover', // title: i18n_panel_links, // animation: true, // delay: 1000 // }); $("#" + panel.divElement.id + "-apply-button").click(function() { panel.readOptionsPanel(); }); $("#" + panel.divElement.id + "-clearButton").click(function() { panel.options.semTagFilter = "none"; panel.options.langFilter = "none"; panel.options.moduleFilter = "none"; panel.options.refsetFilter = "none"; $('#' + panel.divElement.id + '-searchBox').val(''); $('#' + panel.divElement.id + '-searchFilters').html(""); $('#' + panel.divElement.id + '-resultsTable').html(""); $('#' + panel.divElement.id + '-searchBar').html(""); $('#' + panel.divElement.id + '-searchBar2').html(""); $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-ok'); $('#' + panel.divElement.id + '-typeIcon').removeClass('text-success'); $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-remove'); $('#' + panel.divElement.id + '-typeIcon').addClass('text-danger'); lastT = ""; }); $("#" + panel.divElement.id + "-historyButton").click(function(event) { $("#" + panel.divElement.id + "-historyButton").popover({ trigger: 'manual', placement: 'bottomRight', html: true, content: function() { historyHtml = '<div style="height:100px;overflow:auto;">'; if (typeof i18n_no_search_terms == "undefined") { i18n_no_search_terms = "No search terms" } if (panel.history.length == 0) { historyHtml = historyHtml + '<div class="text-center text-muted" style="width:100%"><em>' + i18n_no_search_terms + '</span>...</em></div>'; } historyHtml = historyHtml + '<table>'; var reversedHistory = panel.history.slice(0); reversedHistory.reverse(); //console.log(JSON.stringify(reversedHistory)); $.each(reversedHistory, function(i, field) { var d = new Date(); var curTime = d.getTime(); var ago = curTime - field.time; var agoString = ""; if (ago < (1000 * 60)) { if (Math.round((ago / 1000)) == 1) { agoString = Math.round((ago / 1000)) + ' second ago'; } else { agoString = Math.round((ago / 1000)) + ' seconds ago'; } } else if (ago < (1000 * 60 * 60)) { if (Math.round((ago / 1000) / 60) == 1) { agoString = Math.round((ago / 1000) / 60) + ' minute ago'; } else { agoString = Math.round((ago / 1000) / 60) + ' minutes ago'; } } else if (ago < (1000 * 60 * 60 * 60)) { if (Math.round(((ago / 1000) / 60) / 60) == 1) { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hour ago'; } else { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hours ago'; } } historyHtml = historyHtml + '<tr><td><a href="javascript:void(0);" onclick="searchInPanel(\'' + panel.divElement.id + '\',\'' + field.searchTerm + '\');">' + field.searchTerm + '</a>'; historyHtml = historyHtml + ' <span class="text-muted" style="font-size: 80%"><em>' + agoString + '<em></span>'; historyHtml = historyHtml + '</td></tr>'; }); historyHtml = historyHtml + '</table>'; historyHtml = historyHtml + '</div>'; return historyHtml; } }); $("#" + panel.divElement.id + "-historyButton").popover('toggle'); }); // $("#" + panel.divElement.id + "-linkerButton").click(function (event) { // $("#" + panel.divElement.id + "-linkerButton").popover({ // trigger: 'manual', // placement: 'bottomRight', // html: true, // content: function () { // var linkerHtml = '<div class="text-center text-muted"><em><span class="i18n" data-i18n-id="i18n_drag_to_link">Drag to link with other panels</span><br>'; // if (panel.subscriptions.length == 1) { // linkerHtml = linkerHtml + panel.subscriptions.length + ' link established</em></div>'; // } else { // linkerHtml = linkerHtml + panel.subscriptions.length + ' links established</em></div>'; // } // linkerHtml = linkerHtml + '<div class="text-center"><a href="javascript:void(0);" onclick="clearSearchPanelSubscriptions(\'' + panel.divElement.id + '\');"><span class="i18n" data-i18n-id="i18n_clear_links">Clear links</span></a></div>'; // return linkerHtml; // } // }); // $("#" + panel.divElement.id + "-linkerButton").popover('toggle'); // }); $("#" + panel.divElement.id + "-fullTextButton").click(function(event) { panel.options.searchMode = 'fullText'; panel.updateSearchLabel(); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').show(); if (searchTerm.charAt(0) == "^") { $("#" + panel.divElement.id + '-searchBox').val(searchTerm.slice(1)); } if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-partialMatchingButton").click(function(event) { panel.options.searchMode = 'partialMatching'; panel.updateSearchLabel(); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').hide(); if (searchTerm.charAt(0) == "^") { $("#" + panel.divElement.id + '-searchBox').val(searchTerm.slice(1)); } if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-regexButton").click(function(event) { panel.options.searchMode = 'regex'; panel.updateSearchLabel(); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').hide(); if (searchTerm.charAt(0) != "^") { $("#" + panel.divElement.id + '-searchBox').val("^" + searchTerm); } if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-danishLangButton").click(function(event) { panel.options.searchLang = 'danish'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_danish_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-englishLangButton").click(function(event) { panel.options.searchLang = 'english'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_english_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-spanishLangButton").click(function(event) { panel.options.searchLang = 'spanish'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_spanish_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-swedishLangButton").click(function(event) { panel.options.searchLang = 'swedish'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_swedish_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); panel.updateStatusFilterLabel(); $("#" + panel.divElement.id + "-activeOnlyButton").click(function(event) { panel.options.statusSearchFilter = 'activeOnly'; panel.updateStatusFilterLabel(); }); $("#" + panel.divElement.id + "-activeInactiveButton").click(function(event) { panel.options.statusSearchFilter = 'activeAndInactive'; panel.updateStatusFilterLabel(); }); $("#" + panel.divElement.id + "-inactiveOnlyButton").click(function(event) { panel.options.statusSearchFilter = 'inactiveOnly'; panel.updateStatusFilterLabel(); }); $("#" + panel.divElement.id + "-partialMatchingButton").click(); $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor); }; this.setupOptionsPanel = function() { var possibleSubscribers = []; $.each(componentsRegistry, function(i, field) { if (field.divElement.id != panel.divElement.id) { var object = {}; object.subscriptions = field.subscriptions; object.id = field.divElement.id; possibleSubscribers.push(object); } }); var aux = false; $.each(possibleSubscribers, function(i, field) { aux = false; $.each(panel.subscriptions, function(j, subscription) { if (field.id == subscription.topic) { aux = true; } }); field.subscribed = aux; aux = false; $.each(field.subscriptions, function(i, subscription) { if (subscription.topic == panel.divElement.id) { aux = true; } }); field.subscriptor = aux; }); panel.options.possibleSubscribers = possibleSubscribers; var context = { options: panel.options, divElementId: panel.divElement.id }; $("#" + panel.divElement.id + "-modal-body").html(JST["views/taxonomyPlugin/options.hbs"](context)); } this.readOptionsPanel = function() { $.each(panel.options.possibleSubscribers, function(i, field) { field.subscribed = $("#" + panel.divElement.id + "-subscribeTo-" + field.id).is(':checked'); field.subscriptor = $("#" + panel.divElement.id + "-subscriptor-" + field.id).is(':checked'); var panelToSubscribe = {}; $.each(componentsRegistry, function(i, panelS) { if (panelS.divElement.id == field.id) { panelToSubscribe = panelS; } }); if (field.subscribed) { panel.subscribe(panelToSubscribe); } else { panel.unsubscribe(panelToSubscribe); } if (field.subscriptor) { panelToSubscribe.subscribe(panel); } else { panelToSubscribe.unsubscribe(panel); } }); $.each(componentsRegistry, function(i, field) { if (field.loadMarkers) field.loadMarkers(); }); } this.updateStatusFilterLabel = function() { if (typeof i18n_active_and_inactive == "undefined") { i18n_active_and_inactive = 'Active and Inactive'; } if (typeof i18n_inactive_only == "undefined") { i18n_inactive_only = 'Inactive Only'; } if (typeof i18n_active_only == "undefined") { i18n_active_only = 'Active Only'; } if (panel.options.statusSearchFilter == 'activeAndInactive') { $("#" + panel.divElement.id + '-searchStatus').html(i18n_active_and_inactive); $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_active_and_inactive); } else if (panel.options.statusSearchFilter == 'inactiveOnly') { $("#" + panel.divElement.id + '-searchStatus').html(i18n_inactive_only); $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_inactive_only); } else { panel.options.statusSearchFilter = 'activeOnly'; $("#" + panel.divElement.id + '-searchStatus').html(i18n_active_only); $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_active_only); } var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } } this.search = function(t, skipTo, returnLimit, forceSearch) { if (typeof panel.options.searchMode == "undefined") { panel.options.searchMode = "partialMatching"; } if (typeof panel.options.semTagFilter == "undefined") { panel.options.semTagFilter = "none"; } if (typeof panel.options.langFilter == "undefined") { panel.options.langFilter = "none"; } if (typeof panel.options.moduleFilter == "undefined") { panel.options.moduleFilter = "none"; } if (typeof panel.options.textIndexNormalized == "undefined") { panel.options.textIndexNormalized = "none"; } if (typeof panel.options.refsetFilter == "undefined") { panel.options.refsetFilter = "none"; } if (typeof forceSearch == "undefined") { forceSearch = false; } // panel.divElement.id + '-typeIcon if (t != "" && (t != lastT || forceSearch)) { if (t.length < 3) { $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-ok'); $('#' + panel.divElement.id + '-typeIcon').removeClass('text-success'); $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-remove'); $('#' + panel.divElement.id + '-typeIcon').addClass('text-danger'); } else { $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-remove'); $('#' + panel.divElement.id + '-typeIcon').removeClass('text-danger'); $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-ok'); $('#' + panel.divElement.id + '-typeIcon').addClass('text-success'); //if (t != lastT) { // panel.options.semTagFilter = "none"; // panel.options.langFilter = "none"; // panel.options.moduleFilter ="none"; // panel.options.refsetFilter = "none"; // //panel.options.textIndexNormalized = "none"; //} lastT = t; //console.log(t); var d = new Date(); var time = d.getTime(); panel.history.push({ searchTerm: t, time: time }); //t = t.charAt(0).toUpperCase() + t.slice(1); //console.log("Capitalized t: " + t); $('#' + panel.divElement.id + '-searchFilters').html(""); if (skipTo == 0) { $('#' + panel.divElement.id + '-resultsTable').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); } else { $('#' + panel.divElement.id + '-resultsTable').find('.more-row').html("<td colspan='2' class='text-center'><i class='glyphicon glyphicon-refresh icon-spin'></i>&nbsp;&nbsp;</td>"); } var resultsHtml = ""; if (xhr != null) { xhr.abort(); //console.log("aborting call..."); } $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'>Searching..</span>"); //console.log("panel.options.searchMode " + panel.options.searchMode); t = t.trim(); if (isNumber(t)) { if (t.substr(-2, 1) == "0") { // Search conceptId xhr = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/concepts/" + t, function(result) { }).done(function(result) { console.log(result); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); var resDescriptions = []; $.each(result.descriptions, function(i, field) { var aux = field; aux.definitionStatus = result.definitionStatus; if (!aux.active) { aux.danger = true; } if (field.active) { if (panel.options.statusSearchFilter == "activeOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } else { aux.danger = true; if (panel.options.statusSearchFilter == "inactiveOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } }); result.descriptions = resDescriptions; var context = { result: result }; //console.log(context); $('#' + panel.divElement.id + '-resultsTable').html(JST["views/searchPlugin/body/0.hbs"](context)); $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'></span>"); $('#' + panel.divElement.id + '-resultsTable').find(".result-item").click(function(event) { // $.each(panel.subscribers, function (i, field) { // //console.log("Notify to " + field.divElement.id + " selected " + $(event.target).attr('data-concept-id')); // field.conceptId = $(event.target).attr('data-concept-id'); // field.updateCanvas(); // }); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function() { resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar2').html(""); }); } else if (t.substr(-2, 1) == "1") { xhr = $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/descriptions/" + t, function(result) { }).done(function(result) { //console.log(result); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); var context = { result: result }; $('#' + panel.divElement.id + '-resultsTable').html(JST["views/searchPlugin/body/1.hbs"](context)); $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'></span>"); $('#' + panel.divElement.id + '-resultsTable').find(".result-item").click(function(event) { // $.each(panel.subscribers, function (i, field) { // //console.log("Notify to " + field.divElement.id + " selected " + $(event.target).attr('data-concept-id')); // field.conceptId = $(event.target).attr('data-concept-id'); // field.updateCanvas(); // }); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function() { resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar2').html(""); }); } else { // console.log(t.substr(-2, 1)); resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'></span>"); $('#' + panel.divElement.id + '-searchBar2').html(""); } } else { if (panel.options.searchMode == "partialMatching") { t = t.toLowerCase(); t = t.replace("(", ""); t = t.replace(")", ""); } var startTime = Date.now(); var conceptActiveParam; if (panel.options.statusSearchFilter == "activeOnly") { conceptActiveParam = "true"; } else if (panel.options.statusSearchFilter == "inactiveOnly") { conceptActiveParam = "false"; } else { conceptActiveParam = ""; } var searchUrl = options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/descriptions?" + "term=" + encodeURIComponent(t) + "&limit=50" + "&searchMode=" + panel.options.searchMode + "&lang=" + panel.options.searchLang + "&active=" + "true" + "&skipTo=" + skipTo + "&returnLimit=" + returnLimit; if (panel.options.semTagFilter != "none") { searchUrl = searchUrl + "&semanticTag=" + panel.options.semTagFilter; } if (panel.options.langFilter != "none") { searchUrl = searchUrl + "&langFilter=" + panel.options.langFilter; } if (panel.options.moduleFilter != 'none') { searchUrl = searchUrl + "&moduleFilter=" + panel.options.moduleFilter; } if (panel.options.refsetFilter != 'none') { searchUrl = searchUrl + "&refsetFilter=" + panel.options.refsetFilter; } if (panel.options.textIndexNormalized != "none") { searchUrl = searchUrl + "&normalize=" + panel.options.textIndexNormalized; } if ($("#" + panel.divElement.id + "-groupConcept").is(":checked")) { searchUrl = searchUrl + "&groupByConcept=1"; } //console.log(searchUrl); xhr = $.getJSON(searchUrl, function(result) { }).done(function(result) { var resDescriptions = []; $.each(result.items, function(i, field) { var aux = field; aux.definitionStatus = result.definitionStatus; aux.conceptActive = field.concept.active; if (!aux.active || !aux.conceptActive) { aux.danger = true; } if (field.active && field.concept.active) { if (panel.options.statusSearchFilter == "activeOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } else { aux.danger = true; if (panel.options.statusSearchFilter == "inactiveOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } }); // Convert response format result.matches = resDescriptions; result.matches.forEach(function(match) { match.fsn = match.concept.fsn; match.conceptActive = match.concept.active; match.conceptId = match.concept.conceptId; match.definitionStatus = match.concept.definitionStatus; }) result.filters = {}; result.filters.lang = result.filters.language; result.filters.module = result.filters.module; result.filters.refsetId = result.filters.membership; result.filters.semTag = result.filters.semanticTags; $('#' + panel.divElement.id + '-resultsTable').find('.more-row').remove(); var endTime = Date.now(); var elapsed = (endTime - startTime) / 1000; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper("first20chars", function(string) { return (string.substr(0, 18) + "..."); }); var auxArray = []; if (result.filters) { if (result.filters.refsetId) { $.each(result.filters.refsetId, function(i, refset) { var auxObject = {}; var bucketTerm = null; if (result.bucketConcepts[i]) { bucketTerm = result.bucketConcepts[i].fsn.term; } auxObject.term = bucketTerm; auxObject.value = i; auxObject.cant = refset; auxArray.push(auxObject); }); result.filters.refsetId = []; result.filters.refsetId = auxArray; result.filters.refsetId.sort(function(a, b) { if (a.cant > b.cant) return -1; if (a.cant < b.cant) return 1; return 0; }); } else { result.filters.refsetId = []; } auxArray = []; $.each(result.filters.module, function(i, field) { var auxObject = {}; var bucketTerm = null; if (result.bucketConcepts[i]) { bucketTerm = result.bucketConcepts[i].fsn.term; } auxObject.term = bucketTerm; auxObject.value = i; auxObject.cant = field; auxArray.push(auxObject); }); result.filters.module = []; result.filters.module = auxArray; result.filters.module.sort(function(a, b) { if (a.cant > b.cant) return -1; if (a.cant < b.cant) return 1; return 0; }); if (result.filters.lang && result.filters.semTag) { function sortObject(object) { var sortable = [], sortedObj = {}; for (var attr in object) sortable.push([attr, object[attr]]); sortable.sort(function(a, b) { return b[1] - a[1] }); $.each(sortable, function(i, field) { sortedObj[field[0]] = field[1]; }); return sortedObj; } result.filters.lang = sortObject(result.filters.lang); result.filters.semTag = sortObject(result.filters.semTag); } } // console.log(auxArray); // console.log(result.filters.module); // var ind = 0; // $.each(result.filters.refsetId, function (i, field){ // ind++; // }); // if (ind == 0){ // result.filters.refsetId = 0; // } var context = { result: result, elapsed: elapsed, divElementId: panel.divElement.id, options: panel.options }; $('#' + panel.divElement.id + '-searchBar').html(JST["views/searchPlugin/body/bar.hbs"](context)); $('#' + panel.divElement.id + '-searchBar2').html(JST["views/searchPlugin/body/bar2.hbs"](context)); $('#' + panel.divElement.id + '-moduleResumed').tooltip({ placement: 'left auto', trigger: 'hover', title: $('#' + panel.divElement.id + '-moduleResumed').attr("data-name"), animation: true, delay: 500 }); $('#' + panel.divElement.id + '-refsetResumed').tooltip({ placement: 'left auto', trigger: 'hover', title: $('#' + panel.divElement.id + '-refsetResumed').attr("data-name"), animation: true, delay: 500 }); $("#" + panel.divElement.id + '-searchBar2').find('.semtag-link').click(function(event) { panel.options.semTagFilter = $(event.target).attr('data-semtag'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.module-link').click(function(event) { panel.options.moduleFilter = $(event.target).attr('data-module'); panel.options.moduleFilterName = $(event.target).attr('data-term'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.lang-link').click(function(event) { panel.options.langFilter = $(event.target).attr('data-lang'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.refset-link').click(function(event) { panel.options.refsetFilter = $(event.target).attr('data-refset'); panel.options.refsetFilterName = $(event.target).attr('data-term'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-semtag').click(function(event) { panel.options.semTagFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-lang').click(function(event) { panel.options.langFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-module').click(function(event) { panel.options.moduleFilter = "none"; panel.options.moduleFilterName = null; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-refset').click(function(event) { panel.options.refsetFilter = "none"; panel.options.refsetFilterName = null; panel.search(t, 0, returnLimit, true); }); //original filter $("#" + panel.divElement.id + '-searchBar').find('.semtag-link').click(function(event) { panel.options.semTagFilter = $(event.target).attr('data-semtag'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.module-link').click(function(event) { panel.options.moduleFilter = $(event.target).attr('data-module'); panel.options.moduleFilterName = $(event.target).attr('data-term'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.lang-link').click(function(event) { panel.options.langFilter = $(event.target).attr('data-lang'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.remove-semtag').click(function(event) { panel.options.semTagFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.remove-lang').click(function(event) { panel.options.langFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.remove-module').click(function(event) { panel.options.moduleFilter = "none"; panel.options.moduleFilterName = null; panel.search(t, 0, returnLimit, true); }); if (result.details) { var searchComment = "<span class='text-muted'>" + result.details.total + " matches found in " + elapsed + " seconds.</span>"; } xhr = null; var matchedDescriptions = result.matches; //console.log(JSON.stringify(result)); var remaining = result.totalElements - (skipTo + returnLimit); if (panel.options.searchMode == "regex") { result.matches.sort(function(a, b) { if (a.term.length < b.term.length) return -1; if (a.term.length > b.term.length) return 1; return 0; }); } Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > parseInt(b)) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gre', function(a, b, opts) { if (a) { if (parseInt(a) >= b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('hasFilters', function(options, opts) { if (options.semTagFilter != "none" || options.langFilter != "none" || options.moduleFilter != "none" || options.refsetFilter != "none") { return opts.fn(this);; } else { return opts.inverse(this); } }); var context = { options: panel.options, result: result, divElementId: panel.divElement.id, remaining: remaining, returnLimit: returnLimit }; if (skipTo == 0) { $('#' + panel.divElement.id + '-resultsTable').html(JST["views/searchPlugin/body/default.hbs"](context)); } else { $('#' + panel.divElement.id + '-resultsTable').append(JST["views/searchPlugin/body/default.hbs"](context)); } $("#" + panel.divElement.id + "-groupConcept").click(function() { panel.search(t, parseInt(skipTo), returnLimit, true); }); $("#" + panel.divElement.id + "-remove-all-filters").unbind(); $("#" + panel.divElement.id + "-remove-all-filters").click(function(event) { panel.options.semTagFilter = "none"; panel.options.langFilter = "none"; panel.options.moduleFilter = "none"; panel.options.refsetFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + "-more").unbind(); $("#" + panel.divElement.id + "-more").click(function(event) { panel.search(t, (parseInt(skipTo) + parseInt(returnLimit)), returnLimit, true); }); $('#' + panel.divElement.id + '-resultsTable').find(".result-item").click(function(event) { channel.publish(panel.divElement.id, { term: $(event.target).attr("data-term"), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() { resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar2').html(""); }); } } } } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); // Subscription methods this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; // console.log('Subscribing to id: ' + panelId); var alreadySubscribed = false; $.each(panel.subscriptionsColor, function(i, field) { if (field == panelToSubscribe.markerColor) { alreadySubscribed = true; } }); if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { // console.log("listening in " + panel.divElement.id); panel.options.searchMode = "fullText"; panel.search(data.conceptId, 0, 100, false); $('#' + panel.divElement.id + '-searchBox').val(data.term); }); panel.subscriptions.push(subscription); panelToSubscribe.subscribers.push(panel.divElement.id); panel.subscriptionsColor.push(panelToSubscribe.markerColor); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-subscribersMarker").show(); } this.unsubscribe = function(panelToUnsubscribe) { var aux = [], colors = [], unsubscribed = true; $.each(panel.subscriptionsColor, function(i, field) { if (field != panelToUnsubscribe.markerColor) { colors.push(field); } else { unsubscribed = false; } }); if (!unsubscribed) { panel.subscriptionsColor = colors; // console.log(panel.divElement.id); // console.log(panel.subscriptionsColor); colors = []; $.each(panelToUnsubscribe.subscribers, function(i, field) { if (field != panel.divElement.id) { aux.push(field); } }); panelToUnsubscribe.subscribers = aux; $.each(panelToUnsubscribe.subscriptionsColor, function(i, field) { colors.push(field); }); if (panelToUnsubscribe.subscribers.length == 0) { if (panelToUnsubscribe.subscriptions.length == 0) { $("#" + panelToUnsubscribe.divElement.id + "-subscribersMarker").hide(); } } else { // colors.push(panelToUnsubscribe.markerColor); } panelToUnsubscribe.subscriptionsColor = colors; // console.log(panelToUnsubscribe.divElement.id); // console.log(panelToUnsubscribe.subscriptionsColor); aux = []; $.each(panel.subscriptions, function(i, field) { if (panelToUnsubscribe.divElement.id == field.topic) { field.unsubscribe(); } else { aux.push(field); } }); panel.subscriptions = aux; if (panel.subscriptions.length == 0 && panel.subscribers.length == 0) { $("#" + panel.divElement.id + "-subscribersMarker").hide(); } } } this.loadMarkers = function() { var auxMarker = "", right = 0, top = 0, aux = false, visible = false; $.each(componentsRegistry, function(i, field) { var panelId = field.divElement.id; if ($("#" + panelId + "-subscribersMarker").is(':visible')) { visible = true; } }); if (panel.subscribers.length == 0) { right = 14; $("#" + panel.divElement.id + "-ownMarker").hide(); } else { if (!visible) { $("#" + panel.divElement.id + "-ownMarker").hide(); } aux = true; } if ($("#" + panel.divElement.id + "-subscribersMarker").is(':visible')) { $("#" + panel.divElement.id + "-panelTitle").html($("#" + panel.divElement.id + "-panelTitle").html().replace(/&nbsp;/g, '')); if (aux) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); } $.each(panel.subscriptionsColor, function(i, field) { auxMarker = auxMarker + "<i class='glyphicon glyphicon-bookmark' style='color: " + field + "; top:" + top + "px; right: " + right + "px;'></i>"; $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); top = top + 5; right = right + 10; }); $("#" + panel.divElement.id + "-subscribersMarker").html(auxMarker); } } this.updateSearchLabel = function() { if (typeof panel.options.searchMode == "undefined") { panel.options.searchMode = "partialMatching"; } if (typeof i18n_search_examp_1 == "undefined") { i18n_search_examp_1 = 'Example 1'; } if (typeof i18n_search_examp_2 == "undefined") { i18n_search_examp_2 = 'Example 2'; } if (typeof i18n_search_examp_3 == "undefined") { i18n_search_examp_3 = 'Example 3'; } if (typeof i18n_regex_search_mode == "undefined") { i18n_regex_search_mode = 'Regex'; } if (typeof i18n_partial_match_search_mode == "undefined") { i18n_partial_match_search_mode = 'Partial'; } if (typeof i18n_full_text_search_mode == "undefined") { i18n_full_text_search_mode = 'Full'; } if (panel.options.searchMode == "regex") { $("#" + panel.divElement.id + "-searchMode").html("<span class='i18n' data-i18n-id='i18n_regex_search_mode'>" + i18n_regex_search_mode + "</span>"); $("#" + panel.divElement.id + '-searchExample').html("<span class='i18n text-muted' data-i18n-id='i18n_search_examp_1'>" + i18n_search_examp_1 + "</span> "); $("#" + panel.divElement.id + '-navSearchModeLabel').html("<span class='i18n' data-i18n-id='i18n_regex_search_mode'>" + i18n_regex_search_mode + "</span>"); } else if (panel.options.searchMode == "fullText") { $("#" + panel.divElement.id + "-searchMode").html("<span class='i18n' data-i18n-id='i18n_full_text_search_mode'>" + i18n_full_text_search_mode + "</span>"); $("#" + panel.divElement.id + '-searchExample').html("<span class='i18n text-muted' data-i18n-id='i18n_search_examp_2'>" + i18n_search_examp_2 + "</em></span> "); $("#" + panel.divElement.id + '-navSearchModeLabel').html("<span class='i18n' data-i18n-id='i18n_full_text_search_mode'>" + i18n_full_text_search_mode + "</span>"); } else if (panel.options.searchMode == "partialMatching") { $("#" + panel.divElement.id + "-searchMode").html("<span class='i18n' data-i18n-id='i18n_partial_match_search_mode'>" + i18n_partial_match_search_mode + "</span>"); $("#" + panel.divElement.id + '-searchExample').html("<span class='i18n text-muted' data-i18n-id='i18n_search_examp_3'>" + i18n_search_examp_3 + "</span> "); $("#" + panel.divElement.id + '-navSearchModeLabel').html("<span class='i18n' data-i18n-id='i18n_partial_match_search_mode'>" + i18n_partial_match_search_mode + "</span>"); } if (typeof panel.options.searchLang == "undefined") { panel.options.searchLang = "english"; } if (typeof i18n_danish_stemmer == "undefined") { i18n_danish_stemmer = 'Danish Stemmer'; } if (typeof i18n_english_stemmer == "undefined") { i18n_english_stemmer = 'English Stemmer'; } if (typeof i18n_spanish_stemmer == "undefined") { i18n_spanish_stemmer = 'Spanish Stemmer'; } if (panel.options.searchLang == "danish") { $("#" + panel.divElement.id + '-navLanguageLabel').html("<span class='i18n' data-i18n-id='i18n_danish_stemmer'>" + i18n_danish_stemmer + "</span>"); } else if (panel.options.searchLang == "english") { $("#" + panel.divElement.id + '-navLanguageLabel').html("<span class='i18n' data-i18n-id='i18n_english_stemmer'>" + i18n_english_stemmer + "</span>"); } else if (panel.options.searchLang == "spanish") { $("#" + panel.divElement.id + '-navLanguageLabel').html("<span class='i18n' data-i18n-id='i18n_spanish_stemmer'>" + i18n_spanish_stemmer + "</span>"); } } this.setupCanvas(); this.updateSearchLabel(); } function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function clearSearchPanelSubscriptions(divElementId1) { var d1; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == divElementId1) { d1 = field; } }); d1.unsubscribeAll(); $("#" + divElementId1).find('.linker-button').popover('toggle'); } function searchInPanel(divElementId, searchTerm) { $.each(componentsRegistry, function(i, field) { //console.log(field.divElement.id + ' == ' + divElementId); if (field.divElement.id == divElementId) { $('#' + divElementId + '-searchBox').val(searchTerm); field.search(searchTerm, 0, 100, false); } }); $('.history-button').popover('hide'); } $(document).keypress(function(event) { if (event.which == '13') { event.preventDefault(); } }); (function($) { $.fn.addSearch = function(options) { this.filter("div").each(function() { var tx = new conceptDetails(this, options); }); }; }(jQuery)); /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var idSequence = 0; function drawSctBox(svg, x, y, label, sctid, cssClass) { //console.log("In svg: " + label + " " + sctid + " " + cssClass); // x,y coordinates of the top-left corner var testText = "Test"; if (label && sctid) { if (label.length > sctid.toString().length) { testText = label; } else { testText = sctid.toString(); } } else if (label) { testText = label; } else if (sctid) { testText = sctid.toString(); } var fontFamily = '"Helvetica Neue",Helvetica,Arial,sans-serif'; //var fontFamily = 'sans-serif'; var tempText = svg.text(x, y , testText, {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); var textHeight = tempText.getBBox().height; var textWidth = tempText.getBBox().width; textWidth = Math.round(textWidth* 1.2); svg.remove(tempText); var rect = null; var widthPadding = 20; var heightpadding = 25; if (!sctid || !label) { heightpadding = 15; } if (cssClass == "sct-primitive-concept") { rect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: '#99ccff', stroke: '#333', strokeWidth: 2}); } else if (cssClass == "sct-defined-concept") { rect = svg.rect(x-2, y-2, textWidth + widthPadding + 4, textHeight + heightpadding + 4, {fill: 'white', stroke: '#333', strokeWidth: 1}); var innerRect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: '#ccccff', stroke: '#333', strokeWidth: 1}); } else if (cssClass == "sct-attribute") { rect = svg.rect(x-2, y-2, textWidth + widthPadding + 4, textHeight + heightpadding + 4, 18, 18, {fill: 'white', stroke: '#333', strokeWidth: 1}); var innerRect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, 18, 18, {id: 'rect'+idSequence, fill: '#ffffcc', stroke: '#333', strokeWidth: 1}); }else if (cssClass == "sct-slot") { rect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: '#99ccff', stroke: '#333', strokeWidth: 2}); } else { rect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: 'white', stroke: 'black', strokeWidth: 1}); } if (sctid && label) { svg.text(x + 10, y + 16, sctid.toString(), {fontFamily: fontFamily, fontSize: '10', fill: 'black'}); svg.text(x + 10, y + 31, label, {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); } else if (label) { svg.text(x + 10, y + 18, label, {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); } else if (sctid) { svg.text(x + 10, y + 18, sctid.toString(), {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); } idSequence++; $('rect').click(function(evt){ //console.log(evt.target); }); return rect; } function connectElements(svg, fig1, fig2, side1, side2, endMarker) { var rect1cx = fig1.getBBox().x; var rect1cy = fig1.getBBox().y; var rect1cw = fig1.getBBox().width; var rect1ch = fig1.getBBox().height; var rect2cx = fig2.getBBox().x; var rect2cy = fig2.getBBox().y ; var rect2cw = fig2.getBBox().width; var rect2ch = fig2.getBBox().height; var markerCompensantion1 = 15; var markerCompensantion2 = 15; switch(side1) { case 'top': originY = rect1cy; originX = rect1cx + (rect1cw/2); break; case 'bottom': originY = rect1cy + rect1ch; originX = rect1cx + (rect1cw/2); break; case 'left': originX = rect1cx - markerCompensantion1; originY = rect1cy + (rect1ch/2); break; case 'right': originX = rect1cx + rect1cw; originY = rect1cy + (rect1ch/2); break; case 'bottom-50': originY = rect1cy + rect1ch; originX = rect1cx + 40; break; default: originX = rect1cx + (rect1cw/2); originY = rect1cy + (rect1ch/2); break; } switch(side2) { case 'top': destinationY = rect2cy; destinationX = rect2cx + (rect2cw/2); break; case 'bottom': destinationY = rect2cy + rect2ch; destinationX = rect2cx + (rect2cw/2); break; case 'left': destinationX = rect2cx - markerCompensantion2; destinationY = rect2cy + (rect2ch/2); break; case 'right': destinationX = rect2cx + rect2cw; destinationY = rect2cy + (rect2ch/2); break; case 'bottom-50': destinationY = rect2cy + rect2ch; destinationX = rect2cx + 50; break; default: destinationX = rect2cx + (rect2cw/2); destinationY = rect2cy + (rect2ch/2); break; } if (endMarker == null) endMarker = "BlackTriangle"; polyline1 = svg.polyline([[originX, originY], [originX, destinationY], [destinationX, destinationY]] , {id: 'poly1', fill: 'none', stroke: 'black', strokeWidth: 2, 'marker-end': 'url(#' + endMarker + ')'}); } function loadDefs(svg) { var defs = svg.defs('SctDiagramsDefs'); blackTriangle = svg.marker(defs, 'BlackTriangle', 0, 0, 20, 20, { viewBox: '0 0 22 20', refX: '0', refY: '10', markerUnits: 'strokeWidth', markerWidth: '8', markerHeight: '6', fill: 'black',stroke: 'black', strokeWidth: 2}); svg.path(blackTriangle, 'M 0 0 L 20 10 L 0 20 z'); clearTriangle = svg.marker(defs, 'ClearTriangle', 0, 0, 20, 20, { viewBox: '0 0 22 20', refX: '0', refY: '10', markerUnits: 'strokeWidth', markerWidth: '8', markerHeight: '8', fill: 'white',stroke: 'black', strokeWidth: 2}); svg.path(clearTriangle, 'M 0 0 L 20 10 L 0 20 z'); lineMarker = svg.marker(defs, 'LineMarker', 0, 0, 20, 20, { viewBox: '0 0 22 20', refX: '0', refY: '10', markerUnits: 'strokeWidth', markerWidth: '8', markerHeight: '8', fill: 'white',stroke: 'black', strokeWidth: 2}); svg.path(lineMarker, 'M 0 10 L 20 10'); } function drawAttributeGroupNode(svg, x, y) { circle = svg.circle(x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); return circle; } function drawConjunctionNode(svg, x, y) { circle = svg.circle(x, y, 10, {fill: 'black',stroke: 'black', strokeWidth: 2}); return circle; } function drawEquivalentNode(svg, x, y) { g = svg.group(); svg.circle(g, x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y-5, x+7, y-5, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y, x+7, y, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+5, x+7, y+5, {stroke: 'black', strokeWidth: 2}); return g; } function drawSubsumedByNode(svg, x, y) { g = svg.group(); svg.circle(g, x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y-8, x+7, y-8, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+3, x+7, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-6, y-8, x-6, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+7, x+7, y+7, {stroke: 'black', strokeWidth: 2}); return g; } function drawSubsumesNode(svg, x, y) { g = svg.group(); svg.circle(g, x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y-8, x+7, y-8, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+3, x+7, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x+6, y-8, x+6, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+7, x+7, y+7, {stroke: 'black', strokeWidth: 2}); return g; } /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function taxonomyPanel(divElement, conceptId, options) { var nodeCount = 0; var panel = this; var xhr = null; if (typeof componentsRegistry == "undefined") { componentsRegistry = []; } this.markerColor = 'black'; if (typeof globalMarkerColor == "undefined") { globalMarkerColor = 'black'; } this.type = "taxonomy"; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var componentLoaded = false; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } panel.default = {}; panel.default.conceptId = conceptId; panel.subscribers = []; panel.subscriptions = []; panel.subscriptionsColor = []; this.history = []; if (!options.rootConceptDescendants) { console.log(options); $.ajax({ type: "GET", url: options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts", data: { ecl: "< 138875005|SNOMED CT Concept|", offset: 0, limit: 1 }, dataType: "json", success: function(result) { options.rootConceptDescendants = result.total; } }).done(function(result) { // done }); } this.setupCanvas = function() { var context = { divElementId: panel.divElement.id }; $(divElement).html(JST["views/taxonomyPlugin/main.hbs"](context)); $("#" + panel.divElement.id + "-resetButton").disableTextSelect(); // $("#" + panel.divElement.id + "-linkerButton").disableTextSelect(); $("#" + panel.divElement.id + "-subscribersMarker").disableTextSelect(); $("#" + panel.divElement.id + "-historyButton").disableTextSelect(); $("#" + panel.divElement.id + "-configButton").disableTextSelect(); $("#" + panel.divElement.id + "-collapseButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").disableTextSelect(); $("#" + panel.divElement.id + "-closeButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-subscribersMarker").hide(); $("#" + panel.divElement.id + "-closeButton").click(function(event) { $(divElement).remove(); }); $("#" + panel.divElement.id + "-configButton").click(function(event) { panel.setupOptionsPanel(); // $("#" + panel.divElement.id + "-taxonomyConfigBar").slideToggle('slow'); }); if (typeof panel.options.closeButton != "undefined" && panel.options.closeButton == false) { $("#" + panel.divElement.id + "-closeButton").hide(); } // if (typeof panel.options.linkerButton != "undefined" && panel.options.linkerButton == false) { // $("#" + panel.divElement.id + "-linkerButton").hide(); // } if (typeof panel.options.subscribersMarker != "undefined" && panel.options.subscribersMarker == false) { $("#" + panel.divElement.id + "-subscribersMarker").remove(); } if (typeof panel.options.collapseButton != "undefined" && panel.options.collapseButton == false) { $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").hide(); } $("#" + panel.divElement.id + "-expandButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideDown("fast"); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").show(); }); $("#" + panel.divElement.id + "-collapseButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideUp("fast"); $("#" + panel.divElement.id + "-expandButton").show(); $("#" + panel.divElement.id + "-collapseButton").hide(); }); if (typeof i18n_panel_options == "undefined") { i18n_panel_options = 'Options'; } $("#" + panel.divElement.id + "-configButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_panel_options, animation: true, delay: 1000 }); if (typeof i18n_history == "undefined") { i18n_history = 'History'; } $("#" + panel.divElement.id + "-historyButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_history, animation: true, delay: 1000 }); if (typeof i18n_reset == "undefined") { i18n_reset = 'Reset'; } $("#" + panel.divElement.id + "-resetButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_reset, animation: true, delay: 1000 }); if (typeof i18n_panel_links == "undefined") { i18n_panel_links = 'Panel links'; } // $("#" + panel.divElement.id + "-linkerButton").tooltip({ // placement : 'left', // trigger: 'hover', // title: i18n_panel_links, // animation: true, // delay: 1000 // }); $("#" + panel.divElement.id + "-resetButton").click(function() { // panel.setupParents([], {conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); panel.setToConcept(panel.default.conceptId); }); $("#" + panel.divElement.id + "-apply-button").click(function() { //console.log("apply!"); panel.readOptionsPanel(); // panel.setupParents([], {conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-historyButton").click(function(event) { $("#" + panel.divElement.id + "-historyButton").popover({ trigger: 'manual', placement: 'bottomRight', html: true, content: function() { historyHtml = '<div style="height:100px;overflow:auto;">'; if (typeof i18n_no_terms == "undefined") { i18n_no_terms = "No terms" } if (panel.history.length == 0) { historyHtml = historyHtml + '<div class="text-center text-muted" style="width:100%"><em>' + i18n_no_terms + '</span>...</em></div>'; } historyHtml = historyHtml + '<table>'; var reversedHistory = panel.history.slice(0); reversedHistory.reverse(); //console.log(JSON.stringify(reversedHistory)); $.each(reversedHistory, function(i, field) { var d = new Date(); var curTime = d.getTime(); var ago = curTime - field.time; var agoString = ""; if (ago < (1000 * 60)) { if (Math.round((ago / 1000)) == 1) { agoString = Math.round((ago / 1000)) + ' second ago'; } else { agoString = Math.round((ago / 1000)) + ' seconds ago'; } } else if (ago < (1000 * 60 * 60)) { if (Math.round((ago / 1000) / 60) == 1) { agoString = Math.round((ago / 1000) / 60) + ' minute ago'; } else { agoString = Math.round((ago / 1000) / 60) + ' minutes ago'; } } else if (ago < (1000 * 60 * 60 * 60)) { if (Math.round(((ago / 1000) / 60) / 60) == 1) { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hour ago'; } else { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hours ago'; } } historyHtml = historyHtml + '<tr><td><a href="javascript:void(0);" onclick="historyInTaxPanel(\'' + panel.divElement.id + '\',\'' + field.conceptId + '\');">' + field.term + '</a>'; historyHtml = historyHtml + ' <span class="text-muted" style="font-size: 80%"><em>' + agoString + '<em></span>'; historyHtml = historyHtml + '</td></tr>'; }); historyHtml = historyHtml + '</table>'; historyHtml = historyHtml + '</div>'; return historyHtml; } }); $("#" + panel.divElement.id + "-historyButton").popover('toggle'); }); // $("#" + panel.divElement.id + "-linkerButton").click(function(event) { // $("#" + panel.divElement.id + "-linkerButton").popover({ // trigger: 'manual', // placement: 'bottomRight', // html: true, // content: function() { // linkerHtml = '<div class="text-center text-muted"><em>Drag to link with other panels<br>'; // if (panel.subscriptions.length == 1) { // linkerHtml = linkerHtml + panel.subscriptions.length + ' link established</em></div>'; // } else { // linkerHtml = linkerHtml + panel.subscriptions.length + ' links established</em></div>'; // } // linkerHtml = linkerHtml + '<div class="text-center"><a href="javascript:void(0);" onclick="clearTaxonomyPanelSubscriptions(\'' + panel.divElement.id + '\');">Clear links</a></div>'; // return linkerHtml; // } // }); // $("#" + panel.divElement.id + "-linkerButton").popover('toggle'); // }); $("#" + panel.divElement.id + "-descendantsCountTrue").click(function(event) { panel.options.descendantsCount = true; $("#" + panel.divElement.id + '-txViewLabel2').html("Descendants Count: On"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "inferredDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-descendantsCountFalse").click(function(event) { panel.options.descendantsCount = false; $("#" + panel.divElement.id + '-txViewLabel2').html("Descendants Count: Off"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "inferredDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-inferredViewButton").click(function(event) { panel.options.selectedView = 'inferred'; $("#" + panel.divElement.id + '-txViewLabel').html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "inferredDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-statedViewButton").click(function(event) { panel.options.selectedView = 'stated'; $("#" + panel.divElement.id + '-txViewLabel').html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); }); //$("#" + panel.divElement.id + "-inferredViewButton").click(); $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor); } this.setupOptionsPanel = function() { var possibleSubscribers = []; $.each(componentsRegistry, function(i, field) { if (field.divElement.id != panel.divElement.id) { var object = {}; object.subscriptions = field.subscriptions; object.id = field.divElement.id; possibleSubscribers.push(object); } }); var aux = false; $.each(possibleSubscribers, function(i, field) { aux = false; $.each(panel.subscriptions, function(j, subscription) { if (field.id == subscription.topic) { aux = true; } }); field.subscribed = aux; aux = false; $.each(field.subscriptions, function(i, subscription) { if (subscription.topic == panel.divElement.id) { aux = true; } }); field.subscriptor = aux; }); panel.options.possibleSubscribers = possibleSubscribers; var context = { options: panel.options, divElementId: panel.divElement.id }; $("#" + panel.divElement.id + "-modal-body").html(JST["views/taxonomyPlugin/options.hbs"](context)); } this.readOptionsPanel = function() { $.each(panel.options.possibleSubscribers, function(i, field) { field.subscribed = $("#" + panel.divElement.id + "-subscribeTo-" + field.id).is(':checked'); field.subscriptor = $("#" + panel.divElement.id + "-subscriptor-" + field.id).is(':checked'); var panelToSubscribe = {}; $.each(componentsRegistry, function(i, panelS) { if (panelS.divElement.id == field.id) { panelToSubscribe = panelS; } }); if (field.subscribed) { panel.subscribe(panelToSubscribe); } else { panel.unsubscribe(panelToSubscribe); } if (field.subscriptor) { panelToSubscribe.subscribe(panel); } else { panelToSubscribe.unsubscribe(panel); } }); $.each(componentsRegistry, function(i, field) { if (field.loadMarkers) field.loadMarkers(); }); } this.setupParents = function(parents, focusConcept) { var lastParent; $.each(parents, function(i, parent) { lastParent = parent; }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a > b) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_def', function(conceptId, opts) { if (conceptId == panel.default.conceptId) return opts.fn(this); else return opts.inverse(this); }); var context = { parents: parents, focusConcept: focusConcept, divElementId: panel.divElement.id }; Handlebars.registerHelper('slice', function(a, b) { $("#" + panel.divElement.id + "-panelBody").html($("#" + panel.divElement.id + "-panelBody").html().slice(a, b)); }); $("#" + panel.divElement.id + "-panelBody").html(JST["views/taxonomyPlugin/body/parents.hbs"](context)); if (panel.options.descendantsCount == true) { var auxArray = parents; auxArray.push(focusConcept); auxArray.forEach(function(concept) { var descedants = concept.inferredDescendants; if (panel.options.selectedView == 'stated') { descedants = concept.statedDescendants; } // $.ajax({ // type: "POST", // url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", // data: { // expression: "< " + concept.conceptId + "|" + concept.defaultTerm + "|", // limit : 1, // skip : 0, // form: panel.options.selectedView // }, // dataType: "json", // success: function(result) { // if (result.computeResponse) { $("#" + panel.divElement.id + "-panelBody").find('.selectable-row[data-concept-id="' + concept.conceptId + '"]').append("&nbsp;&nbsp;&nbsp;&nbsp;<span class='text-muted'>" + descedants + "</span>"); // } // } // }).done(function(result){ // // done // }); }); } //console.log(JST["views/taxonomyPlugin/body/parents.hbs"](context)); $(".treeButton").disableTextSelect(); $("#" + panel.divElement.id + "-panelBody").unbind("dblclick"); $("#" + panel.divElement.id + "-panelBody").dblclick(function(event) { if ($(event.target).hasClass("treeLabel")) { var d = new Date(); var time = d.getTime(); var selectedModule = $(event.target).attr('data-module'); var selectedId = $(event.target).attr('data-concept-id'); var selectedLabel = $(event.target).attr('data-term'); var statedDescendants = $(event.target).attr('data-statedDescendants'); var inferredDescendants = $(event.target).attr('data-inferredDescendants'); panel.history.push({ term: selectedLabel, conceptId: selectedId, time: time }); if (typeof selectedId != "undefined") { $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + selectedId + "/parents?form=" + panel.options.selectedView, function(result) { // done }).done(function(result) { panel.setupParents(result, { conceptId: selectedId, defaultTerm: selectedLabel, definitionStatus: "PRIMITIVE", module: selectedModule, statedDescendants: statedDescendants, inferredDescendants: inferredDescendants }); }).fail(function() {}); } } }); $("#" + panel.divElement.id + "-panelBody").unbind("click"); $("#" + panel.divElement.id + "-panelBody").click(function(event) { if ($(event.target).hasClass("treeButton")) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); var iconId = panel.divElement.id + "-treeicon-" + conceptId; event.preventDefault(); if ($("#" + iconId).hasClass("glyphicon-chevron-down")) { //console.log("close"); $(event.target).closest("li").find("ul").remove(); $("#" + iconId).removeClass("glyphicon-chevron-down"); $("#" + iconId).addClass("glyphicon-chevron-right"); } else if ($("#" + iconId).hasClass("glyphicon-chevron-right")) { //console.log("open"); $("#" + iconId).removeClass("glyphicon-chevron-right"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); panel.getChildren($(event.target).closest("li").attr('data-concept-id')); } else if ($("#" + iconId).hasClass("glyphicon-chevron-up")) { $("#" + iconId).removeClass("glyphicon-chevron-up"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); panel.wrapInParents($(event.target).closest("li").attr('data-concept-id'), $(event.target).closest("li")); } else if ($("#" + iconId).hasClass("glyphicon-minus")) { // $("#" + iconId).removeClass("glyphicon-minus"); // $("#" + iconId).addClass("glyphicon-chevron-right"); } } else if ($(event.target).hasClass("treeLabel")) { var selectedId = $(event.target).attr('data-concept-id'); if (typeof selectedId != "undefined") { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: selectedId, source: panel.divElement.id }); } } }); var iconId = panel.divElement.id + "-treeicon-" + focusConcept.conceptId; $("#" + iconId).removeClass("glyphicon-chevron-right"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); //console.log("getChildren..." + focusConcept.conceptId); panel.getChildren(focusConcept.conceptId); }; this.getChildren = function(conceptId) { if (typeof panel.options.selectedView == "undefined") { panel.options.selectedView = "inferred"; } if (panel.options.selectedView == "inferred") { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); } else { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); } if (panel.options.descendantsCount == true) $("#" + panel.divElement.id + "-txViewLabel2").html("Descendants Count: On"); else $("#" + panel.divElement.id + "-txViewLabel2").html("Descendants Count: Off"); $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/children?form=" + panel.options.selectedView, function(result) {}).done(function(result) { if (result && result[0] && typeof result[0].statedDescendants == "undefined") $("#" + panel.divElement.id + "-txViewLabel2").closest("li").hide(); result.forEach(function(c) {setDefaultTerm(c)}); result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); //console.log(JSON.stringify(result)); var listIconIds = []; //console.log(JSON.stringify(listIconIds)); var context = { result: result, divElementId: panel.divElement.id, selectedView: panel.options.selectedView }; Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('push', function(element) { listIconIds.push(element); }); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); if (result.length > 0) { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down"); } else { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); } $("#" + panel.divElement.id + "-treenode-" + conceptId).closest("li").append(JST["views/taxonomyPlugin/body/children.hbs"](context)); if (panel.options.descendantsCount == true) { result.forEach(function(concept) { if (concept.active) { var descedants = concept.inferredDescendants; if (panel.options.selectedView == 'stated') { descedants = concept.statedDescendants; } // $.ajax({ // type: "POST", // url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", // data: { // expression: "< " + concept.conceptId + "|" + concept.defaultTerm + "|", // limit : 1, // skip : 0, // form: panel.options.selectedView // }, // dataType: "json", // success: function(result) { // if (result.computeResponse) { $("#" + panel.divElement.id + "-treenode-" + conceptId).closest("li").find('.selectable-row[data-concept-id="' + concept.conceptId + '"]').append("&nbsp;&nbsp;&nbsp;&nbsp;<span class='text-muted'>" + descedants + "</span>"); // } // } // }).done(function(result){ // // done // }); } }); } $(".treeButton").disableTextSelect(); if (typeof i18n_drag_this == "undefined") { i18n_drag_this = "Drag this"; } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() { $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); }); } this.wrapInParents = function(conceptId, liItem) { var topUl = $("#" + panel.divElement.id + "-panelBody").find('ul:first'); $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/parents?form=" + panel.options.selectedView, function(parents) { // done }).done(function(parents) { if (parents.length > 0) { var firstParent = "empty"; var parentsStrs = []; $.each(parents, function(i, parent) { var parentLiHtml = "<li data-concept-id='" + parent.conceptId + "' data-term='" + parent.defaultTerm + "' class='treeLabel'>"; parentLiHtml = parentLiHtml + "<button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-chevron-"; if (parent.conceptId == "138875005" || parent.conceptId == "9999999999") { parentLiHtml = parentLiHtml + "down"; } else { parentLiHtml = parentLiHtml + "up"; } parentLiHtml = parentLiHtml + " treeButton' id='" + panel.divElement.id + "-treeicon-" + parent.conceptId + "'></i></button>"; if (parent.definitionStatus == "PRIMITIVE") { parentLiHtml = parentLiHtml + '<span class="badge alert-warning" data-concept-id="' + parent.conceptId + '" data-term="' + parent.defaultTerm + '" draggable="true" ondragstart="drag(event)" class="treeLabel selectable-row" id="' + panel.divElement.id + '-treenode-' + parent.conceptId + '">&nbsp;&nbsp;</span>&nbsp;&nbsp;'; } else { parentLiHtml = parentLiHtml + '<span class="badge alert-warning" data-concept-id="' + parent.conceptId + '" data-term="' + parent.defaultTerm + '" draggable="true" ondragstart="drag(event)" class="treeLabel selectable-row" id="' + panel.divElement.id + '-treenode-' + parent.conceptId + '">&equiv;</span>&nbsp;&nbsp;'; } if (countryIcons[parent.module]) { parentLiHtml = parentLiHtml + "<div class='phoca-flagbox' style='width:33px;height:33px'><span class='phoca-flag " + countryIcons[parent.module] + "'></span></div> "; } parentLiHtml = parentLiHtml + '<a href="javascript:void(0);" style="color: inherit;text-decoration: inherit;"><span class="treeLabel selectable-row" data-concept-id="' + parent.conceptId + '" data-term="' + parent.defaultTerm + '"> ' + parent.defaultTerm + '</span></a>'; parentLiHtml = parentLiHtml + "</li>"; parentsStrs.push(parentLiHtml); if (firstParent == "empty") { firstParent = parent.conceptId; } }); var staticChildren = topUl.children().slice(0); topUl.append(parentsStrs[0]); $('#' + panel.divElement.id + '-treenode-' + firstParent).closest('li').append("<ul id='parent-ul-id-" + firstParent + "' style='list-style-type: none; padding-left: 15px;'></ul>"); if (panel.options.descendantsCount == true) { parents.forEach(function(concept) { var descedants = concept.inferredDescendants; if (panel.options.selectedView == 'stated') { descedants = concept.statedDescendants; } // $.ajax({ // type: "POST", // url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", // data: { // expression: "< " + concept.conceptId + "|" + concept.defaultTerm + "|", // limit : 1, // skip : 0, // form: panel.options.selectedView // }, // dataType: "json", // success: function(result) { // if (result.computeResponse) { $(topUl).find('.selectable-row[data-concept-id="' + concept.conceptId + '"]').append("&nbsp;&nbsp;&nbsp;&nbsp;<span class='text-muted'>" + descedants + "</span>"); // } // } // }).done(function(result){ // // done // }); }); } var newMainChild; $.each(staticChildren, function(i, child) { if ($(child).attr('data-concept-id') == conceptId) { newMainChild = $(child); var newUl = $('#' + panel.divElement.id + '-treenode-' + firstParent).closest('li').find('ul:first'); newUl.append($(child)); $(child).find('i:first').removeClass("glyphicon-chevron-up"); $(child).find('i:first').addClass("glyphicon-chevron-down"); } }); $.each(staticChildren, function(i, child) { if ($(child).attr('data-concept-id') != conceptId) { $.each($(child).children(), function(i, subchild) { if ($(subchild).is('ul')) { newMainChild.append(subchild); } }); $('#' + panel.divElement.id + '-treenode-' + $(child).attr('data-concept-id')).closest('li').remove(); } }); $.each(parentsStrs, function(i, parentsStr) { if (parentsStr != parentsStrs[0]) { topUl.prepend(parentsStr); } }); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down"); } else { $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-up"); } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() {}); } this.setToConcept = function(conceptId, term, definitionStatus, module, statedDescendants) { $("#" + panel.divElement.id + "-panelBody").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/parents?form=" + panel.options.selectedView, function(result) { $.each(result, function(i, item) { if (typeof item.defaultTerm == "undefined") { item.defaultTerm = item.fsn.term; } }); }).done(function(result) { if (definitionStatus != "PRIMITIVE" && definitionStatus != "FULLY_DEFINED") { definitionStatus = "PRIMITIVE"; } if (conceptId == 138875005) statedDescendants = options.rootConceptDescendants; if (typeof term == "undefined" || typeof statedDescendants == "undefined") { $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId, function(res) { term = res.fsn.term; if (typeof res.statedDescendants == "undefined") $("#" + panel.divElement.id + "-txViewLabel2").closest("li").hide(); statedDescendants = res.statedDescendants; panel.setupParents(result, { conceptId: conceptId, defaultTerm: term, definitionStatus: definitionStatus, module: module, statedDescendants: statedDescendants }); }); } else { panel.setupParents(result, { conceptId: conceptId, defaultTerm: term, definitionStatus: definitionStatus, module: module, statedDescendants: statedDescendants }); } }).fail(function() { $("#" + panel.divElement.id + "-panelBody").html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); }); } // Subscription methods this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; // console.log('Subscribing to id: ' + panelId); var alreadySubscribed = false; $.each(panel.subscriptionsColor, function(i, field) { if (field == panelToSubscribe.markerColor) { alreadySubscribed = true; } }); if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { // console.log("listening in " + panel.divElement.id); panel.setToConcept(data.conceptId, data.term, data.definitionStatus, data.module, data.statedDescendants); }); panel.subscriptions.push(subscription); panelToSubscribe.subscribers.push(panel.divElement.id); panel.subscriptionsColor.push(panelToSubscribe.markerColor); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-subscribersMarker").show(); } this.refsetSubscribe = function(refsetId) { channel.subscribe("refsetSubscription-" + refsetId, function(data, envelope) { panel.setToConcept(data.conceptId); }); } this.unsubscribe = function(panelToUnsubscribe) { var aux = [], colors = [], unsubscribed = true; $.each(panel.subscriptionsColor, function(i, field) { if (field != panelToUnsubscribe.markerColor) { colors.push(field); } else { unsubscribed = false; } }); if (!unsubscribed) { panel.subscriptionsColor = colors; // console.log(panel.divElement.id); // console.log(panel.subscriptionsColor); colors = []; $.each(panelToUnsubscribe.subscribers, function(i, field) { if (field != panel.divElement.id) { aux.push(field); } }); panelToUnsubscribe.subscribers = aux; $.each(panelToUnsubscribe.subscriptionsColor, function(i, field) { colors.push(field); }); if (panelToUnsubscribe.subscribers.length == 0) { if (panelToUnsubscribe.subscriptions.length == 0) { $("#" + panelToUnsubscribe.divElement.id + "-subscribersMarker").hide(); } } else { // colors.push(panelToUnsubscribe.markerColor); } panelToUnsubscribe.subscriptionsColor = colors; // console.log(panelToUnsubscribe.divElement.id); // console.log(panelToUnsubscribe.subscriptionsColor); aux = []; $.each(panel.subscriptions, function(i, field) { if (panelToUnsubscribe.divElement.id == field.topic) { field.unsubscribe(); } else { aux.push(field); } }); panel.subscriptions = aux; if (panel.subscriptions.length == 0 && panel.subscribers.length == 0) { $("#" + panel.divElement.id + "-subscribersMarker").hide(); } } } this.loadMarkers = function() { var auxMarker = "", right = 0, top = 0, aux = false, visible = false; $.each(componentsRegistry, function(i, field) { var panelId = field.divElement.id; if ($("#" + panelId + "-subscribersMarker").is(':visible')) { visible = true; } }); if (panel.subscribers.length == 0) { right = 14; $("#" + panel.divElement.id + "-ownMarker").hide(); } else { if (!visible) { $("#" + panel.divElement.id + "-ownMarker").hide(); } aux = true; } if ($("#" + panel.divElement.id + "-subscribersMarker").is(':visible')) { $("#" + panel.divElement.id + "-panelTitle").html($("#" + panel.divElement.id + "-panelTitle").html().replace(/&nbsp;/g, '')); if (aux) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); } $.each(panel.subscriptionsColor, function(i, field) { auxMarker = auxMarker + "<i class='glyphicon glyphicon-bookmark' style='color: " + field + "; top:" + top + "px; right: " + right + "px;'></i>"; $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); top = top + 5; right = right + 10; }); $("#" + panel.divElement.id + "-subscribersMarker").html(auxMarker); } } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setupCanvas(); if (!conceptId || conceptId == 138875005) { this.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); } else { if (xhr != null) { xhr.abort(); //console.log("aborting call..."); } xhr = $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId, function(result) { if (typeof result.statedDescendants == "undefined") $("#" + panel.divElement.id + "-txViewLabel2").closest("li").hide(); }).done(function(result) { if (panel.options.selectedView == 'stated') { panel.setToConcept(conceptId, result.defaultTerm, result.definitionStatus, result.module, result.statedDescendants); } else { panel.setToConcept(conceptId, result.defaultTerm, result.definitionStatus, result.module, result.inferredDescendants); } }).fail(function() { //console.log("Error"); }); } } function clearTaxonomyPanelSubscriptions(divElementId1) { var d1; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == divElementId1) { d1 = field; } }); d1.unsubscribeAll(); $("#" + divElementId1).find('.linker-button').popover('toggle'); } function historyInTaxPanel(divElementId, conceptId) { $.each(componentsRegistry, function(i, field) { //console.log(field.divElement.id + ' == ' + divElementId); if (field.divElement.id == divElementId) { // $('#' + divElementId + '-searchBox').val(searchTerm); // field.search(searchTerm,0,100,false); field.setToConcept(conceptId); } }); $('.history-button').popover('hide'); } (function($) { $.fn.addTaxonomy = function(options) { this.filter("div").each(function() { var tx = new conceptDetails(this, options); }); }; }(jQuery)); /** * Created by termmed on 9/2/14. */ /** * Created by termmed on 9/1/14. */ function refsetPanel(divElement, options) { var panel = this; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var favoriteCall = null; this.type = "favorites"; panel.subscribers = []; var xhrMembers = null; this.getConceptId = function() { return this.conceptId; } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setUpPanel = function() { var context = { divElementId: panel.divElement.id } $(divElement).html(JST["views/refsetPlugin/main.hbs"](context)); } panel.setUpPanel(); this.loadRefsets = function() { // console.log(panel.options.manifest); if (panel.options.manifest) { panel.options.manifest.refsets.sort(function(a, b) { if (a.type == "daily-build" && a.type != b.type) return -1; if (a.type < b.type) return -1; if (a.type > b.type) return 1; if (a.defaultTerm < b.defaultTerm) return -1; if (a.defaultTerm > b.defaultTerm) return 1; return 0; }); var context = { divElementId: panel.divElement.id, refsets: panel.options.manifest.refsets } $("#" + panel.divElement.id + "-panelBody").html(JST["views/refsetPlugin/body.hbs"](context)); $('#' + panel.divElement.id + '-panelBody').find(".refset-item").click(function(event) { panel.loadMembers($(event.target).attr('data-concept-id'), $(event.target).attr('data-term'), 100, 0); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); } else { $("#" + panel.divElement.id + "-panelBody").html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); } } panel.loadRefsets(); this.loadMembers = function(conceptId, term, returnLimit, skipTo, paginate) { var membersUrl = options.serverUrl + "/" + options.edition + "/" + options.release + "/members?referenceSet=" + conceptId + "&limit=100"; if (skipTo > 0) { membersUrl = membersUrl + "&offset=" + skipTo; } else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><i class='glyphicon glyphicon-refresh icon-spin'></i></td></tr>"); } var total; if (panel.options.manifest) { $.each(panel.options.manifest.refsets, function(i, field) { if (field.conceptId == panel.conceptId) { if (field.count) { total = field.count; } } }); } if (typeof total != "undefined") { //if (total < 25000){ paginate = 1; membersUrl = membersUrl + "&paginate=1"; //} } // console.log(membersUrl); if (xhrMembers != null) { xhrMembers.abort(); //console.log("aborting call..."); } xhrMembers = $.getJSON(membersUrl, function(result) { }).done(function(result) { var remaining = "asd"; if (typeof total == "undefined") total = result.total; if (total == skipTo) { remaining = 0; } else { if (total > (skipTo + returnLimit)) { remaining = total - (skipTo + returnLimit); } else { // if (result.details.total < returnLimit && skipTo != 0){ remaining = 0; // }else{ // remaining = result.details.total; // } } } if (remaining < returnLimit) { var returnLimit2 = remaining; } else { if (remaining != 0) { var returnLimit2 = returnLimit; } else { var returnLimit2 = 0; } } var context = { result: result, returnLimit: returnLimit2, remaining: remaining, divElementId: panel.divElement.id, skipTo: skipTo, term: term, conceptId: conceptId }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); if (result.total != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#' + panel.divElement.id + "-resultsTable").html(JST["views/refsetPlugin/members.hbs"](context)); } else { $('#' + panel.divElement.id + "-resultsTable").append(JST["views/refsetPlugin/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); skipTo = skipTo + returnLimit; panel.loadMembers(conceptId, term, returnLimit2, skipTo, paginate); }); $("#" + panel.divElement.id + "-sort").unbind(); $("#" + panel.divElement.id + "-sort").click(function() { $("#" + panel.divElement.id + "-sort").blur(); panel.loadMembers(conceptId, term, returnLimit2, 0, 1); }); } else { if (skipTo != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#' + panel.divElement.id + "-resultsTable").html(JST["views/refsetPlugin/members.hbs"](context)); } else { $('#' + panel.divElement.id + "-resultsTable").append(JST["views/refsetPlugin/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); skipTo = skipTo + returnLimit; panel.loadMembers(conceptId, term, returnLimit2, skipTo, paginate); }); $("#" + panel.divElement.id + "-sort").unbind(); $("#" + panel.divElement.id + "-sort").click(function() { $("#" + panel.divElement.id + "-sort").blur(); panel.loadMembers(conceptId, term, returnLimit2, 0, 1); }); } else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } } $('#' + panel.divElement.id + '-resultsTable').find(".member-concept-row").click(function(event) { var clickedBadge = $(event.target).closest(".member-concept-row").find(".badge"); channel.publish(panel.divElement.id, { term: clickedBadge.attr('data-term'), module: clickedBadge.attr("data-module"), conceptId: clickedBadge.attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function(err) { if (xhrMembers.status === 0) { if (xhrMembers.statusText === 'abort') {} else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } } else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } }); } } /** * Created by termmed on 9/1/14. */ function favoritePanel(divElement, options) { var panel = this; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var favoriteCall = null; this.type = "favorites"; panel.subscribers = []; // if (!componentsRegistry){ // componentsRegistry = []; // componentsRegistry.push(panel); // }else{ // componentLoaded = false; // $.each(componentsRegistry, function(i, field) { // if (field.divElement.id == panel.divElement.id) { // componentLoaded = true; // } // }); // if (componentLoaded == false) { // componentsRegistry.push(panel); // } // } this.getConceptId = function() { return this.conceptId; } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setUpFavs = function (){ // var context = { // divElementId: panel.divElement.id // } // $(divElement).html(JST["views/favorites/main.hbs"](context)); } //panel.setUpFavs(); this.loadFavs = function (){ $("#" + panel.divElement.id + "-panelBody").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); var favs = stringToArray(localStorage.getItem("favs")), concepts = []; function loadFavsTemplate(concepts){ var context = { concepts: concepts } $("#" + panel.divElement.id + "-panelBody").html(JST["views/favorites/body.hbs"](context)); $('#' + panel.divElement.id + '-panelBody').find(".glyphicon-remove-circle").click(function (e) { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; $.each(favs, function(i,field){ if (field != $(e.target).attr("data-concept-id")){ auxFavs.push(field); } }); localStorage.setItem("favs", auxFavs); localStorage.removeItem("conceptId:" + $(e.target).attr("data-concept-id")); panel.loadFavs(); }); $("#exportFavsXls").click(function(){ return ExcellentExport.excel(this, 'tableFavs'); }); $('#' + panel.divElement.id + '-panelBody').find(".fav-item").click(function (event) { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); } var length = favs.length - 1; $.each(favs, function(i, field){ var concept = localStorage.getItem("conceptId:" + field); concept = JSON.parse(concept); concepts.push(concept); }); loadFavsTemplate(concepts); } channel.subscribe("favsAction", function() { panel.loadFavs(); }); $("#" + panel.divElement.id + "-li").click(function(){ panel.loadFavs(); }); } /** * Created by termmed on 9/1/14. */ function queryComputerPanel(divElement, options) { var panel = this; panel.showId = false; var limit = 100; var skip = 0; var xhrTotal = null; var xhrExecute = null; panel.currentEx = 0; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); this.type = "query-computer"; panel.subscribers = []; panel.totalResults = []; if (!componentsRegistry) { componentsRegistry = []; componentsRegistry.push(panel); } else { var componentLoaded = false; $.each(componentsRegistry, function(i, field) { if (field.divElement && field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } //panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); panel.markerColor = "asdasdasdas"; this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; var alreadySubscribed = false; if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { if (data) { panel.updateCanvas(data); } }); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-ownMarker").show(); } this.setUpPanel = function() { var context = { divElementId: panel.divElement.id, examples: [{ title: "All excision procedures that are also procedures on the digestive system", context: [{ modifier: "Include", criterias: [ { criteria: "descendantOf", conceptId: "65801008", term: "Excision (procedure)" }, { criteria: "descendantOf", conceptId: "118673008", term: "Procedure on digestive system (procedure)" } ] }] }, { title: "All pneumonias except intersticial pneumonias", context: [{ modifier: "Include", criterias: [ { criteria: "descendantOf", conceptId: "233604007", term: "Pneumonia (disorder)" } ] }, { modifier: "Exclude", criterias: [ { criteria: "descendantOrSelfOf", conceptId: "64667001", term: "Interstitial pneumonia (disorder)" } ] } ] }, { title: "Hypertension related concepts, disorders, personal history and family history", context: [{ modifier: "Include", criterias: [ { criteria: "descendantOf", conceptId: "38341003", term: "Hypertensive disorder, systemic arterial (disorder)" } ] }, { modifier: "Include", criterias: [ { criteria: "self", conceptId: "160273004", term: "No family history: Hypertension (situation)" } ] }, { modifier: "Include", criterias: [ { criteria: "descendantOrSelfOf", conceptId: "161501007", term: "History of hypertension (situation)" } ] }, { modifier: "Include", criterias: [ { criteria: "descendantOrSelfOf", conceptId: "160357008", term: "Family history: Hypertension (situation)" } ] } ] } //{ // title: "", // context: [ // { // modifier: "", // criterias: [ // {criteria: "", conceptId: "", term: "", type: {conceptId: "", term: ''}} // ] // } // ] //}, ] }; $(divElement).html(JST["views/developmentQueryPlugin/main.hbs"](context)); $(divElement).find('textarea').unbind(); $(divElement).find('textarea').keypress(function(event) { if (event.which == 13) { event.preventDefault(); var s = $(this).val(); $(this).val(s + "\n"); } }); $('[data-toggle="tooltip"]').tooltip(); $("#" + panel.divElement.id + "-ExamplesModal").scrollspy({ target: '#' + panel.divElement.id + '-sidebar', offset: 80 }); var clicked = false; $("#" + panel.divElement.id + "-mynav li a").click( function() { //console.log('click...'); $('#' + panel.divElement.id + '-mycontent > div > h4').css('padding-top', 0); $($(this).attr('href') + ' > h4').css('padding-top', '50px'); clicked = true; } ); $("#" + panel.divElement.id + "-ExamplesModal").on('activate.bs.scrollspy', function() { //console.log('scrolling...'); if (!clicked) $('#' + panel.divElement.id + '-mycontent > div > h4').css('padding-top', 0); clicked = false; }); $("#" + panel.divElement.id + "-ExamplesModal").on('shown.bs.modal', function() { $("#" + panel.divElement.id + "-mycontentExamples").html(JST["views/developmentQueryPlugin/examples.hbs"](context)); context.examples.forEach(function(item, index) { var contextHtml = ""; item.context.forEach(function(loopContext) { //contextHtml+= JST[""(loopContext)]; contextHtml += JST["views/developmentQueryPlugin/criteria.hbs"](loopContext); }); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().html(contextHtml); if ($("#" + panel.divElement.id + "-ExpTab").hasClass("active")) { contextHtml = panel.exportToConstraintGrammar(true, false, false, $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first()); if (contextHtml.indexOf("(") == 0) contextHtml = contextHtml.substr(1, contextHtml.length - 2); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().html(contextHtml); } $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().find(".btn").addClass("disabled"); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".query-condition").each(function(index) { $(this).find(".line-number").html(index + 1); }); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".loadExample").first().attr("data-htmlValue", $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().html()); }); $("#" + panel.divElement.id + "-mycontentExamples").find(".loadExample").unbind(); $("#" + panel.divElement.id + "-mycontentExamples").find(".loadExample").click(function(e) { var htmlToPut = $(e.target).attr("data-htmlValue"); if ($("#" + panel.divElement.id + "-ExpTab").hasClass("active")) { $('#' + panel.divElement.id + '-ExpText').html(htmlToPut); $('#' + panel.divElement.id + '-ExpText').val(htmlToPut.replace(/(<([^>]+)>)/ig, "").replace(/&nbsp;/g, " ").replace(/&lt;/g, "<")); $("#" + panel.divElement.id + "-ExamplesModal").modal("hide"); } else { $('#' + panel.divElement.id + '-listGroup').html(htmlToPut); $('#' + panel.divElement.id + '-listGroup').find(".btn").removeClass("disabled"); $('#' + panel.divElement.id + '-listGroup').find(".query-condition").each(function(i) { var critToUpdate = $(this); $(critToUpdate).find("small").remove(); $(critToUpdate).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); $("#" + panel.divElement.id + "-ExamplesModal").modal("hide"); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critToUpdate), true, function(resultCount) { $(critToUpdate).find("small").remove(); $(critToUpdate).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critToUpdate).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").unbind(); $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").click(function(e) { var prevValue = $(e.target).closest(".constraint").attr('data-criteria'); var newValue = $(e.target).html(); if (prevValue != newValue) { $(e.target).closest(".constraint").attr('data-criteria', newValue); $(e.target).closest("div").find("button").first().html(newValue + "&nbsp;"); var critToUpdate = $(e.target).closest(".query-condition"); $(critToUpdate).find("small").remove(); $(critToUpdate).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critToUpdate), true, function(resultCount) { $(critToUpdate).find("small").remove(); $(critToUpdate).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critToUpdate).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); } }); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); }); } }); }); if (!panel.typeArray || !panel.typeArray.length) { $.ajax({ type: "POST", url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", data: { expression: "< 410662002|Concept model attribute (attribute)|", limit: 5000, skip: 0, form: "inferred" }, dataType: "json", //timeout: 300000, success: function(result) { //console.log(result); //console.log(result.computeResponse.matches); result.computeResponse.matches.push({ conceptId: "<< 47429007", defaultTerm: "Associated with (attribute) [<<]" }); result.computeResponse.matches.push({ conceptId: "<< 405815000", defaultTerm: "Procedure device (attribute) [<<]" }); result.computeResponse.matches.push({ conceptId: "<< 405816004", defaultTerm: "Procedure morphology (attribute) [<<]" }); result.computeResponse.matches.push({ conceptId: "<< 363704007", defaultTerm: "Procedure site (attribute) [<<]" }); panel.typeArray = result.computeResponse.matches; panel.typeArray.sort(function(a, b) { if (a.defaultTerm < b.defaultTerm) return -1; if (a.defaultTerm > b.defaultTerm) return 1; return 0; }); } }).done(function(result) { }); } //$.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/410662002/children?form=inferred").done(function(result) { // //console.log(result); // result.sort(function (a, b) { // if (a.defaultTerm < b.defaultTerm) // return -1; // if (a.defaultTerm > b.defaultTerm) // return 1; // return 0; // }); // panel.typeArray = result; //}); //$("#" + panel.divElement.id + "-ExamplesModal").find(".btn").addClass("disabled"); //$("#" + panel.divElement.id + "-ExamplesModal").find(".loadExample").removeClass("disabled"); //$("#" + panel.divElement.id + "-ExamplesModal-close").removeClass("disabled"); var bindAddCriteriaFunction = function() { $(divElement).find(".addCriteria").unbind(); $(divElement).find(".addCriteria").disableTextSelect(); $(divElement).find(".addCriteria").click(function(e) { $(e.target).closest(".form-group").hide(); var criteria = $('#' + panel.divElement.id + '-selectedCriteria').html(); var typeSelected = $(e.target).attr("data-type"); if ($(divElement).find(".addedCriteria").length) typeSelected = $(divElement).find(".addedCriteria").first().attr("data-typeSelected"); $(e.target).closest(".form-inline").append(JST["views/developmentQueryPlugin/andCriteria.hbs"]({ criteria: criteria, typeSelected: typeSelected, types: panel.typeArray })); $(divElement).find(".addedCriteria").find(".selectTypeOpt").unbind(); $(divElement).find(".addedCriteria").find(".selectTypeOpt").click(function(e) { $(e.target).closest(".typeCritCombo").attr("data-type-term", $(e.target).attr("data-term")); $(e.target).closest(".typeCritCombo").attr("data-type-concept-id", $(e.target).attr("data-id")); var term = $(e.target).attr("data-term"); if (term.length > 15) term = term.substr(0, 14) + "..."; $(e.target).closest("div").find("span").first().html(term); }); $(divElement).find(".addedCriteria").find(".removeCriteria").unbind(); $(divElement).find(".addedCriteria").find(".removeCriteria").click(function(e) { $(e.target).closest(".addedCriteria").remove(); var foundAddedCriteria = $(divElement).find(".addedCriteria"); if (!foundAddedCriteria.length) { $("#" + panel.divElement.id + "-addCriteriaAnd").show(); } else { $(divElement).find(".addedCriteria").find(".dropFirstType").hide(); $(divElement).find(".addedCriteria").first().find(".dropFirstType").first().show(); //console.log($(foundAddedCriteria[foundAddedCriteria.length - 1]).find(".addCriteria").first().closest(".form-group")); $(foundAddedCriteria[foundAddedCriteria.length - 1]).find(".addCriteria").first().closest(".form-group").show(); } }); $(divElement).find(".addedCriteria").find("a[data-role='criteria-selector']").unbind(); $(divElement).find(".addedCriteria").find("a[data-role='criteria-selector']").click(function(e) { $(e.target).closest(".dropdown").find("span").first().html($(e.target).html()); }); bindAddCriteriaFunction(); }); }; bindAddCriteriaFunction(); $('#' + panel.divElement.id + '-addCriteriaAnd').unbind(); $('#' + panel.divElement.id + '-clearButton').unbind(); $('#' + panel.divElement.id + '-clearButton').disableTextSelect(); $('#' + panel.divElement.id + '-clearButton').click(function() { if (xhrExecute != null) xhrExecute.abort(); panel.setUpPanel(); }); $('#' + panel.divElement.id + '-copyConstraint').unbind(); $("#" + panel.divElement.id + "-copyConstraint").disableTextSelect(); var clientGrammar = new ZeroClipboard(document.getElementById(panel.divElement.id + "-copyConstraint")); clientGrammar.on("ready", function(readyEvent) { clientGrammar.on("copy", function(event) { // var grammar = panel.exportToConstraintGrammar(false, fullSyntax); //console.log(grammar); $("#" + panel.divElement.id + "-copyConstraint").addClass("animated rubberBand"); window.setTimeout(function() { $("#" + panel.divElement.id + "-copyConstraint").removeClass('animated rubberBand'); }, 1000); alertEvent("Constraint Grammar copied to clipboard", "success"); var clipboard = event.clipboardData; clipboard.setData("text/plain", panel.grammarToCopy); }); }); panel.options.devQuery = true; $('#' + panel.divElement.id + '-exportXls').unbind(); $('#' + panel.divElement.id + '-exportXls').click(function(e) { // var rowsHtml = ""; // alertEvent("Please wait", "info"); // panel.getTotalResults(function(){ // $.each(panel.allResults, function(i, field){ // rowsHtml+= "<tr><td>" + field.defaultTerm + "</td><td>" + field.conceptId + "</td></tr>"; // }); // $("#" + panel.divElement.id + "-outputBody2").html(rowsHtml); if (panel.allResults) { return ExcellentExport.excel(this, panel.divElement.id + '-output2'); } else { e.preventDefault(); e.stopPropagation(); panel.getTotalResults(); } // }); }); $('#' + panel.divElement.id + '-exportBriefcase').unbind(); $('#' + panel.divElement.id + '-exportBriefcase').click(function(e) { function exportToBriefcase() { var result = []; $.each(panel.allResults, function(i, field) { var loopConcept = {}; loopConcept.conceptId = field.conceptId; loopConcept.defaultTerm = field.defaultTerm; loopConcept.module = field.module; result.push(loopConcept); }); briefcase.addConcepts(result); } if (panel.allResults) { exportToBriefcase(); } else { alertEvent("Exporting concepts, please wait", "info"); panel.getTotalResults(function() { exportToBriefcase(); }); } }); $('#' + panel.divElement.id + '-open-grammar').unbind(); $("#" + panel.divElement.id + "-open-grammar").disableTextSelect(); $("#" + panel.divElement.id + "-open-grammar").click(function(e) { panel.updateGrammarModal(false); }); //-brief-syntax-button $('#home-' + panel.divElement.id + '-full-syntax-button').unbind(); $('#home-' + panel.divElement.id + '-full-syntax-button').disableTextSelect(); $('#home-' + panel.divElement.id + '-full-syntax-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-full-syntax-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-full-syntax-button').click(function(event) { panel.updateGrammarModal(true); }); $('#home-' + panel.divElement.id + '-brief-syntax-button').unbind(); $('#home-' + panel.divElement.id + '-brief-syntax-button').disableTextSelect(); $('#home-' + panel.divElement.id + '-brief-syntax-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-brief-syntax-button').click(function(event) { panel.updateGrammarModal(false); }); $('#' + panel.divElement.id + '-exportBriefcaseClean').unbind(); $('#' + panel.divElement.id + '-exportBriefcaseClean').click(function(e) { function exportToBriefcase() { var result = []; briefcase.emptyBriefcase(); $.each(panel.allResults, function(i, field) { var loopConcept = {}; loopConcept.conceptId = field.conceptId; loopConcept.defaultTerm = field.defaultTerm; loopConcept.module = field.module; result.push(loopConcept); }); briefcase.addConcepts(result); } if (panel.allResults) { exportToBriefcase(); } else { alertEvent("Exporting concepts, please wait", "info"); panel.getTotalResults(function() { exportToBriefcase(); }); } }); $('#' + panel.divElement.id + '-computeButton').unbind(); $('#' + panel.divElement.id + '-computeButton').click(function(e) { var query = $('#' + panel.divElement.id + '-input').val(); var request = { query: JSON.parse(query), pathId: options.path.id }; panel.compute(request); }); $("#" + panel.divElement.id).find("a[data-role='modifier-selector']").unbind(); $("#" + panel.divElement.id).find("a[data-role='modifier-selector']").click(function(e) { $('#' + panel.divElement.id + '-selectedModifier').html($(e.target).html()); }); $('#' + panel.divElement.id + '-selectedConcept').show(); $('#' + panel.divElement.id + '-selectedType').hide(); $('#' + panel.divElement.id + '-selectedTarget').hide(); $('#' + panel.divElement.id + '-searchTerm').hide(); $('#' + panel.divElement.id + '-searchTerm').unbind(); $('#' + panel.divElement.id + '-searchTerm').keyup(function(e) { if (e.keyCode === 13) { $('#' + panel.divElement.id + '-addCriteriaButton').click(); } }); $('#' + panel.divElement.id + '-formdropdown').hide(); $("#" + panel.divElement.id).find("a[data-role='criteria-selector']").unbind(); $("#" + panel.divElement.id).find("a[data-role='criteria-selector']").click(function(e) { $('#' + panel.divElement.id + '-selectedCriteria').html($(e.target).html()); //$(e.target).closest(".dropdown").find("span").first().html($(e.target).html()); var selectedCriteria = $(e.target).html(); if (selectedCriteria == "hasDescription") { $('#' + panel.divElement.id + '-selectedConcept').hide(); $('#' + panel.divElement.id + '-selectedType').hide(); $('#' + panel.divElement.id + '-selectedTarget').hide(); $('#' + panel.divElement.id + '-searchTerm').show(); $('#' + panel.divElement.id + '-formdropdown').hide(); } else if (selectedCriteria == "hasRelationship") { $('#' + panel.divElement.id + '-selectedConcept').hide(); $('#' + panel.divElement.id + '-selectedType').show(); $('#' + panel.divElement.id + '-selectedTarget').show(); $('#' + panel.divElement.id + '-searchTerm').hide(); $('#' + panel.divElement.id + '-formdropdown').show(); } else { $('#' + panel.divElement.id + '-selectedConcept').show(); $('#' + panel.divElement.id + '-selectedType').hide(); $('#' + panel.divElement.id + '-selectedTarget').hide(); $('#' + panel.divElement.id + '-searchTerm').hide(); $('#' + panel.divElement.id + '-formdropdown').hide(); } }); $("#" + panel.divElement.id).find("a[data-role='form-selector']").unbind(); $("#" + panel.divElement.id).find("a[data-role='form-selector']").click(function(e) { $('#' + panel.divElement.id + '-selectedForm').html($(e.target).html()); }); $('#' + panel.divElement.id + '-addCriteriaButton').unbind(); $('#' + panel.divElement.id + '-addCriteriaButton').click(function(e) { var modifier = $('#' + panel.divElement.id + '-selectedModifier').html(); var criteria = $('#' + panel.divElement.id + '-selectedCriteria').html(); var conceptIdDroped = $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId"); if ($('#' + panel.divElement.id + '-listGroup').find('.constraint[data-criteria="' + criteria + '"][data-concept-id="' + conceptIdDroped + '"]').length) { if ($('#' + panel.divElement.id + '-listGroup').find('.constraint[data-criteria="' + criteria + '"][data-concept-id="' + conceptIdDroped + '"]').closest(".query-condition").attr("data-modifier") == modifier) { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Criteria already added..."); } else { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Contradictory criteria..."); } } //if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-criteria="' + criteria + '"][data-modifier="' + modifier + '"][data-concept-id="' + conceptIdDroped + '"]').length){ // $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); // $('#' + panel.divElement.id + '-addmsg').html("Criteria already added..."); //}else if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-criteria="' + criteria + '"][data-concept-id="' + conceptIdDroped + '"]').length){ // $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); // $('#' + panel.divElement.id + '-addmsg').html("Contradictory criteria..."); //} else if (criteria == "hasDescription") { var searchTerm = $('#' + panel.divElement.id + '-searchTerm').val(); if (searchTerm == "") { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Enter a search term..."); } else { $('#' + panel.divElement.id + '-addmsg').html(""); $('#' + panel.divElement.id + '-conceptField').removeClass("has-error"); var context2 = { modifier: modifier, criteria: criteria, searchTerm: searchTerm }; $('#' + panel.divElement.id + '-listGroup').append(JST["views/developmentQueryPlugin/searchCriteria.hbs"](context2)); panel.renumLines(); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); $('#' + panel.divElement.id + '-selectedConcept').val(""); $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedType').val(""); $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedTarget').val(""); $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-searchTerm').val(""); } } else if (criteria == "hasRelationship") { var typeId = $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId"); var typeTerm = $('#' + panel.divElement.id + '-selectedType').val(); var targetId = $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId"); var targetTerm = $('#' + panel.divElement.id + '-selectedTarget').val(); var form = $('#' + panel.divElement.id + '-selectedForm').html(); if ((typeof typeId == "undefined" || typeId == "") && typeTerm == "" && (typeof targetId == "undefined" || targetId == "") && targetTerm == "") { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Drop a concept..."); } else { $('#' + panel.divElement.id + '-addmsg').html(""); $('#' + panel.divElement.id + '-conceptField').removeClass("has-error"); var context2 = { modifier: modifier, criteria: criteria, typeId: typeId, typeTerm: typeTerm, targetId: targetId, targetTerm: targetTerm, form: form }; $('#' + panel.divElement.id + '-listGroup').append(JST["views/developmentQueryPlugin/relsCriteria.hbs"](context2)); panel.renumLines(); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); $('#' + panel.divElement.id + '-selectedConcept').val(""); $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedType').val(""); $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedTarget').val(""); $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-searchTerm').val(""); } } else { var conceptId = $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId"); var term = $('#' + panel.divElement.id + '-selectedConcept').val(); if (typeof conceptId == "undefined" || conceptId == "" || term == "") { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Drop a concept..."); } else { $('#' + panel.divElement.id + '-addmsg').html(""); $('#' + panel.divElement.id + '-conceptField').removeClass("has-error"); var criterias = [{ criteria: criteria, conceptId: conceptId, term: term }]; if ($(divElement).find(".addedCriteria").length) { var typeSelected = $(divElement).find(".addedCriteria").first().attr("data-typeSelected"); $(divElement).find(".addedCriteria").each(function(i) { var addedConceptId = $(this).find(".andCriteriaConcept").first().attr("data-conceptId"); var addedTerm = $(this).find(".andCriteriaConcept").first().val(); var addedCrit = $(this).find(".addSelectCriteria").first().html(); if (addedConceptId && addedTerm) { criterias.forEach(function(criteriaAdded) { if (criteriaAdded.criteria == addedCrit && criteriaAdded.conceptId == addedConceptId) { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Criteria already added..."); return false; } }); var crit = { criteria: addedCrit, conceptId: addedConceptId, term: addedTerm }; if (typeSelected == "Refinement") { if ($(this).find(".typeCritCombo").first().attr("data-type-concept-id") == "false") { $('#' + panel.divElement.id + '-addmsg').html("Select a type..."); return false; } else { crit.type = { conceptId: $(this).find(".typeCritCombo").first().attr("data-type-concept-id"), term: $(this).find(".typeCritCombo").first().attr("data-type-term") }; } } criterias.push(crit); } else { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Drop a concept..."); return false; } }); } if ($('#' + panel.divElement.id + '-addmsg').html() == "") { $(divElement).find(".addedCriteria").remove(); $("#" + panel.divElement.id + "-addCriteriaAnd").show(); var context2 = { modifier: modifier, criterias: criterias }; // Add Excludes always at the end, and includes before exclude var foundExclude = false; $('#' + panel.divElement.id + '-listGroup').find(".query-condition").each(function(index) { var modifier = $(this).data('modifier'); if (modifier == "Exclude") { $(this).before(JST["views/developmentQueryPlugin/criteria.hbs"](context2)); var critAdded = $('#' + panel.divElement.id + '-listGroup').find(".query-condition")[index]; $(critAdded).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critAdded), true, function(resultCount) { $(critAdded).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critAdded).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); foundExclude = true; return false; } }); if (!foundExclude) { $('#' + panel.divElement.id + '-listGroup').append(JST["views/developmentQueryPlugin/criteria.hbs"](context2)); var critAdded = $('#' + panel.divElement.id + '-listGroup').find(".query-condition")[$('#' + panel.divElement.id + '-listGroup').find(".query-condition").length - 1]; $(critAdded).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critAdded), true, function(resultCount) { $(critAdded).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critAdded).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); } $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").unbind(); $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").click(function(e) { var prevValue = $(e.target).closest(".constraint").attr('data-criteria'); var newValue = $(e.target).html(); if (prevValue != newValue) { $(e.target).closest(".constraint").attr('data-criteria', newValue); $(e.target).closest("div").find("button").first().html(newValue + "&nbsp;"); var critToUpdate = $(e.target).closest(".query-condition"); $(critToUpdate).find("small").remove(); $(critToUpdate).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critToUpdate), true, function(resultCount) { $(critToUpdate).find("small").remove(); $(critToUpdate).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critToUpdate).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); } }); panel.renumLines(); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); $('#' + panel.divElement.id + '-selectedConcept').val(""); $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedType').val(""); $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedTarget').val(""); $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-searchTerm').val(""); } } } }); $('#' + panel.divElement.id + '-computeInferredButton2').unbind(); $('#' + panel.divElement.id + '-computeInferredButton2').disableTextSelect(); $('#' + panel.divElement.id + '-computeInferredButton2').click(function(e) { var expression = $.trim($("#" + panel.divElement.id + "-ExpText").val()); $('#' + panel.divElement.id + '-computeInferredButton2').addClass("disabled"); /* $.post(options.serverUrl.replace("snomed", "expressions/") + "parse/brief", { expression: expression }).done(function(res) { //console.log(res); if (res.validation) { */ panel.execute("inferred", expression, true); /* } else { alertEvent("Invalid Expression", "error") } }).fail(function(err) { //console.log(err); }).always(function() { */ $('#' + panel.divElement.id + '-computeInferredButton2').removeClass("disabled"); // }); }); $('#' + panel.divElement.id + '-computeInferredButton').unbind(); $('#' + panel.divElement.id + '-computeInferredButton').disableTextSelect(); $('#' + panel.divElement.id + '-computeInferredButton').click(function(e) { var grammar = panel.exportToConstraintGrammar(false, false); if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-modifier="Include"]').length) { panel.execute("inferred", grammar, true); } else { //console.log("add at least one include"); //alertEvent("Add at least one include", "error"); $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-danger'>Add at least one include</span>"); $("#" + panel.divElement.id + "-footer").html(""); //$('#' + panel.divElement.id + '-resultInfo').html('ERROR'); } }); $('#' + panel.divElement.id + '-computeOntoserver').unbind(); $('#' + panel.divElement.id + '-computeOntoserver').click(function(e) { var grammar = panel.exportToConstraintGrammar(false, false); if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-modifier="Include"]').length) { var ontoserverUrl = "http://52.21.192.244:8080/ontoserver/resources/ontology/findConceptsByQuery?versionedId=http%3A%2F%2Fsnomed.info%2Fsct%2F32506021000036107%2Fversion%2F20151130&field=shortId&field=label&field=primitive&field=inferredAxioms&format=json&start=0&rows=100"; var ontoserverConstraintParam = "&query=Constraint("; var sampleEncodedConstraint = "%3C%2019829001%20%7Cdisorder%20of%20lung%7C%3A%20%0A116676008%20%7Cassociated%20morphology%7C%20%3D%20*"; var encodedGrammar = encodeURIComponent(grammar); var executeUrl = ontoserverUrl + ontoserverConstraintParam + encodedGrammar + ")"; panel.currentEx++; $('#' + panel.divElement.id + '-resultInfo').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $('#' + panel.divElement.id + '-footer').html('<div class="progress progress-striped active"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"><span>Searching</span></div></div><p id="' + panel.divElement.id + '-waitingSearch-text" class="lead animated"></p>'); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("OntoServer is processing your instructions..."); $.getJSON(executeUrl, function(result) { //$.getJSON(panel.url + "rest/browser/concepts/" + panel.conceptId + "/children", function(result) { }).done(function(result) { //console.log(result); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + result.totalResults + " concepts</span>"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); //TODO: implement pagination with Ontoserver if (result.totalResults > 100) { $('#' + panel.divElement.id + '-footer').html("Showing first 100 matches"); } else { $('#' + panel.divElement.id + '-footer').html("Showing all matches"); } $.each(result.data, function(i, row) { $('#' + panel.divElement.id + '-outputBody').append("<tr style='cursor: pointer;' class='conceptResult' data-module='' data-concept-id='" + row.shortId + "' data-term='" + row.label + "'><td>" + row.label + "</td><td>" + row.shortId + "</td></tr>"); $('#' + panel.divElement.id + '-outputBody2').append("<tr><td>" + row.label + "</td><td>" + row.shortId + "</td></tr>"); }); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").unbind(); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").click(function(event) { //console.log("clicked",$(event.target).closest("tr").attr('data-term')); channel.publish(panel.divElement.id, { term: $(event.target).closest("tr").attr('data-term'), module: $(event.target).closest("tr").attr("data-module"), conceptId: $(event.target).closest("tr").attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function(err) { //console.log("Error",err); }); } else { $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-danger'>Add at least one include</span>"); $("#" + panel.divElement.id + "-footer").html(""); } }); }; panel.updateGrammarModal = function(fullSyntax) { if (fullSyntax) { $('#home-' + panel.divElement.id + '-full-syntax-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-full-syntax-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').removeClass("btn-primary"); } else { $('#home-' + panel.divElement.id + '-full-syntax-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-full-syntax-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').addClass("btn-primary"); } panel.grammarToCopy = panel.exportToConstraintGrammar(false, fullSyntax); $("#" + panel.divElement.id + "-constraintGrammar").html(panel.exportToConstraintGrammar(true, fullSyntax)); }; panel.setUpPanel(); this.renumLines = function() { $('#' + panel.divElement.id + '-listGroup').find(".query-condition").each(function(index) { $(this).find(".line-number").html(index + 1); }); }; this.getTotalResults = function(callback) { if (xhrTotal != null) { xhrTotal.abort(); } panel.lastRequest.skip = 0; panel.lastRequest.limit = panel.lastTotalValues + 1; $('#' + panel.divElement.id + '-exportXls').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); xhrTotal = $.ajax({ type: "POST", url: options.serverUrl.replace("snomed", "expressions/") + "/" + options.edition + "/" + options.release + "/execute/brief", data: panel.lastRequest, dataType: "json", success: function(result) { xhrTotal = null; panel.allResults = result.computeResponse.matches; var rowsHtml = ""; if (panel.allResults && panel.allResults.length) { $.each(panel.allResults, function(i, field) { rowsHtml += "<tr><td>" + field.defaultTerm + "</td><td>" + field.conceptId + "</td></tr>"; }); } $("#" + panel.divElement.id + "-outputBody2").html(rowsHtml); $('#' + panel.divElement.id + '-exportXls').html('Download XLS <img style="height: 23px;" src="img/excel.png">'); if (callback) callback(); } }).always(function(result) { xhrTotal = null; }).fail(function() { alertEvent("Failed!", "error"); }); //xhrTotal = $.post(panel.lastUrl, panel.lastRequest).done(function(data){ // xhrTotal = null; // panel.allResults = data.matches; // var rowsHtml = ""; // if (panel.allResults && panel.allResults.length){ // $.each(panel.allResults, function(i, field){ // rowsHtml+= "<tr><td>" + field.defaultTerm + "</td><td>" + field.conceptId + "</td></tr>"; // }); // } // $("#" + panel.divElement.id + "-outputBody2").html(rowsHtml); // $('#' + panel.divElement.id + '-exportXls').html('Download XLS <img style="height: 23px;" src="img/excel.png">'); // if (callback) // callback(); //}).fail(function(){ // alertEvent("Failed!", "error"); //}); }; this.getExpressionForCondition = function(condition, htmlFormat, fullSyntax) { var grammar = ""; var operator = ""; if (condition.criteria == "self") { if (fullSyntax) { operator = "self "; } else { operator = ""; } } else if (condition.criteria == "descendantOf") { if (fullSyntax) { operator = "descendantOf "; } else { operator = "< "; } } else if (condition.criteria == "descendantOrSelfOf") { if (fullSyntax) { operator = "descendantOrSelfOf "; } else { operator = "<< "; } } else if (condition.criteria == "childrenOf") { if (fullSyntax) { operator = "childrenOf "; } else { operator = "<1 "; } } else if (condition.criteria == "ancestorOf") { if (fullSyntax) { operator = "ancestorOf "; } else { operator = "> "; } } else if (condition.criteria == "ancestorOrSelfOf") { if (fullSyntax) { operator = "ancestorOrSelfOf "; } else { operator = ">> "; } } else if (condition.criteria == "parentsOf") { if (fullSyntax) { operator = "parentsOf "; } else { operator = ">1 "; } } else if (condition.criteria == "hasDescription") { if (fullSyntax) { operator = "hasDescription "; } else { operator = "desc "; } } else if (condition.criteria == "hasRelationship") { if (fullSyntax) { operator = "hasRelationship "; } else { operator = "rel "; } } else if (condition.criteria == "isMemberOf") { if (fullSyntax) { operator = "isMemberOf "; } else { operator = "^ "; } }; var term = "|" + condition.term + "|"; if (htmlFormat) { operator = "<span class='exp-operators'>" + operator + "</span>"; term = "<span class='exp-term'>" + term + "</span>"; } if (condition.typeId) { if (condition.typeId == "*") { grammar = " * = " + operator + condition.conceptId + term; } else { var typeTerm = "|" + condition.typeTerm + "|"; if (htmlFormat) { term = "<span class='exp-term'>" + typeTerm + "</span>"; } grammar = condition.typeId + typeTerm + " = " + operator + condition.conceptId + term; } } else { grammar = operator + condition.conceptId + term; } return grammar; }; this.exportToConstraintGrammar = function(htmlFormat, fullSyntax, htmlObj, fullObjHtml) { var breakLine = " "; if (htmlFormat) { breakLine = "<br>"; } var grammar = ""; if ($('#' + panel.divElement.id + '-listGroup').find(".query-condition").length == 0 && !htmlObj && !fullObjHtml) { //console.log("Add at least one instruction..."); } else { var includes = []; var excludes = []; if (htmlObj) { var conditions = []; $(htmlObj).find(".constraint").each(function(index2) { var condition = { "criteria": $(this).attr('data-criteria'), "typeId": $(this).attr('data-type-concept-id'), "typeTerm": $(this).attr('data-type-term'), "conceptId": $(this).attr('data-concept-id'), "term": $(this).attr('data-term') }; conditions.push(condition); }); includes.push(conditions); } else { var objTouse = '#' + panel.divElement.id + '-listGroup'; if (fullObjHtml) objTouse = fullObjHtml $(objTouse).find(".query-condition").each(function(index) { var conditions = []; $(this).find(".constraint").each(function(index2) { var condition = { "criteria": $(this).attr('data-criteria'), "typeId": $(this).attr('data-type-concept-id'), "typeTerm": $(this).attr('data-type-term'), "conceptId": $(this).attr('data-concept-id'), "term": $(this).attr('data-term') }; conditions.push(condition); }); if ($(this).data('modifier') == "Exclude") { excludes.push(conditions); } else { includes.push(conditions); } }); } var isRefined = function(conditions) { var refined = false; if (conditions.length > 1) { if (conditions[1].typeId) { refined = true; } } return refined; }; //if (includes.length > 1) grammar += "("; $.each(includes, function(index, conditions) { if (index > 0) grammar += " OR "; if (conditions.length > 1 || isRefined(conditions)) grammar += " ("; if (isRefined(conditions)) { $.each(conditions, function(index2, condition) { grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (index2 == 0) { grammar += " : "; } else if (index2 < conditions.length - 1) { grammar += " , "; } if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } else { $.each(conditions, function(index2, condition) { if (index2 > 0) grammar += " AND "; grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } if (conditions.length > 1 || isRefined(conditions)) grammar += ") "; if (htmlFormat && index < includes.length - 1) { grammar += "<br>"; } }); //if (includes.length > 1) grammar += ")"; if (excludes.length > 0 && includes.length > 1) { grammar = "(" + grammar; grammar += ") MINUS "; if (htmlFormat) { grammar += "<br>"; } } else if (excludes.length > 0) { grammar += " MINUS "; if (htmlFormat) { grammar += "<br>"; } } if (excludes.length > 1) grammar += "("; $.each(excludes, function(index, conditions) { if (index > 0) grammar += " OR "; if (conditions.length > 1 || isRefined(conditions)) grammar += " ("; if (isRefined(conditions)) { $.each(conditions, function(index2, condition) { grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (index2 == 0) { grammar += " : "; } else if (index2 < conditions.length - 1) { grammar += " , "; } if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } else { $.each(conditions, function(index2, condition) { if (index2 > 0) grammar += " AND "; grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } if (conditions.length > 1 || isRefined(conditions)) grammar += ") "; if (htmlFormat && index < excludes.length - 1) { grammar += "<br>"; } }); if (excludes.length > 1) grammar += ")"; } grammar = grammar.trim(); //console.log(grammar.charAt(0)); //console.log(grammar.charAt(grammar.length-1)); //if (grammar.charAt(0) == "(" && grammar.charAt(grammar.length-1) == ")") { // grammar = grammar.substr(1,grammar.length-2); //} return grammar; }; this.execute = function(form, expression, clean, onlyTotal) { panel.currentEx++; var currentEx = panel.currentEx; //$('#' + panel.divElement.id + '-footer').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); if (onlyTotal) { limit = 1; skip = 0; } else { $('#' + panel.divElement.id + '-footer').html('<div class="progress progress-striped active"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"><span>Searching</span></div></div><p id="' + panel.divElement.id + '-waitingSearch-text" class="lead animated"></p>'); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("The server is processing your instructions..."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); setTimeout(function() { //console.log(currentEx, panel.currentEx); if (xhrExecute != null && currentEx == panel.currentEx) { $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("The server is still processing your instructions..."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); }, 600); } }, 15000); setTimeout(function() { if (xhrExecute != null && currentEx == panel.currentEx) { $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("This seems to be a complex set of instructions, still processing..."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); }, 600); } }, 30000); setTimeout(function() { if (xhrExecute != null && currentEx == panel.currentEx) { $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("The server is processing a complex set of instructions. This action might not be supported in a public server. Some times instructions can be simplified by specifying conditions using concepts closer in the hierarchy to the intended results, avoiding unnecessary selections of large portions of the terminology."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); }, 600); } }, 45000); //setTimeout(function(){ // $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); // setTimeout(function(){ // $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); // if (xhrExecute != null && currentEx == panel.currentEx){ // $("#" + panel.divElement.id + "-waitingSearch-text").html(""); // $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); // $("#" + panel.divElement.id + "-waitingSearch-text").html("Instruction set exceeds maximum allowed time for computation. Some times instructions can be simplified by specifying conditions using concepts closer in the hierarchy to the intended results, avoiding unnecessary selections of large portions of the terminology."); // setTimeout(function(){ // $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); // }, 600); // } // }, 600); //}, 61000); $('#' + panel.divElement.id + '-resultInfo').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); if (clean) { $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); limit = 100; skip = 0; } } var data = { expression: expression, limit: limit, skip: skip, form: form }; console.log("normal " + expression); var strippedExpression1 = expression.replace(/\|.*?\|/guim, ''); var strippedExpression = strippedExpression1.replace(/\n/guim, ''); console.log("stripped " + strippedExpression); panel.lastRequest = data; page = skip / limit; var expressionURL; if (options.queryBranch == 'MAIN') { expressionURL = options.queryServerUrl + "/" + options.queryBranch + "/concepts?module=900000000000207008&ecl=" + strippedExpression + "&offset=" + skip + "&limit=" + limit + "&expand=fsn()"; } else if (options.queryBranch.includes('SNOMEDCT-US')) { expressionURL = options.queryServerUrl + "/" + options.queryBranch + "/concepts?&ecl=" + strippedExpression + "&offset=" + skip + "&limit=" + limit + "&expand=fsn()"; } else { expressionURL = options.queryServerUrl + "/" + options.queryBranch + "/concepts?ecl=" + strippedExpression + "&page=" + page + "&size=" + limit; } console.log("queryURL " + expressionURL); if (xhrExecute != null && !onlyTotal) xhrExecute.abort(); var xhrExecute2 = $.ajax({ type: "GET", url: expressionURL, //timeout: 300000,lasturl success: function(result) { //if (result.paserResponse.validation) { data = result; //result.computeResponse.matches if (!onlyTotal) { $("#" + panel.divElement.id + "-exportResults").removeClass("disabled"); if (data.performanceCutOff) { if (!data.totalElements) { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.total + " concepts. <span class='text-danger'>This query cannot be completed in real-time, please schedule a Cloud executions. Results below are incomplete and some conditions were not tested. </span></span>"); } else { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.totalElements + " concepts. <span class='text-danger'>This query cannot be completed in real-time, please schedule a Cloud executions. Results below are incomplete and some conditions were not tested. </span></span>"); } } else { if (!data.totalElements) { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.total + " concepts</span>"); } else { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.totalElements + " concepts</span>"); } } $.each(data.items, function(i, row) { $('#' + panel.divElement.id + '-outputBody').append("<tr style='cursor: pointer;' class='conceptResult' data-module='" + row.moduleId + "' data-concept-id='" + row.id + "' data-term='" + row.fsn.term + "'><td>" + row.fsn.term + "</td><td>" + row.id + "</td></tr>"); $('#' + panel.divElement.id + '-outputBody2').append("<tr><td>" + row.fsn.term + "</td><td>" + row.id + "</td></tr>"); }); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").unbind(); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").click(function(event) { //console.log("clicked",$(event.target).closest("tr").attr('data-term')); channel.publish(panel.divElement.id, { term: $(event.target).closest("tr").attr('data-term'), module: $(event.target).closest("tr").attr("data-module"), conceptId: $(event.target).closest("tr").attr('data-concept-id'), source: panel.divElement.id, showConcept: true }); }); if (!data.totalElements) { panel.lastTotalValues = data.total; if (limit + skip < data.total) { $('#' + panel.divElement.id + '-footer').html("<span id='" + panel.divElement.id + "-more'>Show more (viewing " + (limit + skip) + " of " + data.total + " total)</span>"); } else { $('#' + panel.divElement.id + '-footer').html("Showing all " + data.total + " matches"); } } else { panel.lastTotalValues = data.totalElements; if (limit + skip < data.totalElements) { $('#' + panel.divElement.id + '-footer').html("<span id='" + panel.divElement.id + "-more'>Show more (viewing " + (limit + (page * limit)) + " of " + data.totalElements + " total)</span>"); } else { $('#' + panel.divElement.id + '-footer').html("Showing all " + data.totalElements + " matches"); } } $('#' + panel.divElement.id + '-more').unbind(); $('#' + panel.divElement.id + '-more').click(function(e) { skip = (page * limit) + 100; panel.execute(form, expression, false); }); } else { onlyTotal(data.total); } } }).done(function(result) { // done xhrExecute2 = null; }).fail(function(jqXHR) { //console.log(xhrExecute2); if (jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.computeResponse && jqXHR.responseJSON.computeResponse.message) { $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $("#" + panel.divElement.id + "-footer").html(""); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-danger'>" + jqXHR.responseJSON.computeResponse.message + "</span>"); } else { var textStatus = xhrExecute2.statusText; if (textStatus != "abort") { if (xhrExecute2.status == 0) textStatus = "timeout"; xhrExecute2 = null; if (textStatus === 'timeout') { // $("#" + panel.divElement.id + "-syntax-result").html('<span class="label label-danger">ERROR</span>'); // $("#" + panel.divElement.id + "-results").html("Timeout..."); if (!onlyTotal) { $('#' + panel.divElement.id + '-footer').html("<p class='lead'>Instruction set exceeds maximum allowed time for computation. Some times instructions can be simplified by specifying conditions using concepts closer in the hierarchy to the intended results, avoiding unnecessary selections of large portions of the terminology.</p>"); $('#' + panel.divElement.id + '-resultInfo').html("This query cannot be completed in real-time."); //$('#' + panel.divElement.id + '-footer').html("Timeout Error"); } else { onlyTotal("Error"); } } else { if (!onlyTotal) { $("#" + panel.divElement.id + "-syntax-result").html('<span class="label label-danger">ERROR</span>'); $("#" + panel.divElement.id + "-results").html("Error..."); } else { onlyTotal("Error"); } } } } }); if (!onlyTotal) xhrExecute = xhrExecute2; } } /** * Created by alo on 7/18/14. */ icon = document.createElement("img"); channel = postal.channel("Selections"); Handlebars.registerHelper('i18n', function (i18n, defaultV){ if (typeof window[i18n] == "undefined"){ //console.log(i18n, "=", defaultV); return defaultV; }else{ return window[i18n]; } }); Handlebars.registerHelper('if_undefined', function (a, opts) { if (opts != "undefined") { if (typeof a == "undefined") return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper("if_eqInd", function(a, b, opts){ if ((parseInt(a) + 1) == parseInt(b)) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper("console", function(a){ console.log(a); }); $(document).on('dragend', function(){ removeHighlight(); }); function setDefaultTerm(concept) { if (concept) { if (concept.fsn) { if (typeof concept.fsn == "object") { concept.defaultTerm = concept.fsn.term; } else { concept.defaultTerm = concept.fsn; } } if (concept.relationships) { concept.statedRelationships = []; concept.relationships.forEach(function(r) { r.type.defaultTerm = r.type.fsn.term; r.target.defaultTerm = r.target.fsn.term; if (r.characteristicType == "STATED_RELATIONSHIP") { concept.statedRelationships.push(r); } }) // Remove statedRelationships from relationships array concept.statedRelationships.forEach(function(r) { concept.relationships.splice(concept.relationships.indexOf(r), 1); }) } if (concept.definitionStatus == "PRIMITIVE") { concept.definitionStatus = "PRIMITIVE"; } } } function removeHighlight(){ $(document).find('.drop-highlighted').removeClass('drop-highlighted'); } function allowDrop(ev) { ev.preventDefault(); var aux; if ($(ev.target).attr("data-droppable") == "true"){ aux = $(ev.target); }else{ aux = $(ev.target).closest("div"); } // while (typeof $(aux).closest('div').attr('ondrop') != "undefined"){ // aux = $(aux).closest('div'); // } $(aux).addClass("drop-highlighted"); } function dropField(ev){ var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } $(ev.target).val(term); $(ev.target).attr("data-conceptId", conceptId); } } function iconToDrag(text){ var CVS = document.createElement('canvas'), ctx = CVS.getContext('2d'); CVS.width = 300; CVS.height = 300; ctx.font = "15px sans-serif"; ctx.strokeText(text, 10, 20); var icon = document.createElement("img"); icon.src = CVS.toDataURL(); return icon; } function drag(ev, id) { var dataText = ""; var term = "", conceptId = ""; $.each(ev.target.attributes, function (){ if (this.name.substr(0, 4) == "data"){ ev.dataTransfer.setData(this.name.substr(5), this.value); if (this.name.substr(5) == "concept-id"){ conceptId = this.value; } if (this.name.substr(5) == "term"){ term = this.value; } } }); icon = iconToDrag(term); if (navigator.userAgent.indexOf("Chrome") > -1){ icon = iconToDrag(term); ev.dataTransfer.setDragImage(icon, 0, 0); }else{ // icon = iconToDrag(term); } ev.dataTransfer.setDragImage(icon, 0, 0); dataText = conceptId + "|" + term; ev.dataTransfer.setData("Text", dataText); ev.dataTransfer.setData("divElementId", id); } function dropS(ev){ $(document).find('.drop-highlighted').removeClass('drop-highlighted'); ev.preventDefault(); var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } $(ev.target).val(term); var id = $(ev.target).attr("id").replace("-searchBox", ""); $.each(componentsRegistry, function(i, field) { if (field.divElement.id == id) { field.search(term, 0, 100, false); } }); } } function dropC(ev, id) { $(document).find('.drop-highlighted').removeClass('drop-highlighted'); ev.preventDefault(); var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } var divElementID = id; var panelAct; $.each(componentsRegistry, function (i, field){ if (field.divElement.id == divElementID){ panelAct = field; } }); if (conceptId && panelAct.conceptId != conceptId) { panelAct.conceptId = conceptId; panelAct.updateCanvas(); channel.publish(panelAct.divElement.id, { term: term, conceptId: panelAct.conceptId, source: panelAct.divElement.id }); } } } function dropF(ev, id) { var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); var module = ev.dataTransfer.getData("module"); if (typeof term == "undefined"){ term = text.substr(i); } var favs = stringToArray(localStorage.getItem("favs")), found = false; $.each(favs, function(i,field){ if (field == conceptId){ found = true; } }); var concept = { defaultTerm: term, conceptId: conceptId, module: module }; if (!found){ // console.log(concept); favs.push(conceptId); localStorage.setItem("favs", favs); localStorage.setItem("conceptId:" + conceptId, JSON.stringify(concept)); } channel.publish("favsAction"); } } function dropT(ev, id) { $(document).find('.drop-highlighted').removeClass('drop-highlighted'); ev.preventDefault(); var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);") { var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var divElementId = id; var panel; var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } var definitionStatus = ev.dataTransfer.getData("def-status"); var module = ev.dataTransfer.getData("module"); $.each(componentsRegistry, function (i, field){ if (field.divElement.id == divElementId){ panel = field; } }); if (conceptId) { if (panel.options.selectedView == "undefined") { panel.options.selectedView = "inferred"; } if (typeof conceptId != "undefined") { var d = new Date(); var time = d.getTime(); panel.history.push({term: term, conceptId: conceptId, time: time}); panel.setToConcept(conceptId, term, definitionStatus, module); channel.publish(panel.divElement.id, { term: term, conceptId: conceptId, source: panel.divElement.id }); } } } } function stringToArray (string){ if (typeof string == "string"){ var ind = 0, auxString, array = []; while (ind < string.length){ auxString = ""; while (string.substr(ind, 1) != "," && ind < string.length){ auxString = auxString + string.substr(ind,1); ind++; } array.push(auxString); ind++; } return(array); }else{ return false; } } var lastEventTime = (new Date()).getTime(); function alertEvent(message, type) { var t = (new Date()).getTime(); if (t-lastEventTime < 10 && message.toLowerCase().includes("copied")) { // Ignore notification } else { $.notify(message,type); } lastEventTime = t; } if (!String.prototype.endsWith) { String.prototype.endsWith = function(searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; }
snomed-interaction-components/js/snomed-interaction-components-2.1.js
this["JST"] = this["JST"] || {}; this["JST"]["views/conceptDetailsPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='margin: 5px; height:98%; overflow:auto;' class='panel panel-default'>\n <div class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading' ondrop=\"dropC(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\">\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding:2px;position: absolute;top: 1px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-8' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_concept_details'>Concept Details</span></strong></div>\n <div class='col-md-4 text-right'>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div class='panel-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <!-- Nav tabs -->\n <ul class=\"nav nav-tabs\" id=\"details-tabs-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <li class=\"active\"><a href=\"#home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_summary\">Summary</span></a></li>\n <li><a href=\"#details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_details\">Details</span></a></li>\n <li id=\"diagram-tab\"><a href=\"#diagram-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\" id=\"diagram-tab-link-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"><span class=\"i18n\" data-i18n-id=\"i18n_diagram\">Diagram</span></a></li>\n <li id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-members-tab\"><a href=\"#members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_members\">Members</span></a></li>\n <li id=\"product-details-tab\" style=\"display: none;\"><a id=\"product-details-tab-link-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" href=\"#product-details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-toggle=\"tab\" style=\"padding-top: 3px; padding-bottom:3px;\"><span class=\"i18n\" data-i18n-id=\"i18n_vcd\">CD</span></a></li>\n </ul>\n <!-- Tab panes -->\n <div class=\"tab-content\" id=\"details-tab-content-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"tab-pane fade in active\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" style=\"padding: 5px;\">\n <div class=\"pull-right\">\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-stated-button\">Stated</button>\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferred-button\">Inferred</button>\n </div>\n <div><span class=\"text-muted text-center\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-wf-status-label\"></span></div>\n </div>\n <div style=\"max-height: 300px; overflow: auto; margin-left: 0%; margin-bottom: 10px; margin-top: 10px; width: 80%;border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\">\n <div class=\"panel-heading\">\n <h4><span data-i18n-id=\"i18n_parents\" class=\"i18n\">Parents</span></h4>\n </div>\n <div class=\"panel-body\" id=\"home-parents-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <span data-i18n-id=\"i18n_no_parents\" class=\"i18n\">No parents</span>\n </div>\n </div>\n <div class=\"row\" style=\"overflow: auto; max-height: 30%;\">\n <div class=\"col-md-offset-1 col-md-4\" style=\"color: #ffffff;background-color: #1e90ff;display: inline-block; border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\" id=\"home-attributes-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Attributes</div>\n <div class=\"col-md-4\" style=\"background-color: rgba(30, 144, 255, 0.17); display: inline-block; min-height: 100%; margin-left: 10px; border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\" id=\"home-roles-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Relationships</div>\n </div>\n <div style=\"max-height: 300px; overflow: auto; margin-left: 0%; margin-bottom: 10px; margin-top: 10px; width: 80%;border: 2px solid #357ebd; border-radius: 4px; padding: 5px;\" id=\"home-children-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"panel-heading\">\n <h4><span data-i18n-id=\"i18n_children\" class=\"i18n\">Children</span>&nbsp;<span id=\"home-children-cant-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></span></h4>\n </div>\n <div class=\"panel-body\" id=\"home-children-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-body\"></div>\n </div>\n <div><span class=\"text-muted pull-right\" id=\"footer-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></span></div>\n </div>\n <div class=\"tab-pane fade\" id=\"details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"pull-right\">\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" class=\"btn btn-default\" id=\"details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-stated-button\">Stated</button>\n <button type=\"button\" class=\"btn btn-default\" id=\"details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferred-button\">Inferred</button>\n </div>\n <div><span class=\"text-muted text-center\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-wf-status-label\"></span></div>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-attributes-panel' class='panel panel-default'>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descriptions-panel' class='panel panel-default'>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-rels-panel' class='panel panel-default'>\n </div>\n <!--<div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-children-panel' class='panel panel-default' style='height:100px;overflow:auto;margin-bottom: 15px;'>-->\n <!--</div>-->\n </div>\n <div class=\"tab-pane fade\" id=\"diagram-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"row\" style=\"margin-right: 20px\"><span class=\"pull-right text-muted\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagram-viewLabel\"></span></div>\n <div id=\"diagram-canvas-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></div>\n </div>\n <div class=\"tab-pane fade\" id=\"expression-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"row\" style=\"margin-right: 20px\"><span class=\"pull-right text-muted\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expression-viewLabel\"></span></div>\n <div id=\"expression-canvas-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></div>\n </div>\n <div class=\"tab-pane fade\" id=\"refsets-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n </div>\n <div class=\"tab-pane fade\" id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <!--<div class=\"pull-right\" style=\"padding: 5px\">-->\n <!--<button id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-sort\" class=\"btn btn-default\">Sort results</button>-->\n <!--<span class=\"text-muted\">This operation may time-out for large refsets</span>-->\n <!--</div>-->\n <!--<br>-->\n <table id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable\" class=\"table table-hover table-bordered\">\n </table>\n <!--<button id=\"members-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-normal\" class=\"btn btn-default\">100 first members</button>-->\n </div>\n <div class=\"tab-pane fade\" id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n <div class=\"panel-group\" id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-accordion\">\n\n </div>\n <!--<br>-->\n <!--<span class=\"text-muted\" style=\"padding: 5px;\" id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-total\"></span>-->\n <!--<table id=\"references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable\" class=\"table table-hover table-bordered\">-->\n <!--</table>-->\n </div>\n <div class=\"tab-pane fade\" id=\"product-details-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">\n </div>\n </div>\n </div>\n</div>\n<div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n</div>\n "; return buffer; }); this["JST"]["views/conceptDetailsPlugin/options.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displaySynonymsOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_display_synonyms2\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options) : helperMissing.call(depth0, "i18n", "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options))) + "</span>\n "; return buffer; } function program3(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displaySynonymsOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_display_synonyms2\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options) : helperMissing.call(depth0, "i18n", "i18n_display_synonyms2", "Display Synonyms along with FSN and preferred terms", options))) + "</span>\n "; return buffer; } function program5(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayIdsOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_display_ids\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_ids", "Display Description Ids", options) : helperMissing.call(depth0, "i18n", "i18n_display_ids", "Display Description Ids", options))) + "</span>\n "; return buffer; } function program7(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayIdsOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_display_ids\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_ids", "Display Description Ids", options) : helperMissing.call(depth0, "i18n", "i18n_display_ids", "Display Description Ids", options))) + "</span>\n "; return buffer; } function program9(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayInactiveDescriptionsOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_display_inactive_descriptions\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_inactive_descriptions", "Display inactive descriptions", options) : helperMissing.call(depth0, "i18n", "i18n_display_inactive_descriptions", "Display inactive descriptions", options))) + "</span>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayInactiveDescriptionsOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_display_inactive_descriptions\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_inactive_descriptions", "Display inactive descriptions", options) : helperMissing.call(depth0, "i18n", "i18n_display_inactive_descriptions", "Display inactive descriptions", options))) + "</span>\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-hideNotAcceptableOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_hide_not_acceptable\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options) : helperMissing.call(depth0, "i18n", "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options))) + "</span>\n "; return buffer; } function program15(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-hideNotAcceptableOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_hide_not_acceptable\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options) : helperMissing.call(depth0, "i18n", "i18n_hide_not_acceptable", "Hide descriptions with no acceptability", options))) + "</span>\n "; return buffer; } function program17(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagrammingMarkupEnabledOption\" checked> <span class=\"i18n\" data-i18n-id=\"i18n_diagramming_markup_enabled\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options) : helperMissing.call(depth0, "i18n", "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options))) + "</span>\n "; return buffer; } function program19(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagrammingMarkupEnabledOption\"> <span class=\"i18n\" data-i18n-id=\"i18n_diagramming_markup_enabled\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options) : helperMissing.call(depth0, "i18n", "i18n_diagramming_markup_enabled", "Diagramming Guideline colors enabled", options))) + "</span>\n "; return buffer; } function program21(depth0,data) { return "checked"; } function program23(depth0,data) { return "\n <option value=\"stated\" selected>Stated</option>\n "; } function program25(depth0,data) { return "\n <option value=\"stated\">Stated</option>\n "; } function program27(depth0,data) { return "\n <option value=\"inferred\" selected>Inferred</option>\n "; } function program29(depth0,data) { return "\n <option value=\"inferred\">Inferred</option>\n "; } function program31(depth0,data) { return "\n <option value=\"all\" selected>All</option>\n "; } function program33(depth0,data) { return "\n <option value=\"all\">All</option>\n "; } function program35(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.manifest)),stack1 == null || stack1 === false ? stack1 : stack1.languageRefsets), {hash:{},inverse:self.noop,fn:self.programWithDepth(36, program36, data, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program36(depth0,data,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <div class=\"checkbox\">\n <label>\n <input class=\"langOption\" type=\"checkbox\" value=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = (helper = helpers.ifIn || (depth0 && depth0.ifIn),options={hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptId), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.langRefset), options) : helperMissing.call(depth0, "ifIn", (depth0 && depth0.conceptId), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.langRefset), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </label>\n </div>\n "; return buffer; } function program38(depth0,data,depth1) { var buffer = "", stack1, helper; buffer += "-->\n <!--<tr>-->\n <!--<td>"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>-->\n <!--<td>-->\n <!--<div class=\"checkbox\">-->\n <!--<label>-->\n <!--<input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscribeTo-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscribed), {hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">-->\n <!--</label>-->\n <!--</div>-->\n <!--</td>-->\n <!--<td>-->\n <!--<div class=\"checkbox\">-->\n <!--<label>-->\n <!--<input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscriptor-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscriptor), {hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">-->\n <!--</label>-->\n <!--</div>-->\n <!--</td>-->\n <!--</tr>-->\n <!--"; return buffer; } buffer += "<form role=\"form\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-options-form\">\n <div class=\"form-group\">\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.displaySynonyms), {hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.showIds), {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.displayInactiveDescriptions), {hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.hideNotAcceptable), {hash:{},inverse:self.program(15, program15, data),fn:self.program(13, program13, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.diagrammingMarkupEnabled), {hash:{},inverse:self.program(19, program19, data),fn:self.program(17, program17, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </label>\n </div>\n <div class=\"checkbox\">\n <label>\n <input type=\"checkbox\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-displayChildren\" "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.displayChildren), {hash:{},inverse:self.noop,fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> <span class=\"i18n\" data-i18n-id=\"i18n_display_children\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_display_children", "Display All Children", options) : helperMissing.call(depth0, "i18n", "i18n_display_children", "Display All Children", options))) + "</span>\n </label>\n </div>\n </div>\n <div class=\"form-group\">\n <label for=\"selectedRelsView\"><span class=\"i18n\" data-i18n-id=\"i18n_rels_view\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_rels_view", "Relationships View", options) : helperMissing.call(depth0, "i18n", "i18n_rels_view", "Relationships View", options))) + "</span></label>\n <select class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-relsViewOption\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(25, program25, data),fn:self.program(23, program23, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(29, program29, data),fn:self.program(27, program27, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(33, program33, data),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "all", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "all", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </select>\n </div>\n <div class=\"form-group\">\n <label><span class=\"i18n\" data-i18n-id=\"i18n_language_refset\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_language_refset", "Language Refset", options) : helperMissing.call(depth0, "i18n", "i18n_language_refset", "Language Refset", options))) + "</span></label>\n\n "; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.manifest)),stack1 == null || stack1 === false ? stack1 : stack1.languageRefsets), {hash:{},inverse:self.noop,fn:self.programWithDepth(35, program35, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <!--<div class=\"form-group\">-->\n <!--<table class='table table-bordered table-hover'>-->\n <!--<thead>-->\n <!--<tr>-->\n <!--<th>Panel</th>-->\n <!--<th>Subscribed</th>-->\n <!--<th>Subscriptor</th>-->\n <!--</tr>-->\n <!--</thead>-->\n <!--<tbody>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.possibleSubscribers), {hash:{},inverse:self.noop,fn:self.programWithDepth(38, program38, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</tbody>-->\n <!--</table>-->\n <!--</div>-->\n</form>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/attributes-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { return "\n class = 'highlightEffectiveTime'\n "; } function program3(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" style=\"color: inherit;text-decoration: inherit;\"><span class=\"badge alert-warning\">&nbsp;&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program5(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" style=\"color: inherit;text-decoration: inherit;\"><span class=\"badge alert-warning\" >&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program7(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_primitive'>PRIMITIVE</span>\n "; } function program9(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_fully_defined'>Fully defined</span>\n "; } function program11(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_active'>Active</span>\n "; } function program13(depth0,data) { return "\n , <span class='i18n' data-i18n-id='i18n_inactive'>Inactive</span>\n "; } function program15(depth0,data) { return "\n "; } function program17(depth0,data) { var buffer = "", stack1; buffer += "\n . Descendants count, Stated: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendantsString)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " concepts, Inferred: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.inferredDescendantsString)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " concepts.\n "; return buffer; } function program19(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"pull-right\">\n <div class=\"dropdown\">\n <button class=\"btn btn-link dropdown-toggle\" type=\"button\" id=\"dropdownMenu1-details\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <i class=\"glyphicon glyphicon-plus-sign pull-right\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addsyn-icon-details\"></i>\n </button>\n <ul class=\"dropdown-menu small pull-right\" role=\"menu\" aria-labelledby=\"dropdownMenu2-details\">\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addsyn-sctid-details\">Skicka synonymförslag</a></li>\n </ul>\n </div>\n </span>\n "; return buffer; } buffer += "<table class='table table-default' >\n <tr\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n >\n <td>\n <h4>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <span ondrop=\"dropC(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\">" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n </h4>\n <br>SCTID: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.active), true, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.active), true, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(17, program17, data),fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendantsString), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendantsString), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr><tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.effectiveTime)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td></tr></table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n &nbsp;\n <span class=\"pull-right\">\n <div class=\"dropdown\">\n <button class=\"btn btn-link dropdown-toggle\" type=\"button\" id=\"dropdownMenu1-details\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <i class=\"glyphicon glyphicon-export pull-right\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-icon-details\"></i>\n </button>\n <ul class=\"dropdown-menu small pull-right\" role=\"menu\" aria-labelledby=\"dropdownMenu1-details\">\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid-details\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy ConceptId</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-term-details\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid-term-details\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " |" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "|\">Copy ConceptId + term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-link-details\" class=\"clip-btn\" data-clipboard-text=\""; if (helper = helpers.link) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.link); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Copy Link to share</a></li>\n </ul>\n </div>\n </span>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(19, program19, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.edition), "se-edition", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.edition), "se-edition", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <!--<button type=\"button\" id=\"share-link-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"btn btn-link more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"-->\n <!--<form><input class='form-control' id='share-field-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' value='"; if (helper = helpers.dataContentValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.dataContentValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "?perspective=full&conceptId1=" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&edition="; if (helper = helpers.edition) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.edition); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&release="; if (helper = helpers.release) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.release); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&server="; if (helper = helpers.server) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.server); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&langRefset="; if (helper = helpers.langRefset) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.langRefset); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></form><br>Copy the concept link (e.g. CTRL-C) to save and share a reference to this concept.-->\n <!--\" data-html=\"true\"><i class=\"glyphicon glyphicon-share-alt\"></i></button>-->\n <span class=\"pull-right\">\n <div class=\"phoca-flagbox\" style=\"width:40px;height:40px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.moduleId), options))) + "\"></span>\n </div>\n </span>\n </td>\n\n </tr>\n</table>\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/children-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this; function program1(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <tr><td draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n "; return buffer; } buffer += "<div>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th>\n <span class='i18n' data-i18n-id='i18n_children'>Children</span>\n </th>\n </tr>\n </thead>\n <tbody>\n</div>\n"; stack1 = helpers.each.call(depth0, (depth0 && depth0.childrenResult), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</tbody>\n</table>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/descriptions-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { return "\n <th>SCTID</th>\n "; } function program3(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options)); if(stack1 || stack1 === 0) { buffer += stack1; } stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth1 && depth1.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth1 && depth1.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.preferred), {hash:{},inverse:self.program(27, program27, data),fn:self.program(22, program22, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;&nbsp;&nbsp;"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth1 && depth1.options)),stack1 == null || stack1 === false ? stack1 : stack1.showIds), {hash:{},inverse:self.noop,fn:self.program(32, program32, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.preferred), {hash:{},inverse:self.program(36, program36, data),fn:self.program(34, program34, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>DescriptionId</th><th style='padding: 3px;'>Type</th><th style='padding: 3px;'>Language</th><th style='padding: 3px;'>Case Significance</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.descriptionId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.descriptionId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>" + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "</td><td style='padding: 3px;'>"; if (helper = helpers.lang) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.lang); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>" + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.ics)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.ics)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program4(depth0,data) { return " fsn-row"; } function program6(depth0,data) { return " synonym-row"; } function program8(depth0,data) { var buffer = ""; return buffer; } function program10(depth0,data) { return " danger"; } function program12(depth0,data) { return " highlightEffectiveTime"; } function program14(depth0,data) { var buffer = "", helper, options; buffer += "\n <span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_fsn", "FSN", options) : helperMissing.call(depth0, "i18n", "i18n_fsn", "FSN", options))) + "\">F</span>\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(19, program19, data),fn:self.program(17, program17, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000013009", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000013009", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program17(depth0,data) { var buffer = "", helper, options; buffer += "\n <span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_synonym", "Synonym", options) : helperMissing.call(depth0, "i18n", "i18n_synonym", "Synonym", options))) + "\">S</span>\n "; return buffer; } function program19(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000550004", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000550004", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program20(depth0,data) { var buffer = "", helper, options; buffer += "\n <span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_definition", "Definition", options) : helperMissing.call(depth0, "i18n", "i18n_definition", "Definition", options))) + "\">D</span>\n "; return buffer; } function program22(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(25, program25, data),fn:self.program(23, program23, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000003001", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program23(depth0,data) { var buffer = "", helper, options; buffer += "\n &nbsp;<span class=\"glyphicon glyphicon-star-empty\" rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_preferred", "Preferred", options) : helperMissing.call(depth0, "i18n", "i18n_preferred", "Preferred", options))) + "\"></span>\n "; return buffer; } function program25(depth0,data) { var buffer = "", helper, options; buffer += "\n &nbsp;<span class=\"glyphicon glyphicon-star\" rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_preferred", "Preferred", options) : helperMissing.call(depth0, "i18n", "i18n_preferred", "Preferred", options))) + "\"></span>\n "; return buffer; } function program27(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.acceptable), {hash:{},inverse:self.program(30, program30, data),fn:self.program(28, program28, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program28(depth0,data) { var buffer = "", helper, options; buffer += "\n &nbsp;<span rel=\"tooltip-right\" title=\"" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_acceptable", "Acceptable", options) : helperMissing.call(depth0, "i18n", "i18n_acceptable", "Acceptable", options))) + "\">&#10004;</span></span>\n "; return buffer; } function program30(depth0,data) { return "\n &nbsp;&nbsp;&nbsp;\n "; } function program32(depth0,data) { var buffer = "", stack1; buffer += "\n <td>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.concept)),stack1 == null || stack1 === false ? stack1 : stack1.id)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n "; return buffer; } function program34(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n' data-i18n-id='i18n_preferred'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_preferred", "Preferred", options) : helperMissing.call(depth0, "i18n", "i18n_preferred", "Preferred", options))) + "</span>\n "; return buffer; } function program36(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.acceptable), {hash:{},inverse:self.program(39, program39, data),fn:self.program(37, program37, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program37(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n' data-i18n-id='i18n_acceptable'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_acceptable", "Acceptable", options) : helperMissing.call(depth0, "i18n", "i18n_acceptable", "Acceptable", options))) + "</span>\n "; return buffer; } function program39(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n' data-i18n-id='i18n_not_acceptable'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_not_acceptable", "Not acceptable", options) : helperMissing.call(depth0, "i18n", "i18n_not_acceptable", "Not acceptable", options))) + "</span>\n "; return buffer; } buffer += "<table class='table table-bordered' id = '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descriptions-panel-table'>\n <thead>\n <tr>\n <th colspan=\"2\" class=\"text-center\">" + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.longLangName), options) : helperMissing.call(depth0, "removeSemtag", (depth0 && depth0.longLangName), options))) + "</th>\n </tr>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_term'>Term</span></th>\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.showIds), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <th><span class='i18n' data-i18n-id='i18n_acceptability'>Acceptability</span>&nbsp;&nbsp;"; if (helper = helpers.languageName) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.languageName); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.allDescriptions), {hash:{},inverse:self.noop,fn:self.programWithDepth(3, program3, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n</table>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/diagram.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div class=\"container\" style=\"max-width: 100%;\">\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagram-toolbar\" class=\"row\">\n <div class=\"row\" style=\"margin: 15px;\">\n <div class=\"btn-toolbar pull-right\" role=\"toolbar\">\n <div class=\"btn-group\" role=\"group\" aria-label=\"...\" style=\"margin-right: 5px;\">\n <button type=\"button\" class=\"btn btn-default btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-stated-button-d\">Stated</button>\n <button type=\"button\" class=\"btn btn-default btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferred-button-d\">Inferred</button>\n </div>\n </div>\n </div>\n </div>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-diagram-body\" class=\"row\" style=\"overflow: auto; width: 1000;\">\n\n </div>\n</div>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/details/rels-panel.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, self=this, helperMissing=helpers.helperMissing, functionType="function", escapeExpression=this.escapeExpression; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), "undefined", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(27, program27, data),fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(34, program34, data),fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), "undefined", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(55, program55, data),fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), "undefined", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program3(depth0,data) { return "\n <tr><td colspan='4'><span class='text-muted'>No relationships</span></td></tr>\n "; } function program5(depth0,data) { var buffer = "", stack1; buffer += "\n\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(7, program7, data, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program7(depth0,data,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='inferred-rel\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n '>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n ham\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>TypeId</th><th style='padding: 3px;'>TargetId</th><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program8(depth0,data) { return "\n highlightEffectiveTime\n "; } function program10(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_stated'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_stated", "Stated", options) : helperMissing.call(depth0, "i18n", "i18n_stated", "Stated", options))) + "</span>\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program21(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_inferred'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_inferred", "Inferred", options) : helperMissing.call(depth0, "i18n", "i18n_inferred", "Inferred", options))) + "</span>\n "; return buffer; } function program23(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_other'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_other", "Other", options) : helperMissing.call(depth0, "i18n", "i18n_other", "Other", options))) + "</span>\n "; return buffer; } function program25(depth0,data) { return "\n "; } function program27(depth0,data) { var buffer = "", stack1; buffer += "\n\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), {hash:{},inverse:self.noop,fn:self.program(28, program28, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program28(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(29, program29, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program29(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='stated-rel\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n '>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(30, program30, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program32(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program34(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(35, program35, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program35(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(36, program36, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program36(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(37, program37, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program37(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='stated-rel\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(38, program38, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n '>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(42, program42, data),fn:self.program(40, program40, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(46, program46, data),fn:self.program(44, program44, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(50, program50, data),fn:self.program(48, program48, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program38(depth0,data) { return "\n highlightEffectiveTime\n "; } function program40(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program42(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program44(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program46(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program48(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_stated'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_stated", "Stated", options) : helperMissing.call(depth0, "i18n", "i18n_stated", "Stated", options))) + "</span>\n "; return buffer; } function program50(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(53, program53, data),fn:self.program(51, program51, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program51(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_inferred'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_inferred", "Inferred", options) : helperMissing.call(depth0, "i18n", "i18n_inferred", "Inferred", options))) + "</span>\n "; return buffer; } function program53(depth0,data) { var buffer = "", helper, options; buffer += "\n <td><span class='i18n' data-i18n-id='i18n_other'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_other", "Other", options) : helperMissing.call(depth0, "i18n", "i18n_other", "Other", options))) + "</span>\n "; return buffer; } function program55(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(35, program35, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program57(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.noop,fn:self.program(58, program58, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program58(depth0,data) { return "\n <p>No additional relationships</p>\n "; } function program60(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.additionalRels), {hash:{},inverse:self.noop,fn:self.program(61, program61, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n"; return buffer; } function program61(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(62, program62, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program62(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(65, program65, data),fn:self.program(63, program63, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(69, program69, data),fn:self.program(67, program67, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_additional", "Additional", options) : helperMissing.call(depth0, "i18n", "i18n_additional", "Additional", options))) + "</span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program63(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program65(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program67(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program69(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program71(depth0,data) { return "\n <p>No Axioms found</p>\n"; } function program73(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(74, program74, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program74(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <p>Class Axiom - "; if (helper = helpers.axiomId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.axiomId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(75, program75, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; return buffer; } function program75(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(76, program76, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program76(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(30, program30, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>Axiom </span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } function program78(depth0,data) { return "\n <p>No GCI's found</p>\n"; } function program80(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(81, program81, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program81(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <p>GCI Axiom - "; if (helper = helpers.axiomId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.axiomId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(82, program82, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; return buffer; } function program82(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(83, program83, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program83(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(30, program30, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>"; if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>GCI Axiom</span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; return buffer; } stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n"; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(60, program60, data),fn:self.program(57, program57, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.additionalRels), options) : helperMissing.call(depth0, "if_undefined", (depth0 && depth0.additionalRels), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n"; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(73, program73, data),fn:self.program(71, program71, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(80, program80, data),fn:self.program(78, program78, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/expression.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<p class=\"\" style=\"margin-top: 20px;\">Pre-coordinated Expression (*)&nbsp;&nbsp;&nbsp;&nbsp;<small><i class=\"glyphicon glyphicon-export clip-btn-exp\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-pre-coordinated-expression\" data-clipboard-text=\""; if (helper = helpers.plainPreCoordinatedExpression) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.plainPreCoordinatedExpression); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></i></small></p>\n<div class=\"expression-code\" style=\"margin-top: 10px; padding: 10px;\">"; if (helper = helpers.preCoordinatedExpressionHtml) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.preCoordinatedExpressionHtml); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n<p class=\"\" style=\"margin-top: 20px;\">Expression from Stated Concept Definition (*)&nbsp;&nbsp;&nbsp;&nbsp;<small><i class=\"glyphicon glyphicon-export clip-btn-exp\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-stated-expression\" data-clipboard-text=\""; if (helper = helpers.plainStatedExpression) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.plainStatedExpression); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></i></small></p>\n<div class=\"expression-code\" style=\"margin-top: 10px; padding: 10px;\">"; if (helper = helpers.statedExpressionHtml) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedExpressionHtml); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n<p class=\"\" style=\"margin-top: 20px;\">Expression from Inferred Concept Definition (*)&nbsp;&nbsp;&nbsp;&nbsp;<small><i class=\"glyphicon glyphicon-export clip-btn-exp\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-inferred-expression\" data-clipboard-text=\""; if (helper = helpers.plainInferredExpression) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.plainInferredExpression); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></i></small></p>\n<div class=\"expression-code\" style=\"margin-top: 10px; padding: 10px;\">"; if (helper = helpers.inferredExpressionHtml) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.inferredExpressionHtml); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n<br><br>\n<div class=\"well small\">\n <p>(*) The expressions are generated according to the ABNF syntax found in the \"SNOMED CT Compositional Grammar Specification and Guide\" (<a href=\"http://snomed.org/compgrammar\" target=\"_blank\">http://snomed.org/compgrammar</a>)</p>\n <p>SNOMED CT Compositional Grammar is a lightweight syntax for the representation of SNOMED CT expressions. SNOMED CT expressions are used in Electronic Health Records (EHRs) to represent clinical meanings in a way that enables automatic interpretation. They are also carried in messages, used to define precoordinated concepts and used to represent links between SNOMED CT and other terminologies.</p>\n <p>These expressions are generated as an example from the published concept definition, a Pre-coordinated Expression is direct reference to the concept, and Post-coordinated expressions are generated from the stated or inferred relationships. In a Sufficiently Defined concept, all three will be equivalent.</p>\n</div>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/attributes.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { var buffer = ""; return buffer; } function program3(depth0,data) { return "-empty"; } function program5(depth0,data) { return "\n &nbsp;&nbsp;\n "; } function program7(depth0,data) { return "\n &equiv;\n "; } buffer += "<h4 data-droppable=\"true\" ondrop=\"dropC(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\">\n <span class=\"pull-right\">\n <div class=\"dropdown\">\n <button class=\"btn btn-link dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\" style=\"padding: 0px;\">\n <i class=\"glyphicon glyphicon-export pull-right\" style=\"color: white;\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-icon\"></i>\n </button>\n <ul class=\"dropdown-menu small\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy ConceptId</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-term\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">Copy term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-sctid-term\" class=\"clip-btn\" data-clipboard-text=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " |" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "|\">Copy ConceptId + term</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copy-link\" class=\"clip-btn\" data-clipboard-text=\""; if (helper = helpers.link) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.link); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">Copy Link to share</a></li>\n </ul>\n </div>\n </span>\n <span class=\"pull-right\">\n <a href=\"javascript:void(0);\" style=\"font-size: 20px; color: white; padding: 5px;\">\n <span data-conceptId=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" class=\"glyphicon glyphicon-star"; stack1 = (helper = helpers.if_fav || (depth0 && depth0.if_fav),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), options) : helperMissing.call(depth0, "if_fav", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\"></span>\n </a>\n </span>\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">\n <span class=\"badge alert-warning\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </span>\n </a>\n &nbsp;&nbsp;\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n <span class=\"pull-right\">\n <div class=\"phoca-flagbox\" style=\"width:40px;height:40px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n </span>\n</h4>\n\n<h5>SCTID: " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "<br><br><div id=\"copy-content-custom\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " | " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " |</div></h5>\n\n<div id=\"home-descriptions-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\"></div>\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/children.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", helper, options; buffer += "\n <span data-i18n-id=\"i18n_no_children\" class=\"text-muted i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_children", "No Children", options) : helperMissing.call(depth0, "i18n", "i18n_no_children", "No Children", options))) + "</span>\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 15px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.childrenResult), {hash:{},inverse:self.noop,fn:self.programWithDepth(5, program5, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program5(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth2 && depth2.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth2 && depth2.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", (depth2 && depth2.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(16, program16, data, depth1),fn:self.programWithDepth(14, program14, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span class=\"treeLabel selectable-row\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" id=\"" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n </li>\n "; return buffer; } function program7(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafInferred), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafInferred), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program8(depth0,data) { return "minus"; } function program10(depth0,data) { return "chevron-right"; } function program12(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafStated), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafStated), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program14(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program16(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program21(depth0,data) { var buffer = "", helper, options; buffer += "\n <span data-i18n-id=\"i18n_no_children\" class=\"text-muted i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_children", "No children", options) : helperMissing.call(depth0, "i18n", "i18n_no_children", "No children", options))) + "</span>\n "; return buffer; } function program23(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(26, program26, data),fn:self.program(24, program24, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 30, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length), 30, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program24(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <button id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-showChildren\" class=\"btn btn-link\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.childrenResult)),stack1 == null || stack1 === false ? stack1 : stack1.length)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " <span data-i18n-id=\"i18n_children\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_children", "children", options) : helperMissing.call(depth0, "i18n", "i18n_children", "children", options))) + "</span></button>\n "; return buffer; } function program26(depth0,data) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 15px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.childrenResult), {hash:{},inverse:self.noop,fn:self.programWithDepth(27, program27, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program27(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(28, program28, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program28(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth2 && depth2.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth2 && depth2.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", (depth2 && depth2.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(31, program31, data, depth1),fn:self.programWithDepth(29, program29, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(33, program33, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span class=\"treeLabel selectable-row\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" id=\"" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n </li>\n "; return buffer; } function program29(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program31(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program33(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } stack1 = helpers['if'].call(depth0, (depth0 && depth0.displayChildren), {hash:{},inverse:self.program(20, program20, data),fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/parents.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, self=this, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(5, program5, data, depth0),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(28, program28, data, depth0),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedParentsFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program3(depth0,data) { return "\n <span class='text-muted'>No parents</span>\n "; } function program5(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 2px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedParents), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program6(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li class=\"treeLabel\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n <!--<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='text-warning' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>-->\n <!--"; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</span>&nbsp;&rArr;&nbsp;-->\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' data-first=\"true\" data-ind=\"" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(18, program18, data, depth1),fn:self.programWithDepth(16, program16, data, depth1),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "hasCountryIcon", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(24, program24, data, depth2),fn:self.programWithDepth(22, program22, data, depth2),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </span>\n </a>\n </li>\n "; return buffer; } function program7(depth0,data) { var buffer = "", stack1, helper, options; buffer += "-->\n <!--" + escapeExpression((helper = helpers.substr || (depth0 && depth0.substr),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options) : helperMissing.call(depth0, "substr", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), 0, options))) + "-->\n <!--"; return buffer; } function program9(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-->\n <!--"; return buffer; } function program11(depth0,data) { return "minus"; } function program13(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "9999999999", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "9999999999", options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program14(depth0,data) { return "chevron-right"; } function program16(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program20(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program22(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program24(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program26(depth0,data) { return "\n "; } function program28(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 2px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedParentsFromAxioms), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(33, program33, data, depth0),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.inferredParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.inferredParents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program31(depth0,data) { return "\n <span class='text-muted'>No parents</span>\n "; } function program33(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n <ul style='list-style-type: none; padding-left: 2px; padding-top: 0px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.inferredParents), {hash:{},inverse:self.noop,fn:self.programWithDepth(34, program34, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n "; return buffer; } function program34(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li class=\"treeLabel\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n <!--<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='text-warning' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>-->\n <!--" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-->\n <!--</span>&nbsp;&rArr;&nbsp;-->\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "138875005", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' data-first=\"true\" data-ind=\"" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(37, program37, data, depth1),fn:self.programWithDepth(35, program35, data, depth1),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "hasCountryIcon", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(41, program41, data, depth2),fn:self.programWithDepth(39, program39, data, depth2),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </span>\n </a>\n </li>\n "; return buffer; } function program35(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program37(depth0,data,depth2) { var buffer = "", stack1; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program39(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program41(depth0,data,depth3) { var buffer = "", stack1; buffer += "\n <span id='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + escapeExpression(((stack1 = (depth3 && depth3.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(30, program30, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n\n\n\n\n\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/home/roles.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedRoles), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.statedRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.statedRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n \n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(17, program17, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(30, program30, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <!--<br>-->\n "; stack1 = (helper = helpers.eqLastGroup || (depth0 && depth0.eqLastGroup),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "eqLastGroup", (depth0 && depth0.groupId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-attribute-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span>&nbsp;&rarr;&nbsp;\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "\n </span><br>\n "; return buffer; } function program3(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n </div>\n " + escapeExpression((helper = helpers.setLastGroup || (depth0 && depth0.setLastGroup),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "setLastGroup", (depth0 && depth0.groupId), options))) + "\n " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "random", options) : helperMissing.call(depth0, "lastColor", "random", options))) + "\n <div "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.groupId), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program4(depth0,data) { var buffer = ""; return buffer; } function program6(depth0,data) { return "style=\"border: 1px solid darkgrey; border-radius: 4px; padding: 3px; background-color: white; margin: 5px;\""; } function program8(depth0,data) { var buffer = "", helper, options; buffer += "\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program10(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.attributesFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.attributesFromAxioms)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program15(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n text-muted' data-i18n-id='i18n_no_attributes'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_attributes", "No relationships", options) : helperMissing.call(depth0, "i18n", "i18n_no_attributes", "No relationships", options))) + "</span>\n "; return buffer; } function program17(depth0,data) { var buffer = "", stack1; buffer += "\n <div>Axiom</div>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div> \n "; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(21, program21, data),fn:self.program(19, program19, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "116680003", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "116680003", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program19(depth0,data) { return "\n "; } function program21(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <!--<br>-->\n "; stack1 = (helper = helpers.eqLastGroup || (depth0 && depth0.eqLastGroup),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "eqLastGroup", (depth0 && depth0.groupId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;<span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-attribute-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span>&nbsp;&rarr;&nbsp;\n\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(28, program28, data),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "\n </span><br>\n "; return buffer; } function program22(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n </div>\n " + escapeExpression((helper = helpers.setLastGroup || (depth0 && depth0.setLastGroup),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "setLastGroup", (depth0 && depth0.groupId), options))) + "\n " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "random", options) : helperMissing.call(depth0, "lastColor", "random", options))) + "\n <div "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.groupId), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program24(depth0,data) { var buffer = "", helper, options; buffer += "\n <span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "'></span>\n "; return buffer; } function program26(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-primitive-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program28(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-defined-concept-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1; buffer += "\n <div>GCI</div>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; return buffer; } function program32(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.inferredRoles), {hash:{},inverse:self.noop,fn:self.program(33, program33, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(38, program38, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.inferredRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.inferredRoles)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program33(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <!--<br>inferred-->\n "; stack1 = (helper = helpers.eqLastGroup || (depth0 && depth0.eqLastGroup),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.groupId), options) : helperMissing.call(depth0, "eqLastGroup", (depth0 && depth0.groupId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n &nbsp;<span style='background-color: " + escapeExpression((helper = helpers.lastColor || (depth0 && depth0.lastColor),options={hash:{},data:data},helper ? helper.call(depth0, "get", options) : helperMissing.call(depth0, "lastColor", "get", options))) + "' draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='sct-attribute-compact' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span>&nbsp;&rarr;&nbsp;\n <span draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(36, program36, data),fn:self.program(34, program34, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n ' data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term), options))) + "</span><br>\n "; return buffer; } function program34(depth0,data) { return "\n sct-primitive-concept-compact\n "; } function program36(depth0,data) { return "\n sct-defined-concept-compact\n "; } function program38(depth0,data) { var buffer = "", helper, options; buffer += "\n <span class='i18n text-muted' data-i18n-id='i18n_no_attributes'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_attributes", "No relationships", options) : helperMissing.call(depth0, "i18n", "i18n_no_attributes", "No relationships", options))) + "</span>\n "; return buffer; } buffer += "<div style='line-height: 100%;'>\n " + escapeExpression((helper = helpers.setLastGroup || (depth0 && depth0.setLastGroup),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.null), options) : helperMissing.call(depth0, "setLastGroup", (depth0 && depth0.null), options))) + "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</div>\n"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/members.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { var buffer = "", helper, options; buffer += "\n <thead>\n <tr>\n <th><span data-i18n-id=\"i18n_term\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_term", "Term", options) : helperMissing.call(depth0, "i18n", "i18n_term", "Term", options))) + "</span></th>\n <th><span data-i18n-id=\"i18n_conceptId\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_conceptId", "Concept Id", options) : helperMissing.call(depth0, "i18n", "i18n_conceptId", "Concept Id", options))) + "</span></th>\n </tr>\n </thead>\n"; return buffer; } function program3(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class=\"member-row\">\n <td data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n\n "; return buffer; } function program4(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span></button>\n </td>\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program9(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <td class=\"text-muted\" class=\"text-center\" colspan=\"2\">"; if (helper = helpers.total) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.total); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_members\" class=\"i18n\">members</span></td>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.skipTo), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.skipTo), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.items), {hash:{},inverse:self.noop,fn:self.programWithDepth(3, program3, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <tr class=\"more-row\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), "asd", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), "asd", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tr>\n</tbody>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/product.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n </tr>\n "; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program10(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n <br>\n &nbsp;&nbsp;&nbsp;<span class=\"text-muted\"><em>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.boss)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</em></span>\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.numeratorValue), {hash:{},inverse:self.noop,fn:self.program(15, program15, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.numeratorUnit), {hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.denominatorValue), {hash:{},inverse:self.noop,fn:self.program(25, program25, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n <td>\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.denominatorUnit), {hash:{},inverse:self.noop,fn:self.program(30, program30, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </td>\n </tr>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.ingredient)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program15(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(18, program18, data),fn:self.program(16, program16, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program21(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program23(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.numeratorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program25(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(28, program28, data),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program26(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program28(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(33, program33, data),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression((helper = helpers.removeSemtag || (depth0 && depth0.removeSemtag),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options) : helperMissing.call(depth0, "removeSemtag", ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm), options))) + "\n "; return buffer; } function program31(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program33(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.denominatorUnit)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } buffer += "<br>\n<h4>&nbsp;&nbsp;&nbsp;" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.productData)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</h4>\n<br>\n<table class='table table-bordered' id = ''>\n <thead>\n <tr><th colspan=\"2\">Dose form</th></tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.productData)),stack1 == null || stack1 === false ? stack1 : stack1.forms), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n</table>\n<br>\n<table class='table table-bordered' id = ''>\n <thead>\n <tr>\n <th>Ingredient / BoSS</th>\n <th colspan=\"2\">Strength Numerator</th>\n <th colspan=\"2\">Strength Denominator</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.productData)),stack1 == null || stack1 === false ? stack1 : stack1.ingredients), {hash:{},inverse:self.noop,fn:self.program(10, program10, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n</table>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/references.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <div style=\"margin-top: 10px;\" class=\"panel panel-default\">\n <div class=\"panel-heading\">\n <h3 style=\"font-size: 12px\" class=\"panel-title\">\n <a style=\"text-decoration: inherit;\" data-toggle=\"collapse\" data-parent=\"#references-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-accordion\" href=\"#references-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">\n <span id=\"references-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-span\" class=\"references glyphicon glyphicon-"; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.length), 10, options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.length), 10, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\"></span>\n </a>&nbsp;" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0[0])),stack1 == null || stack1 === false ? stack1 : stack1.relationship)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " ("; if (helper = helpers.length) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.length); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")\n </h3>\n </div>\n <div id=\"references-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" class=\"panel-collapse collapse "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.length), 10, options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.length), 10, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"panel-body\">\n <table class=\"table table-hover table-bordered\">\n <thead>\n <tr>\n <th>Term</th>\n <th>ConceptId</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, depth0, {hash:{},inverse:self.noop,fn:self.programWithDepth(10, program10, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n </div>\n </div>\n"; return buffer; } function program2(depth0,data) { return "chevron-right"; } function program4(depth0,data) { return "chevron-down"; } function program6(depth0,data) { var buffer = ""; return buffer; } function program8(depth0,data) { return "in"; } function program10(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n <td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n </tr>\n "; return buffer; } function program11(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program13(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "-->\n <!--<tr>-->\n <!--<td>-->\n <!--<span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>-->\n <!--"; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-->\n <!--</td>-->\n <!--<td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>-->\n <!--<td>-->\n <!--"; stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(16, program16, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n\n <!--"; stack1 = helpers.each.call(depth0, (depth0 && depth0.statedRelationships), {hash:{},inverse:self.noop,fn:self.program(16, program16, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</td>-->\n <!--</tr>-->\n <!--"; return buffer; } function program14(depth0,data) { var buffer = "", helper, options; buffer += "-->\n <!--<div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">-->\n <!--<span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>-->\n <!--</div>-->\n <!--"; return buffer; } function program16(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-->\n <!--"; return buffer; } stack1 = helpers.each.call(depth0, (depth0 && depth0.groups), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n<!--<thead>-->\n <!--<tr>-->\n <!--<th>Term</th>-->\n <!--<th>ConceptId</th>-->\n <!--<th>Relationships Type</th>-->\n <!--</tr>-->\n<!--</thead>-->\n<!--<tbody>-->\n <!--"; stack1 = helpers.each.call(depth0, (depth0 && depth0.result), {hash:{},inverse:self.noop,fn:self.programWithDepth(13, program13, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n</tbody>"; return buffer; }); this["JST"]["views/conceptDetailsPlugin/tabs/refset.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, self=this, functionType="function"; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLE_REFSET", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLE_REFSET", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simple", true, options) : helperMissing.call(depth0, "refset", "simple", true, options))) + "\n "; return buffer; } function program4(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLEMAP", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLEMAP", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program5(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simplemap", true, options) : helperMissing.call(depth0, "refset", "simplemap", true, options))) + "\n "; return buffer; } function program7(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "ATTRIBUTE_VALUE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "ATTRIBUTE_VALUE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program8(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "attr", true, options) : helperMissing.call(depth0, "refset", "attr", true, options))) + "\n "; return buffer; } function program10(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "assoc", true, options) : helperMissing.call(depth0, "refset", "assoc", true, options))) + "\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLE_REFSET", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLE_REFSET", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program13(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>"; if (helper = helpers.otherValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.otherValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'>\n <tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\"data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program14(depth0,data) { var buffer = ""; return buffer; } function program16(depth0,data) { return "danger"; } function program18(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program22(depth0,data) { return "\n </tbody>\n "; } function program24(depth0,data) { return "\n <tr><td><span class='i18n text-muted' data-i18n-id='i18n_no_memberships'>No memberships</span></td></tr>\n </tbody>\n "; } function program26(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(27, program27, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "SIMPLEMAP", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "SIMPLEMAP", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program27(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(30, program30, data),fn:self.program(28, program28, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td class=\"refset-simplemap\" data-refsetId=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-conceptId=\""; if (helper = helpers.otherValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.otherValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.otherValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.otherValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program28(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program30(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program32(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(33, program33, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "ATTRIBUTE_VALUE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "ATTRIBUTE_VALUE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program33(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(36, program36, data),fn:self.program(34, program34, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program34(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program36(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program38(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(39, program39, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.type), "ASSOCIATION", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.type), "ASSOCIATION", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program39(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(42, program42, data),fn:self.program(40, program40, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n <td>\n <div class=\"phoca-flagbox\" style=\"width:35px;height:35px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>RefsetId</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr>\n <td style='padding: 3px;'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.refset)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td><td style='padding: 3px;'>"; if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td><td style='padding: 3px;'>"; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i>\n </button>\n </td>\n </tr>\n "; return buffer; } function program40(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; return buffer; } function program42(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart = \"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-def-status=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.cidValue)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; return buffer; } buffer += escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simple", false, options) : helperMissing.call(depth0, "refset", "simple", false, options))) + "\n" + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "simplemap", false, options) : helperMissing.call(depth0, "refset", "simplemap", false, options))) + "\n" + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "attr", false, options) : helperMissing.call(depth0, "refset", "attr", false, options))) + "\n" + escapeExpression((helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},data:data},helper ? helper.call(depth0, "assoc", false, options) : helperMissing.call(depth0, "refset", "assoc", false, options))) + "\n\n"; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n<div style=\"margin: 10px;\">\n <a class=\"btn btn-primary btn-sm pull-right\" href=\"https://mapping.ihtsdotools.org/#/record/conceptId/" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "/autologin?refSetId=P447562003\" target=\"_blank\" role=\"button\">Open maps for this concept</a>\n</div>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_simple_refset_memberships'>Simple Refsets Membership</span></th>\n </tr></thead>\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(12, program12, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "simple", "get", options) : helperMissing.call(depth0, "refset", "simple", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_simple_map_refset_name'>Simple Map Refset name</span></th>\n </tr></thead>\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(26, program26, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "simplemap", "get", options) : helperMissing.call(depth0, "refset", "simplemap", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_attribute_value_refset_name'>Attribute Value Refset name</span></th>\n </tr></thead>\n<tbody>\n\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(32, program32, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "attr", "get", options) : helperMissing.call(depth0, "refset", "attr", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n\n<table class='table table-hover'>\n <thead><tr>\n <th colspan=\"3\"><span class='i18n' data-i18n-id='i18n_association_refset_name'>Association Refset name</span></th>\n </tr></thead>\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.memberships), {hash:{},inverse:self.noop,fn:self.program(38, program38, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.refset || (depth0 && depth0.refset),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, "assoc", "get", options) : helperMissing.call(depth0, "refset", "assoc", "get", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</table>\n"; return buffer; }); this["JST"]["views/developmentQueryPlugin/andCriteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { return "Conjunction"; } function program3(depth0,data) { var stack1, helper; if (helper = helpers.typeSelected) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeSelected); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } return escapeExpression(stack1); } function program5(depth0,data) { return "\n and\n "; } function program7(depth0,data) { return "\n attribute\n "; } function program9(depth0,data) { var buffer = ""; return buffer; } function program11(depth0,data) { return "style=\"display: none;\""; } function program13(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <li role=\"presentation\"><a class=\"selectTypeOpt\" data-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a></li>\n "; return buffer; } buffer += "<div class=\"addedCriteria\" data-typeSelected=\""; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.typeSelected), "false", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.typeSelected), "false", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">\n <div class=\"form-group text-center\" style=\"width: 75px;\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.typeSelected), "Conjunction", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.typeSelected), "Conjunction", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n <div data-type-concept-id=\"false\" class=\"form-group typeCritCombo\" "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.typeSelected), "Refinement", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.typeSelected), "Refinement", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <div class=\"dropdown\">\n <button style=\"width: 147px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span>Select type&nbsp;</span>\n <span class=\"caret\"></span>\n </button>\n <ul style=\"max-height: 400px; overflow: auto;\" class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a class=\"selectTypeOpt\" data-id=\"*\" data-term=\"Any\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">Any</a></li>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.types), {hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n </div>\n </div>\n <div class=\"form-group\">\n <div class=\"dropdown\">\n <button style=\"width: 147px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span class=\"addSelectCriteria\">"; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOf</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOrSelfOf</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">self</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">isMemberOf</a></li>\n </ul>\n </div>\n </div>\n <div class=\"form-group\">\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control andCriteriaConcept\" placeholder=\"Drag a concept here\" readonly>\n </div>\n <div class=\"form-group\"><button type=\"button\" class=\"btn btn-link glyphicon glyphicon-remove removeCriteria\" style=\"text-decoration: none;\"></button></div>\n <div class=\"form-group\"><button type=\"button\" class=\"btn btn-link glyphicon glyphicon-plus addCriteria\" style=\"text-decoration: none;\"></button></div>\n</div>"; return buffer; }); this["JST"]["views/developmentQueryPlugin/criteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, self=this, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; function program1(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (data == null || data === false ? data : data.index), 0, options) : helperMissing.call(depth0, "if_eq", (data == null || data === false ? data : data.index), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <span class=\"constraint\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-criteria=\""; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <!--"; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;-->\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.noop,fn:self.program(15, program15, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <div style=\"display: inline-block;\" class=\"dropdown\">\n <button style=\"text-decoration: inherit; color: inherit; display: inline-block; padding: 0px;\" class=\"btn btn-link dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n "; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\">\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOf</a></li>\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOrSelfOf</a></li>\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">self</a></li>\n <li role=\"presentation\"><a class=\"criteriaDropdownOption\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">isMemberOf</a></li>\n </ul>\n </div>\n <span style=\"color: forestgreen;\">"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>&nbsp;\n |\n <span style=\"color: firebrick;\">"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n |"; stack1 = helpers['if'].call(depth0, ((stack1 = ((stack1 = ((stack1 = (depth1 && depth1.criterias)),stack1 == null || stack1 === false ? stack1 : stack1[1])),stack1 == null || stack1 === false ? stack1 : stack1.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.noop,fn:self.programWithDepth(17, program17, data, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </span>\n "; return buffer; } function program2(depth0,data) { return "\n "; } function program4(depth0,data) { var buffer = "", stack1; buffer += "\n <br>\n <div style=\"margin-left: "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.program(7, program7, data),fn:self.program(5, program5, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "px; display: inline-block\">\n "; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), {hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </div>\n "; return buffer; } function program5(depth0,data) { return "68"; } function program7(depth0,data) { return "43"; } function program9(depth0,data) { var buffer = ""; return buffer; } function program11(depth0,data) { return "AND"; } function program13(depth0,data) { var buffer = "", stack1; buffer += "data-type-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-type-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\""; return buffer; } function program15(depth0,data) { var buffer = "", stack1; buffer += "\n <span style=\"color: forestgreen;\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span> |\n <span style=\"color: firebrick;\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span> | =\n "; return buffer; } function program17(depth0,data,depth2) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eqInd || (depth2 && depth2.if_eqInd),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, (data == null || data === false ? data : data.index), ((stack1 = (depth2 && depth2.criterias)),stack1 == null || stack1 === false ? stack1 : stack1.length), options) : helperMissing.call(depth0, "if_eqInd", (data == null || data === false ? data : data.index), ((stack1 = (depth2 && depth2.criterias)),stack1 == null || stack1 === false ? stack1 : stack1.length), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program18(depth0,data) { return "\n "; } function program20(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (data == null || data === false ? data : data.index), {hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program21(depth0,data) { return "\n ,\n "; } function program23(depth0,data) { return "\n :\n "; } buffer += "<li data-modifier=\""; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"list-group-item clearfix query-condition\">\n <span class=\"text-muted line-number\" style=\"font-size: 200%;\"></span>&nbsp;&nbsp;\n <span style=\"position: relative; top: -5px;\">\n <div style=\"width: 45px;display: inline-block;\">"; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ":</div>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.criterias), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </span>\n <button class='pull-right btn btn-link removeLi' style=\"position: relative; top: 3px;\">\n <i class='glyphicon glyphicon-remove'></i>\n </button>\n </li>"; return buffer; }); this["JST"]["views/developmentQueryPlugin/examples.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var stack1, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <br>\n <div id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-modal-examples\" "; stack1 = (helper = helpers.if_eqInd || (depth1 && depth1.if_eqInd),options={hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (data == null || data === false ? data : data.index), ((stack1 = (depth1 && depth1.examples)),stack1 == null || stack1 === false ? stack1 : stack1.length), options) : helperMissing.call(depth0, "if_eqInd", (data == null || data === false ? data : data.index), ((stack1 = (depth1 && depth1.examples)),stack1 == null || stack1 === false ? stack1 : stack1.length), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ">\n <h4>"; if (helper = helpers.title) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.title); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</h4>\n <span data-htmlValue=\""; if (helper = helpers.htmlValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.htmlValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"pull-right btn btn-primary btn-xs loadExample\" style=\"padding: 0px; display: inline-block;\">Load instructions</span>\n <br>\n <div class=\"contentExamples\" style=\"margin: 10px;\">"; if (helper = helpers.htmlValue) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.htmlValue); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n <br>\n </div>\n"; return buffer; } function program2(depth0,data) { return "style=\"min-height: 450px;\""; } stack1 = helpers.each.call(depth0, (depth0 && depth0.examples), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } }); this["JST"]["views/developmentQueryPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data,depth1) { var buffer = "", stack1, helper; buffer += "\n <li><a contenteditable=\"false\" href=\"#" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-" + escapeExpression(((stack1 = (data == null || data === false ? data : data.index)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-modal-examples\" class=\"list-group-item\">"; if (helper = helpers.title) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.title); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a></li>\n "; return buffer; } buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong>"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_terminology_content_selection", "Terminology content selections", options) : helperMissing.call(depth0, "i18n", "i18n_terminology_content_selection", "Terminology content selections", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</strong></div>\n <div class='col-md-6 text-right'>\n <!--<a class=\"btn btn-link\" href=\"help/topics/creating-queries.html\" target=\"_blank\" title=\"Help\" role=\"button\"><i class='glyphicon glyphicon-question-sign'></i></a>-->\n </div>\n </div>\n </div>\n <div class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <!--<p style=\"margin: 10px;\">Create a query, conditions are evaluated in order:</p>-->\n <div class=\"row container-fluid\" style=\"margin: 10px;\">\n <p class=\"lead col-md-6\">Enter an expression</p>\n <button type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-helpButton\" class=\"btn btn-default pull-right\" style=\"margin: 10px;\" data-toggle=\"modal\" data-target=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-queryHelpModal\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_help", "Help", options) : helperMissing.call(depth0, "i18n", "i18n_help", "Help", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <button type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-clearButton\" class=\"btn btn-default pull-right\" style=\"margin: 10px;\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_clear", "Clear", options) : helperMissing.call(depth0, "i18n", "i18n_clear", "Clear", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <!--<p><strong>This will execute against the current MAIN branch of the authoring platform. Please make sure you have logged into the authoring platform to be able to run any queries.</strong></p> -->\n </div>\n <div>\n <ul class=\"nav nav-tabs\">\n <li class=\"active\"><a href=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExpTab\" data-toggle=\"tab\"><span class=\"i18n\" data-i18n-id=\"i18n_expression\">Enter an existing expression</span></a></li>\n <!-- <li><a href=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-BuilderTab\" data-toggle=\"tab\"><span class=\"i18n\" data-i18n-id=\"i18n_builder\">Build a simple expression</span></a></li>\n-->\n </ul>\n <div class=\"tab-content\">\n <div class=\"tab-pane\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-BuilderTab\" style=\"padding: 0px;margin: 0;\">\n <div class=\"row container-fluid\" style=\"margin: 10px;\">\n <form class=\"form-inline\" role=\"form\">\n <div class=\"form-group\">\n <div class=\"dropdown\">\n <button style=\"width: 75px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modifierButton\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedModifier\">Include</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modifierButton\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"modifier-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">Include</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"modifier-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">Exclude</a></li>\n </ul>\n </div>\n </div>\n <div class=\"form-group\">\n <div class=\"dropdown\">\n <button style=\"width: 147px;\" class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\"dropdownMenu1\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedCriteria\">descendantOf</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\"dropdownMenu1\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOf</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">descendantOrSelfOf</a></li>\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">ancestorOf</a></li>-->\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">ancestorOrSelfOf</a></li>-->\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">self</a></li>\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">childrenOf</a></li>-->\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">parentsOf</a></li>-->\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">isMemberOf</a></li>\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">hasDescription</a></li>-->\n <!--<li role=\"presentation\"><a role=\"menuitem\" data-role=\"criteria-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">hasRelationship</a></li>-->\n </ul>\n </div>\n </div>\n <div class=\"form-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-conceptField\">\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedConcept\" placeholder=\"Drag a concept here\" readonly>\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedType\" placeholder=\"Drag a type here\" readonly>\n <input type=\"text\" data-droppable=\"true\" ondrop=\"dropField(event)\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedTarget\" placeholder=\"Drag a destination here\" readonly>\n <input type=\"text\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchTerm\" placeholder=\"Type search string\">\n <span class=\"dropdown\">\n <button class=\"btn btn-default dropdown-toggle\" type=\"button\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-formdropdown\" data-toggle=\"dropdown\" aria-expanded=\"true\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-selectedForm\">stated</span>\n <span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-formdropdown\">\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"form-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">stated</a></li>\n <li role=\"presentation\"><a role=\"menuitem\" data-role=\"form-selector\" tabindex=\"-1\" href=\"javascript:void(0);\">inferred</a></li>\n </ul>\n </span>\n </div>\n <div style=\"margin-left: 41px;\" class=\"form-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addCriteriaAnd\">\n <div class=\"dropdown\">\n <button style=\"text-decoration: none;\" class=\"btn btn-link dropdown-toggle\" type=\"button\" data-toggle=\"dropdown\" aria-expanded=\"true\"><span data-toggle=\"tooltip\" data-placement=\"top\" title=\"More\" class=\"glyphicon glyphicon-plus\"></span></button>\n <ul class=\"dropdown-menu pull-right\" role=\"menu\">\n <li role=\"presentation\"><a class=\"addCriteria\" data-type=\"Conjunction\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">Add AND</a></li>\n <li role=\"presentation\"><a class=\"addCriteria\" data-type=\"Refinement\" role=\"menuitem\" tabindex=\"-1\" href=\"javascript:void(0);\">Add Refinement</a></li>\n </ul>\n </div>\n </div>\n </form>\n <form class=\"form-inline\" role=\"form\">\n <div class=\"form-group\">\n <button type=\"button\" class=\"btn btn-primary\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addCriteriaButton' style=\"margin: 10px;\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_add_condition", "Add instruction", options) : helperMissing.call(depth0, "i18n", "i18n_add_condition", "Add instruction", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <!--<button type=\"button\" class=\"btn btn-primary\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-cloudResults' style=\"margin: 10px; position: relative;\" title=\"Open Cloud Queries Processor\" data-toggle=\"modal\" data-target=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-cloudModal\"><i class='glyphicon glyphicon-cloud' style=\"position: relative; top: 3px;\"></i> <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-cloudCount\"></span></button>-->\n\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addmsg\" for=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-addCriteriaButton\" class=\"small text-danger\"></span>\n </div>\n </form>\n <ul class=\"list-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-listGroup\">\n </ul>\n <div class=\"btn btn-success\" style=\"margin: 10px;\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-computeInferredButton'>"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_run_query", "Execute", options) : helperMissing.call(depth0, "i18n", "i18n_run_query", "Execute", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n <button type=\"button\" class=\"btn btn-primary pull-right\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-open-grammar' style=\"margin: 10px; position: relative;\" data-toggle=\"modal\" data-target=\"#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammarModal\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_constraint_grammar", "Constraint Grammar", options) : helperMissing.call(depth0, "i18n", "i18n_constraint_grammar", "Constraint Grammar", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</button>\n <br>\n <br>\n </div>\n </div>\n <div class=\"tab-pane active\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExpTab\" style=\"padding: 15px;margin: 0;\">\n <textarea rows=\"5\" class=\"form-control\" placeholder=\"Expression...\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExpText\"></textarea>\n <div class=\"btn btn-success\" style=\"margin: 10px;\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-computeInferredButton2'>"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_run_query", "Execute", options) : helperMissing.call(depth0, "i18n", "i18n_run_query", "Execute", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</div>\n <div class=\"btn btn-success\" style=\"display: none; margin: 10px;\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-computeOntoserver2'>Run on Ontoserver</div>\n <br>\n </div>\n </form>\n <!-- <ul class=\"list-group\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-listGroup\">\n </ul>\n "; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_results", "Results", options) : helperMissing.call(depth0, "i18n", "i18n_results", "Results", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ": <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultInfo\" class=\"text-muted small\"></span>\n-->\n <div class=\"row container-fluid\" style=\"margin: 10px;\">\n <p class=\"lead\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_results", "Results", options) : helperMissing.call(depth0, "i18n", "i18n_results", "Results", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += ": <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultInfo\"></p></span>\n </div>\n\n <div class=\"row container-fluid\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-output\" style=\"margin: 10px;\">\n <table class=\"table table-bordered\">\n <thead>\n <tr>\n <th>Concept</th>\n <th>Id</th>\n </tr>\n </thead>\n <tbody id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-outputBody\"></tbody>\n <tfoot>\n <tr>\n <td colspan=\"2\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-footer\" class=\"text-center text-muted small\"></td>\n </tr>\n </tfoot>\n </table>\n <table id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-output2\" style=\"display: none\">\n <thead>\n <tr>\n <th>Concept</th>\n <th>Id</th>\n </tr>\n </thead>\n <tbody id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-outputBody2\">\n </tbody>\n </table>\n\n </div>\n </div>\n <br><br><br><br><br><br><br><br><br><br><br><br><br><br>\n </div>\n </div>\n <!-- Modals -->\n <div class=\"modal fade\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExamplesModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-myCloudModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg\" style=\"width: 80%;\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n <h4 class=\"modal-title\">Terminology content selections examples</h4>\n </div>\n <div class=\"modal-body\" style=\"max-height: 450px; overflow: auto;\">\n <div class=\"row\">\n <div class=\"col-md-4\">\n <div class=\"list-group navbar\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-sidebar\">\n <ul id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mynav\" data-spy=\"affix\" data-offset-top=\"280\" class=\"nav\" style=\"position: fixed; width: 30%;\">\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.examples), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n </div>\n </div>\n <div class=\"col-md-8\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mycontentExamples\">\n\n </div>\n </div>\n </div>\n <div class=\"modal-footer\">\n <button id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ExamplesModal-close\" type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"modal fade\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-queryHelpModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-myCloudModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n <h4 class=\"modal-title\">Terminology content selections help</h4>\n </div>\n <div class=\"modal-body\" style=\"max-height: 450px; overflow: auto;\">\n <h2>SNOMED CT Expression Constraint Language</h2>\n <p>This tool implements the full set of ECL v1.3 functions from the \"SNOMED CT Expression Constraint Language Specification and Guide\" (<a href=\"http://snomed.org/expressionconstraint\" target=\"_blank\">http://snomed.org/expressionconstraint)</a>. </p>\n <p>The goal of this tool is to enable the creation of a terminology constraint for the selection of content in SNOMED CT, with a user friendly UI designed to support the most common real world use cases for content selection, like the creation\n of reference sets to support implementation.</p>\n <p class=\"lead\">Reference</p>\n <table class=\"c0\">\n <tbody>\n <tr class=\"c15\">\n <td class=\"c18 c24\" colspan=\"2\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">ECL Operator</span></p>\n </td>\n <td class=\"c13 c18\" colspan=\"1\" rowspan=\"2\">\n <p class=\"c3\"><span class=\"c2\">Summary</span></p>\n </td>\n <td class=\"c6 c18\" colspan=\"1\" rowspan=\"2\">\n <p class=\"c3\"><span class=\"c2\">Example</span></p>\n </td>\n </tr>\n <tr class=\"c15\">\n <td class=\"c7\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">Symbol</span></p>\n </td>\n <td class=\"c10\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">Name</span></p>\n </td>\n </tr>\n <tr class=\"c16\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&lt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Descendant of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all subtypes of the given concept</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 404684003 |Clinical finding|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&lt;&lt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Descendant or self of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all subtypes of the given concept plus the concept itself</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c23\">&lt;&lt; </span><span class=\"c20\">73211009 |Diabetes mellitus|</span></p>\n </td>\n </tr>\n <tr class=\"c16\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&gt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Ancestor of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all supertypes of the given concept</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&gt; 40541001 |Acute pulmonary edema|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&gt;&gt; </span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Ancestor or self of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all supertypes of the given concept plus the concept itself</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&gt;&gt; 40541001 |Acute pulmonary edema|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">&lt;!</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Child of</span></p> \n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of all children of the given concept</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">! 195967001 |Asthma|</span></p>\n </td>\n </tr>\n <tr class=\"c1\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">^</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Member of</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">The set of referenced components in the given reference set</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">^ 733990004 |Nursing activities reference set|</span></p>\n </td>\n </tr>\n <tr class=\"c16\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">*</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Any</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Any concept in the given SNOMED CT edition</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">*</span></p>\n </td>\n </tr>\n <tr class=\"c21\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">:</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Refinement</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Only those concepts whose defining relationships match the given attribute value pairs</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 404684003 |clinical finding|: 116676008 |associated morphology| = *</span></p>\n </td>\n </tr>\n <tr class=\"c19\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">AND</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Conjunction</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Only those concepts in both sets</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 19829001 |disorder of lung| AND &lt; 301867009 |edema of trunk|</span></p>\n </td>\n </tr>\n <tr class=\"c19\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">OR</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Disjunction</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Any concept that belongs to either set</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 19829001 |disorder of lung| OR &lt; 301867009 |edema of trunk|</span></p>\n </td>\n </tr>\n <tr class=\"c19\">\n <td class=\"c8\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c2\">MINUS</span></p>\n </td>\n <td class=\"c11\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Exclusion</span></p>\n </td>\n <td class=\"c13\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c5\">Concepts in the first set that do not belong to the second set</span></p>\n </td>\n <td class=\"c6\" colspan=\"1\" rowspan=\"1\">\n <p class=\"c3\"><span class=\"c9\">&lt; 19829001 |disorder of lung| MINUS &lt; 301867009 |edema of trunk|</span></p>\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n\n\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n\n <div class=\"modal fade\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammarModal\" tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"constraintGrammarModalLabel\" aria-hidden=\"true\">\n <div class=\"modal-dialog modal-lg\" style=\"max-height: 450px;\">\n <div class=\"modal-content\">\n <div class=\"modal-header\">\n <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"><span aria-hidden=\"true\">&times;</span></button>\n <h4 class=\"modal-title\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammarModalLabel\">"; stack1 = (helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_constraint_grammar", "Constraint Grammar", options) : helperMissing.call(depth0, "i18n", "i18n_constraint_grammar", "Constraint Grammar", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "</h4>\n </div>\n <div class=\"modal-body\" style=\"max-height: 450px; overflow: auto;\">\n <div class=\"row\">\n <div class=\"expression-code col-md-11\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-constraintGrammar\">\n\n </div>\n <div class=\"col-md-1\">\n <small><i class=\"glyphicon glyphicon-export pull-right\" style=\"font-size: 14px;cursor: pointer;\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-copyConstraint\"></i></small>\n </div>\n </div>\n </div>\n <div class=\"modal-footer\">\n <div class=\"btn-group pull-left\" role=\"group\" aria-label=\"...\">\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-full-syntax-button\">Full</button>\n <button type=\"button\" class=\"btn btn-default\" id=\"home-"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-brief-syntax-button\">Brief</button>\n </div>\n &nbsp;&nbsp;\n <button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>\n </div>\n </div>\n </div>\n </div>\n"; return buffer; }); this["JST"]["views/developmentQueryPlugin/relsCriteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<li data-modifier=\""; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-criteria=\""; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-type-id=\""; if (helper = helpers.typeId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-type-term=\""; if (helper = helpers.typeTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-target-term=\""; if (helper = helpers.targetTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.targetTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-target-id=\""; if (helper = helpers.targetId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.targetId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-form=\""; if (helper = helpers.form) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.form); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"list-group-item clearfix query-condition\">\n <span class=\"text-muted line-number\" style=\"font-size: 200%;\"></span>&nbsp;&nbsp;\n <span style=\"position: relative; top: -5px;\">\n "; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ", "; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;\n <span style=\"color: forestgreen;\">"; if (helper = helpers.typeId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.typeId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>&nbsp;\n |\n <span style=\"color: firebrick;\">" + escapeExpression((helper = helpers.isEmptyString || (depth0 && depth0.isEmptyString),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.typeTerm), "Any", options) : helperMissing.call(depth0, "isEmptyString", (depth0 && depth0.typeTerm), "Any", options))) + "</span>\n |\n &nbsp;->&nbsp;\n <span style=\"color: forestgreen;\">"; if (helper = helpers.targetId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.targetId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>&nbsp;\n |\n <span style=\"color: firebrick;\">" + escapeExpression((helper = helpers.isEmptyString || (depth0 && depth0.isEmptyString),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.targetTerm), "Any", options) : helperMissing.call(depth0, "isEmptyString", (depth0 && depth0.targetTerm), "Any", options))) + "</span>\n |&nbsp;&nbsp;"; if (helper = helpers.form) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.form); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </span>\n <button class='pull-right btn btn-link removeLi' style=\"position: relative; top: 3px;\">\n <i class='glyphicon glyphicon-remove'></i>\n </button>\n </li>"; return buffer; }); this["JST"]["views/developmentQueryPlugin/searchCriteria.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<li data-modifier=\""; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-criteria=\""; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-search-term=\""; if (helper = helpers.searchTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.searchTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"list-group-item clearfix query-condition\">\n <span class=\"text-muted line-number\" style=\"font-size: 200%;\"></span>&nbsp;&nbsp;\n <span style=\"position: relative; top: -5px;\">\n "; if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ", "; if (helper = helpers.criteria) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.criteria); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "&nbsp;\n <span style=\"color: firebrick;\">"; if (helper = helpers.searchTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.searchTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </span>\n <button class='pull-right btn btn-link removeLi' style=\"position: relative; top: 3px;\">\n <i class='glyphicon glyphicon-remove'></i>\n </button>\n</li>"; return buffer; }); this["JST"]["views/favorites/body.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <tr>\n <td>"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n </tr>\n "; return buffer; } function program3(depth0,data) { return "\n <tr>\n <td>\n <span class=\"text-muted\"> No favorites</span>\n </td>\n </tr>\n "; } function program5(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.concepts), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>\n <a class=\"fav-item\" href=\"javascript:void(0);\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style=\"color: inherit; text-decoration: inherit;\">\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </a>\n </td>\n <td>"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n <a href=\"javascript:void(0);\" style=\"text-decoration: inherit;\">\n <span data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class=\"pull-right glyphicon glyphicon-remove-circle\"></span>\n </a>\n </td>\n </tr>\n "; return buffer; } function program7(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } buffer += "<div style=\"margin-top: 10px\" class=\"panel panel-default\">\n <div class=\"panel-body\">\n <table id=\"tableFavs\" style=\"display: none;\">\n <thead>\n <tr>\n <td>Term</td>\n <td>Concept ID</td>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.concepts), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n <table id=\"\" class=\"table table-hover table-bordered\">\n <tbody>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.concepts)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.concepts)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n</div>\n"; return buffer; }); this["JST"]["views/favorites/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_favorites'>Favorites</span></strong></div>\n <!--<div class='col-md-6 text-right'>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resetButton' class='btn btn-link' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-repeat'></i></button>-->\n <!--&lt;!&ndash;<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>&ndash;&gt;-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>-->\n <!--</div>-->\n </div>\n </div>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n </div>\n</div>\n<!--<div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>-->\n <!--<div class='modal-dialog'>-->\n <!--<div class='modal-content'>-->\n <!--<div class='modal-header'>-->\n <!--<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>-->\n <!--<h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>-->\n <!--</div>-->\n <!--<div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>-->\n <!--<p></p>-->\n <!--</div>-->\n <!--<div class='modal-footer'>-->\n <!--<button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>-->\n <!--</div>-->\n <!--</div>-->\n <!--</div>-->\n<!--</div>-->"; return buffer; }); this["JST"]["views/refsetPlugin/body.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { return "\n <tr>\n <td colspan=\"3\">\n <span class=\"text-muted\"> No refsets</span>\n </td>\n </tr>\n "; } function program3(depth0,data) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.refsets), {hash:{},inverse:self.noop,fn:self.programWithDepth(4, program4, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program4(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr>\n <td>"; if (helper = helpers.type) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.type); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <a class=\"refset-item\" href=\"javascript:void(0);\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style=\"color: inherit; text-decoration: inherit;\">\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(5, program5, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </a>\n </td>\n <td>\n "; if (helper = helpers.count) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.count); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n "; return buffer; } function program5(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } buffer += "<div style=\"margin-top: 10px\" class=\"panel panel-default\">\n <div class=\"panel-body\">\n <div class=\"row container-fluid\" style=\"max-height: 260px; overflow-y: scroll; margin: 10px;\">\n <table class=\"table table-hover table-bordered\">\n <thead>\n <tr>\n <th>Type</th>\n <th>Refset</th>\n <th>Members count</th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.refsets)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.refsets)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n <div class=\"row container-fluid\">\n <table id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable\" class=\"table table-hover table-bordered\">\n\n </table>\n </div>\n </div>\n</div>"; return buffer; }); this["JST"]["views/refsetPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_refsets'>Refsets</span></strong></div>\n </div>\n </div>\n <div ondrop=\"dropF(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n </div>\n</div>"; return buffer; }); this["JST"]["views/refsetPlugin/members.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <thead>\n <tr>\n <th colspan=\"2\">Members of "; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " (<span>" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>)</th>\n </tr>\n <tr>\n <th><span data-i18n-id=\"i18n_term\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_term", "Term", options) : helperMissing.call(depth0, "i18n", "i18n_term", "Term", options))) + "</span></th>\n <th><span data-i18n-id=\"i18n_conceptId\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_conceptId", "Concept Id", options) : helperMissing.call(depth0, "i18n", "i18n_conceptId", "Concept Id", options))) + "</span></th>\n </tr>\n </thead>\n"; return buffer; } function program3(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class=\"member-concept-row\">\n <td>\n <span class=\"badge alert-warning\" draggable='true' ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>&nbsp;&nbsp;</span>\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n <td>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.referencedComponent)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</td>\n </tr>\n "; return buffer; } function program4(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:22px;height:22px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program6(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span></button>\n </td>\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(11, program11, data),fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program9(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <td class=\"text-muted\" class=\"text-center\" colspan=\"2\">"; if (helper = helpers.total) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.total); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_members\" class=\"i18n\">members</span></td>\n "; return buffer; } function program11(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.remaining), (depth0 && depth0.returnLimit), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program12(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <td class=\"text-center\" colspan=\"2\">\n <button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moreMembers'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining", "remaining", options) : helperMissing.call(depth0, "i18n", "i18n_remaining", "remaining", options))) + "</span>)</button>\n </td>\n "; return buffer; } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.skipTo), 0, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.skipTo), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n<tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.items), {hash:{},inverse:self.noop,fn:self.programWithDepth(3, program3, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n <tr class=\"more-row\">\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), "asd", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.remaining), "asd", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tr>\n</tbody>"; return buffer; }); this["JST"]["views/searchPlugin/aux.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing; buffer += "<div style='margin: 5px; height:95%;' class='panel panel-default'>\n <div class='panel-heading'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 15px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-8' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_search'>Search</span></span></strong></div>\n <div class='col-md-4 text-right'>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div class='panel-body' style='height:86%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <div style=\"display: inline;width: 34%;height: 100%; float: left; border: 1px solid lightgray; border-radius: 4px; padding: 5px; \">\n <h4><span>Options</span></h4>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchConfigBar' style='margin-bottom: 10px;'>\n <div style=\"margin-top: 5px\" class=\"btn-group\">\n <button style=\"white-space: normal;\" type=\"button\" class=\"btn btn-success dropdown-toggle\" data-toggle=\"dropdown\">\n <span class='i18n' data-i18n-id='i18n_status'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_status", "Status", options) : helperMissing.call(depth0, "i18n", "i18n_status", "Status", options))) + "</span>: <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchStatus\"></span>&nbsp;<span class=\"caret\"></span>\n </button>\n <ul class=\"dropdown-menu\" role=\"menu\">\n <li>\n <a href=\"#\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeOnlyButton' data-i18n-id='i18n_active_only'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_active_only", "Active components only", options) : helperMissing.call(depth0, "i18n", "i18n_active_only", "Active components only", options))) + "</a>\n </li>\n <li>\n <a href=\"#\" id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeInactiveButton' data-i18n-id='i18n_active_and_inactive'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_active_and_inactive", "Active and inactive components", options) : helperMissing.call(depth0, "i18n", "i18n_active_and_inactive", "Active and inactive components", options))) + "</a>\n </li>\n <li>\n <a href=\"#\"id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inactiveOnlyButton' data-i18n-id='i18n_inactive_only'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_inactive_only", "Inactive components only", options) : helperMissing.call(depth0, "i18n", "i18n_inactive_only", "Inactive components only", options))) + "</a>\n </li>\n </ul>\n </div>\n <div style=\"margin-top: 5px; \" class=\"checkbox\">\n <label>\n <input id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-groupConcept\" type=\"checkbox\"><span class='i18n' data-i18n-id='i18n_group_by_concept'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group_by_concept", "Group by concept", options) : helperMissing.call(depth0, "i18n", "i18n_group_by_concept", "Group by concept", options))) + "</span>\n </label>\n </div>\n </div>\n </div>\n <div style=\"display: inline; width: 66%; float: right; padding: 5px;\">\n <form>\n <div class=\"form-group\" style=\"margin-bottom: 2px;\">\n <label for=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\">\n <span class=\"i18n\" data-i18n-id=\"i18n_type_3_chars\">Type at least 3 characters</span> <i class=\"glyphicon glyphicon-remove text-danger\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-typeIcon\"></i> <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchExample\"></span></label>\n <br><div class=\"btn-group\" style=\"width: 100%;\"><input data-droppable=\"true\" ondrop=\"dropS(event);\" ondragover=\"removeHighlight();\" ondragstart=\"allowDrop(event);\" type=\"search\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\" placeholder=\"Search...\" autocomplete=\"off\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-clearButton\" class=\"searchclear glyphicon glyphicon-remove-circle\"></span></div>\n </div>\n </form>\n <div class='panel panel-default' style='height:70%;overflow:auto;margin-bottom: 15px;min-height: 300px;' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsScrollPane'>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBar\"></div>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFilters\"></div>\n <table class='table table-bordered'>\n <tbody id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable'>\n </tbody>\n </table>\n </div>\n <div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>\n"; return buffer; }); this["JST"]["views/searchPlugin/body/0.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data,depth1) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='resultRow selectable-row "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.danger), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td class='col-md-7'>\n <div class='result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(6, program6, data, depth1),fn:self.programWithDepth(4, program4, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href='javascript:void(0);' style='color: inherit;text-decoration: inherit;' draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a>\n </div>\n </td>\n <td class='text-muted small-text col-md-5 result-item' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n " + escapeExpression(((stack1 = ((stack1 = (depth1 && depth1.result)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\n </td>\n </tr>\n"; return buffer; } function program2(depth0,data) { return "danger"; } function program4(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program6(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:20px;height:20px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program10(depth0,data) { var buffer = "", helper, options; buffer += "\n <tr><td class='text-muted'><span data-i18n-id=\"i18n_no_results\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_results", "No results", options) : helperMissing.call(depth0, "i18n", "i18n_no_results", "No results", options))) + "</span></td></tr>\n"; return buffer; } stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.descriptions), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.descriptions)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.descriptions)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/body/1.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data,depth1) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, self=this, helperMissing=helpers.helperMissing, functionType="function", escapeExpression=this.escapeExpression; function program1(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='resultRow selectable-row"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.active), false, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.active), false, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td class='col-md-7'>\n <div class='result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(8, program8, data, depth0),fn:self.programWithDepth(6, program6, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(13, program13, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href='javascript:void(0);' style='color: inherit;text-decoration: inherit;' draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a>\n </div>\n </td>\n <td class='text-muted small-text col-md-5 result-item' data-module=\""; if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; if (helper = helpers.fsn) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.fsn); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n"; return buffer; } function program2(depth0,data) { return "danger"; } function program4(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.concept)),stack1 == null || stack1 === false ? stack1 : stack1.active), false, options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.concept)),stack1 == null || stack1 === false ? stack1 : stack1.active), false, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program6(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(11, program11, data, depth1),fn:self.programWithDepth(9, program9, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "900000000000074008", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "900000000000074008", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program9(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program11(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program13(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:20px;height:20px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/body/bar.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class='text-muted'>" + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " matches found in "; if (helper = helpers.elapsed) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.elapsed); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " seconds.</span>\n"; return buffer; } function program3(depth0,data) { return "-->\n<!--"; } function program5(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--&nbsp;&nbsp;<span class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-semtag'>&times;</a></span>&nbsp;&nbsp;-->\n<!--"; return buffer; } function program7(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--&nbsp;&nbsp;<span class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-lang'>&times;</a></span>&nbsp;&nbsp;-->\n<!--"; return buffer; } function program9(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--&nbsp;&nbsp;<span class='label label-danger'>"; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), {hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " &nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-module'>&times;</a></span>&nbsp;&nbsp;-->\n<!--"; return buffer; } function program10(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program12(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program14(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--<li><a class='lang-link' href='javascript:void(0);' data-lang='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " (" + escapeExpression((typeof depth0 === functionType ? depth0.apply(depth0) : depth0)) + ")</a></li>-->\n <!--"; return buffer; } function program16(depth0,data) { var buffer = "", stack1; buffer += "-->\n <!--<li><a class='semtag-link' href='javascript:void(0);' data-semtag='" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'>" + escapeExpression(((stack1 = (data == null || data === false ? data : data.key)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " (" + escapeExpression((typeof depth0 === functionType ? depth0.apply(depth0) : depth0)) + ")</a></li>-->\n <!--"; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper, options; buffer += "-->\n <!--<li><a class='module-link' href='javascript:void(0);' data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-module='"; if (helper = helpers.value) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.value); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; stack1 = helpers['if'].call(depth0, (depth0 && depth0.term), {hash:{},inverse:self.program(21, program21, data),fn:self.program(19, program19, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " ("; if (helper = helpers.cant) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.cant); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")-->\n <!--"; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(23, program23, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.value), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.value), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</a></li>-->\n <!--"; return buffer; } function program19(depth0,data) { var stack1, helper; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } return escapeExpression(stack1); } function program21(depth0,data) { var stack1, helper; if (helper = helpers.value) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.value); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } return escapeExpression(stack1); } function program23(depth0,data) { var buffer = "", helper, options; buffer += "-->\n <!--<div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">-->\n <!--<span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.value), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.value), options))) + "\"></span>-->\n <!--</div>-->\n <!--"; return buffer; } stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details), {hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n<!--<span class='pull right'>-->\n<!--<a class='btm btn-xs' style='margin: 3px; color: #777; background-color: #fff; border: 1px #ccc solid; margin-left: 25px;' data-toggle='collapse' href='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFiltersPanel'>-->\n <!--<span class='i18n' data-i18n-id='i18n_filters'>" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters", "Filters", options) : helperMissing.call(depth0, "i18n", "i18n_filters", "Filters", options))) + "</span>-->\n<!--</a>-->\n<!--"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n<!--"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(7, program7, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n<!--"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n<!--</span>-->\n<!--<div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFiltersPanel' class='panel-collapse collapse'>-->\n <!--<div class='tree'>-->\n <!--<ul>-->\n <!--<li><a><span data-i18n-id=\"i18n_filters_language\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters_language", "Filter results by Language", options) : helperMissing.call(depth0, "i18n", "i18n_filters_language", "Filter results by Language", options))) + "</span></a>-->\n <!--<ul>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.filters)),stack1 == null || stack1 === false ? stack1 : stack1.lang), {hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</ul>-->\n <!--</li>-->\n <!--</ul>-->\n <!--<ul>-->\n <!--<li><a><span data-i18n-id=\"i18n_filters_semtag\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters_semtag", "Filter results by Semantic Tag", options) : helperMissing.call(depth0, "i18n", "i18n_filters_semtag", "Filter results by Semantic Tag", options))) + "</span></a>-->\n <!--<ul>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.filters)),stack1 == null || stack1 === false ? stack1 : stack1.semTag), {hash:{},inverse:self.noop,fn:self.program(16, program16, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</ul>-->\n <!--</li>-->\n <!--</ul>-->\n <!--<ul>-->\n <!--<li><a><span data-i18n-id=\"i18n_filters_module\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_filters_module", "Filter results by Module", options) : helperMissing.call(depth0, "i18n", "i18n_filters_module", "Filter results by Module", options))) + "</span></a>-->\n <!--<ul>-->\n <!--"; stack1 = helpers.each.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.filters)),stack1 == null || stack1 === false ? stack1 : stack1.module), {hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "-->\n <!--</ul>-->\n <!--</li>-->\n <!--</ul>-->\n <!--</div>-->\n<!--</div>-->"; return buffer; }); this["JST"]["views/searchPlugin/body/bar2.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data) { return "\n"; } function program3(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-moduleResumed\" style=\"font-size: 12px;white-space: normal\" class='label label-danger' data-name=\""; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), {hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">"; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), {hash:{},inverse:self.program(10, program10, data),fn:self.program(8, program8, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " &nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-module'>&times;</a></span>\n </h3>\n"; return buffer; } function program4(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program6(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program8(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilterName), options))); } function program10(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), options))); } function program12(depth0,data) { var buffer = "", stack1; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span style=\"font-size: 12px; margin-top: 5px;\" class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-lang'>&times;</a></span>\n </h3>\n"; return buffer; } function program14(depth0,data) { var buffer = "", stack1; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span style=\"font-size: 12px; margin-top: 5px;\" class='label label-danger'>" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "&nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-semtag'>&times;</a></span>\n </h3>\n"; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <h3 style=\"margin-top: 5px;\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-refsetResumed\" style=\"font-size: 12px; margin-top: 5px;\" class='label label-danger' data-name=\""; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), {hash:{},inverse:self.program(19, program19, data),fn:self.program(17, program17, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\">"; stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), {hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " &nbsp;<a href='javascript:void(0);' style='color: white;text-decoration: none;' class='remove-refset'>&times;</a></span>\n </h3>\n"; return buffer; } function program17(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program19(depth0,data) { var stack1; return escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)); } function program21(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilterName), options))); } function program23(depth0,data) { var stack1, helper, options; return escapeExpression((helper = helpers.first20chars || (depth0 && depth0.first20chars),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), options) : helperMissing.call(depth0, "first20chars", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), options))); } stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(3, program3, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.moduleFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.langFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(14, program14, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.semTagFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), "none", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.refsetFilter), "none", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(1, program1, data),fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total), 0, options) : helperMissing.call(depth0, "if_eq", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/body/default.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helperMissing=helpers.helperMissing, escapeExpression=this.escapeExpression, functionType="function", self=this; function program1(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_gre || (depth0 && depth0.if_gre),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, "0", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches)),stack1 == null || stack1 === false ? stack1 : stack1.length), options) : helperMissing.call(depth0, "if_gre", "0", ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches)),stack1 == null || stack1 === false ? stack1 : stack1.length), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program2(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-muted'><span data-i18n-id=\"i18n_no_results\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_results", "No results", options) : helperMissing.call(depth0, "i18n", "i18n_no_results", "No results", options))) + "</span></td></tr>\n "; stack1 = (helper = helpers.hasFilters || (depth0 && depth0.hasFilters),options={hash:{},inverse:self.noop,fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.options), options) : helperMissing.call(depth0, "hasFilters", (depth0 && depth0.options), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program3(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-center'><span data-i18n-id=\"i18n_remove_filters\" class=\"i18n\">\n " + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options) : helperMissing.call(depth0, "i18n", "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options))) + "</span><br>\n <button class=\"btn btn-danger btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-remove-all-filters\"><span data-i18n-id=\"i18n_remove_filters_button\" class=\"i18n\">Remove all filters</span></button>\n </td></tr> "; return buffer; } function program5(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.program(22, program22, data),fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.remaining), 0, options) : helperMissing.call(depth0, "if_gr", (depth0 && depth0.remaining), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program6(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='resultRow selectable-row"; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(9, program9, data),fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.active), false, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.active), false, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "'>\n <td class='col-md-6'>\n <div class='result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(13, program13, data, depth0),fn:self.programWithDepth(11, program11, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href='javascript:void(0);' style='color: inherit;text-decoration: inherit;' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</a>\n </div>\n </td>\n <td class='text-muted small-text col-md-6 result-item' data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'>"; if (helper = helpers.fsn) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.fsn); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\n </td>\n </tr>\n "; return buffer; } function program7(depth0,data) { return " danger"; } function program9(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(7, program7, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptActive), false, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.conceptActive), false, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program11(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program13(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(16, program16, data, depth1),fn:self.programWithDepth(14, program14, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "900000000000074008", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "900000000000074008", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program14(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program16(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.term) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.term); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:20px;height:20px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program20(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='more-row'><td colspan='2' class='text-center'><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-more'><span data-i18n-id=\"i18n_load\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_load", "Load", options) : helperMissing.call(depth0, "i18n", "i18n_load", "Load", options))) + "</span> "; if (helper = helpers.returnLimit) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.returnLimit); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_more\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_more", "more", options) : helperMissing.call(depth0, "i18n", "i18n_more", "more", options))) + "</span> ("; if (helper = helpers.remaining) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.remaining); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " <span data-i18n-id=\"i18n_remaining_server\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remaining_server", "remaining on server", options) : helperMissing.call(depth0, "i18n", "i18n_remaining_server", "remaining on server", options))) + "</span>)</button></td></tr>\n "; return buffer; } function program22(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr class='more-row'><td colspan='2' class='text-center text-muted'><span data-i18n-id=\"i18n_all_res\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_all_res", "All", options) : helperMissing.call(depth0, "i18n", "i18n_all_res", "All", options))) + "</span> " + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.details)),stack1 == null || stack1 === false ? stack1 : stack1.total)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + " <span data-i18n-id=\"i18n_results_displayed\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_results_displayed", "results are displayed", options) : helperMissing.call(depth0, "i18n", "i18n_results_displayed", "results are displayed", options))) + "</span></td></tr>\n "; return buffer; } function program24(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-muted'><span data-i18n-id=\"i18n_no_results\" class=\"i18n\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_no_results", "No results", options) : helperMissing.call(depth0, "i18n", "i18n_no_results", "No results", options))) + "</span></td></tr>\n "; stack1 = (helper = helpers.hasFilters || (depth0 && depth0.hasFilters),options={hash:{},inverse:self.noop,fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.options), options) : helperMissing.call(depth0, "hasFilters", (depth0 && depth0.options), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; } function program25(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <tr><td class='text-center'><span data-i18n-id=\"i18n_remove_filters\" class=\"i18n\">\n " + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options) : helperMissing.call(depth0, "i18n", "i18n_remove_filters", "There are filters active, remove them to search again with a broader criteria.", options))) + "</span><br>\n <button class=\"btn btn-danger btn-sm\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-remove-all-filters\"><span data-i18n-id=\"i18n_remove_filters_button\" class=\"i18n\">Remove all filters</span></button>\n </td></tr>\n "; return buffer; } stack1 = helpers['if'].call(depth0, ((stack1 = (depth0 && depth0.result)),stack1 == null || stack1 === false ? stack1 : stack1.matches), {hash:{},inverse:self.program(24, program24, data),fn:self.program(1, program1, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n"; return buffer; }); this["JST"]["views/searchPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='margin: 5px; height:95%;' class='panel panel-default'>\n <div class='panel-heading'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 15px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-8' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_search'>Search</span></span></strong></div>\n <div class='col-md-4 text-right'>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div class='panel-body' style='height:86%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n <form>\n <div class=\"form-group\" style=\"margin-bottom: 2px;\">\n <label for=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\">\n <span class=\"i18n\" data-i18n-id=\"i18n_type_3_chars\">Type at least 3 characters</span> <i class=\"glyphicon glyphicon-remove text-danger\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-typeIcon\"></i> <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchExample\"></span></label>\n <br><div class=\"btn-group\" style=\"width: 100%;\"><input data-droppable=\"true\" ondrop=\"dropS(event);\" ondragover=\"removeHighlight();\" ondragstart=\"allowDrop(event);\" type=\"search\" class=\"form-control\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBox\" placeholder=\"Search...\" autocomplete=\"off\">\n <span id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-clearButton\" class=\"searchclear glyphicon glyphicon-remove-circle\"></span></div>\n </div>\n </form>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchConfigBar' style='margin-bottom: 10px;'><nav class='navbar navbar-default' role='navigation' style='min-height: 28px;border-radius: 0px;border-bottom: 1px lightgray solid;'>\n <ul class='nav navbar-nav navbar-left'>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-navSearchModeLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-fullTextButton'><span class='i18n' data-i18n-id='i18n_full_text_search_mode'>Full text search mode</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-partialMatchingButton'><span class='i18n' data-i18n-id='i18n_partial_match_search_mode'>Partial matching search mode</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-regexButton'><span class='i18n' data-i18n-id='i18n_regex_search_mode'>Regular Expressions search mode</span></button></li>\n </ul>\n </li>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-navLanguageLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-danishLangButton'><span class='i18n' data-i18n-id='i18n_danish_stemmer'>Danish language stemmer</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-englishLangButton'><span class='i18n' data-i18n-id='i18n_english_stemmer'>English language stemmer</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-spanishLangButton'><span class='i18n' data-i18n-id='i18n_spanish_stemmer'>Spanish language stemmer</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-swedishLangButton'><span class='i18n' data-i18n-id='i18n_swedish_stemmer'>Swedish language stemmer</span></button></li>\n </ul>\n </li>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-navStatusFilterLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeOnlyButton'><span class='i18n' data-i18n-id='i18n_active_only'>Active components only</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-activeInactiveButton'><span class='i18n' data-i18n-id='i18n_active_and_inactive'>Active and inactive components</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inactiveOnlyButton'><span class='i18n' data-i18n-id='i18n_inactive_only'>Inactive components only</span></button></li>\n </ul>\n </li>\n </ul>\n </nav></div>\n <div class='panel panel-default' style='height:70%;overflow:auto;margin-bottom: 15px;min-height: 300px;' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsScrollPane'>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchBar\"></div>\n <div id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-searchFilters\"></div>\n <table class='table table-bordered'>\n <tbody id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resultsTable'>\n </tbody>\n </table>\n </div>\n <div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>\n "; return buffer; }); this["JST"]["views/taxonomyPlugin/body/children.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, self=this, helperMissing=helpers.helperMissing, functionType="function", escapeExpression=this.escapeExpression; function program1(depth0,data,depth1) { var buffer = "", stack1; buffer += "\n "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(2, program2, data, depth0, depth1),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; return buffer; } function program2(depth0,data,depth1,depth2) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + " data-statedDescendants='"; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'>\n <i class='glyphicon glyphicon-"; stack1 = (helper = helpers.if_eq || (depth2 && depth2.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(3, program3, data),data:data},helper ? helper.call(depth0, (depth2 && depth2.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", (depth2 && depth2.selectedView), "inferred", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i>\n </button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.programWithDepth(12, program12, data, depth1),fn:self.programWithDepth(10, program10, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span class=\"treeLabel selectable-row\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-statedDescendants=\""; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" id=\"" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n " + escapeExpression((helper = helpers.push || (depth0 && depth0.push),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptId), options) : helperMissing.call(depth0, "push", (depth0 && depth0.conceptId), options))) + "\n </li>\n "; return buffer; } function program3(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafInferred), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafInferred), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program4(depth0,data) { return "minus"; } function program6(depth0,data) { return "chevron-right"; } function program8(depth0,data) { var stack1, helper, options; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(6, program6, data),fn:self.program(4, program4, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.isLeafStated), true, options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.isLeafStated), true, options)); if(stack1 || stack1 === 0) { return stack1; } else { return ''; } } function program10(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program12(depth0,data,depth2) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '" + escapeExpression(((stack1 = (depth2 && depth2.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "')\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program14(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:26px;height:26px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } buffer += "<ul style='list-style-type: none; padding-left: 15px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.result), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n</ul>\n"; return buffer; }); this["JST"]["views/taxonomyPlugin/body/parents.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, helperMissing=helpers.helperMissing, self=this; function program1(depth0,data,depth1) { var buffer = "", stack1, helper, options; buffer += "\n <li data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id='"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-term='"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' data-statedDescendants='"; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'>\n <i class='glyphicon glyphicon-chevron-"; stack1 = (helper = helpers.if_def || (depth0 && depth0.if_def),options={hash:{},inverse:self.program(4, program4, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.conceptId), options) : helperMissing.call(depth0, "if_def", (depth0 && depth0.conceptId), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += " treeButton' id='" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treeicon-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "'></i>\n </button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(8, program8, data),fn:self.program(6, program6, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "hasCountryIcon", (depth0 && depth0.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-statedDescendants=\""; if (helper = helpers.statedDescendants) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.statedDescendants); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" class=\"treeLabel selectable-row\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-treenode-"; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\">"; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</span>\n </a>\n "; return buffer; } function program2(depth0,data) { return "down"; } function program4(depth0,data) { return "up"; } function program6(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program8(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" data-module=\""; if (helper = helpers.module) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.module); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-concept-id=\""; if (helper = helpers.conceptId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.conceptId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" data-term=\""; if (helper = helpers.defaultTerm) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.defaultTerm); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program10(depth0,data) { var buffer = "", helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:33px;height:33px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, (depth0 && depth0.module), options) : helperMissing.call(depth0, "countryIcon", (depth0 && depth0.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program12(depth0,data) { var buffer = "", helper, options; buffer += "\n " + escapeExpression((helper = helpers.slice || (depth0 && depth0.slice),options={hash:{},data:data},helper ? helper.call(depth0, 0, -5, options) : helperMissing.call(depth0, "slice", 0, -5, options))) + "\n "; return buffer; } function program14(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&nbsp;&nbsp;</span>&nbsp;&nbsp;\n "; return buffer; } function program16(depth0,data) { var buffer = "", stack1, helper; buffer += "\n <span class=\"badge alert-warning\" draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">&equiv;</span>&nbsp;&nbsp;\n "; return buffer; } function program18(depth0,data) { var buffer = "", stack1, helper, options; buffer += "\n <div class=\"phoca-flagbox\" style=\"width:33px;height:33px\">\n <span class=\"phoca-flag " + escapeExpression((helper = helpers.countryIcon || (depth0 && depth0.countryIcon),options={hash:{},data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "countryIcon", ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options))) + "\"></span>\n </div>\n "; return buffer; } function program20(depth0,data) { return "\n </li>\n "; } buffer += "<div style='height:100%;margin-bottom: 15px;'>\n <ul style='list-style-type: none; padding-left: 5px;'>\n "; stack1 = helpers.each.call(depth0, (depth0 && depth0.parents), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.noop,fn:self.program(12, program12, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <ul style='list-style-type: none; padding-left: 15px;'>\n <li data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-term='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' data-statedDescendants='" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendants)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "' class='treeLabel'>\n <button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-chevron-right treeButton' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-treeicon-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "'></i></button>\n "; stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n "; stack1 = (helper = helpers.hasCountryIcon || (depth0 && depth0.hasCountryIcon),options={hash:{},inverse:self.noop,fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options) : helperMissing.call(depth0, "hasCountryIcon", ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module), options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\">\n <span data-module=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.module)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-concept-id=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-term=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" data-statedDescendants=\"" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.statedDescendants)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\" class=\"treeLabel selectable-row\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-treenode-" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "\">" + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.focusConcept)),stack1 == null || stack1 === false ? stack1 : stack1.defaultTerm)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "</span>\n </a>\n </li>\n </ul>\n "; stack1 = (helper = helpers.if_gr || (depth0 && depth0.if_gr),options={hash:{},inverse:self.noop,fn:self.program(20, program20, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options) : helperMissing.call(depth0, "if_gr", ((stack1 = (depth0 && depth0.parents)),stack1 == null || stack1 === false ? stack1 : stack1.length), 0, options)); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </ul>\n</div>"; return buffer; }); this["JST"]["views/taxonomyPlugin/main.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, functionType="function", escapeExpression=this.escapeExpression; buffer += "<div style='height:100%;margin: 5px; overflow:auto;' class='panel panel-default' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-mainPanel'>\n <div ondrop=\"dropT(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-heading' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelHeading'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-ownMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 0px;'><i class='glyphicon glyphicon-book'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-subscribersMarker' class='btn btn-link btn-lg' style='padding: 2px; position: absolute;top: 1px;left: 15px;'><i class='glyphicon glyphicon-bookmark'></i></button>\n <div class='row'>\n <div class='col-md-6' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelTitle'>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<strong><span class='i18n' data-i18n-id='i18n_taxonomy'>Taxonomy</span></strong></div>\n <div class='col-md-6 text-right'>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-historyButton' class='btn btn-link history-button' style='padding:2px'><i class='glyphicon glyphicon-time'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-resetButton' class='btn btn-link' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-repeat'></i></button>\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-linkerButton' draggable=\"true\" ondragstart=\"drag(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" class='btn btn-link linker-button' data-panel='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "' style='padding:2px'><i class='glyphicon glyphicon-link'></i></button>-->\n <!--<button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configButton' class='btn btn-link' data-toggle='modal' style='padding:2px' data-target='#"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'><i class='glyphicon glyphicon-cog'></i></button>-->\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-collapseButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-small'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-expandButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-resize-full'></i></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-closeButton' class='btn btn-link' style='padding:2px'><i class='glyphicon glyphicon-remove'></i></button>\n </div>\n </div>\n </div>\n <div id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-taxonomyConfigBar' style='margin-bottom: 10px;'><nav class='navbar navbar-default' role='navigation' style='min-height: 28px;border-radius: 0px;border-bottom: 1px lightgray solid;'>\n <ul class='nav navbar-nav navbar-left'>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-txViewLabel'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-inferredViewButton'><span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-statedViewButton'><span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span></button></li>\n </ul>\n </li>\n <li class='dropdown' style='margin-bottom: 2px; margin-top: 2px;'>\n <a href='javascript:void(0);' class='dropdown-toggle' data-toggle='dropdown' style='padding-top: 2px; padding-bottom: 2px;'><span id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-txViewLabel2'></span> <b class='caret'></b></a>\n <ul class='dropdown-menu' role='menu' style='float: none;'>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descendantsCountTrue'><span class='i18n' data-i18n-id='i18n_on'>On</span></button></li>\n <li><button class='btn btn-link' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-descendantsCountFalse'><span class='i18n' data-i18n-id='i18n_off'>Off</span></button></li>\n </ul>\n </li>\n </ul>\n </nav></div>\n <div ondrop=\"dropT(event, '"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "')\" ondragleave=\"removeHighlight();\" ondragover=\"allowDrop(event)\" class='panel-body' style='height:100%' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-panelBody'>\n </div>\n</div>\n<div class='modal fade' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-configModal'>\n <div class='modal-dialog'>\n <div class='modal-content'>\n <div class='modal-header'>\n <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>&times;</button>\n <h4 class='modal-title'><span class='i18n' data-i18n-id='i18n_options'>Options</span> ("; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + ")</h4>\n </div>\n <div class='modal-body' id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-modal-body'>\n <p></p>\n </div>\n <div class='modal-footer'>\n <button type='button' class='btn btn-danger' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_cancel'>Cancel</span></button>\n <button id='"; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-apply-button' type='button' class='btn btn-success' data-dismiss='modal'><span class='i18n' data-i18n-id='i18n_apply_changes'>Apply changes</span></button>\n </div>\n </div>\n </div>\n</div>"; return buffer; }); this["JST"]["views/taxonomyPlugin/options.hbs"] = Handlebars.template(function (Handlebars,depth0,helpers,partials,data) { this.compilerInfo = [4,'>= 1.0.0']; helpers = this.merge(helpers, Handlebars.helpers); data = data || {}; var buffer = "", stack1, helper, options, functionType="function", escapeExpression=this.escapeExpression, self=this, helperMissing=helpers.helperMissing; function program1(depth0,data,depth1) { var buffer = "", stack1, helper; buffer += "\n <tr>\n <td>"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "</td>\n <td>\n <div class=\"checkbox\">\n <label>\n <input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscribeTo-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscribed), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> <span class=\"i18n\"></span>\n </label>\n </div>\n </td>\n <td>\n <div class=\"checkbox\">\n <label>\n <input type=\"checkbox\" id=\"" + escapeExpression(((stack1 = (depth1 && depth1.divElementId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) + "-subscriptor-"; if (helper = helpers.id) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.id); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "\" "; stack1 = helpers['if'].call(depth0, (depth0 && depth0.subscriptor), {hash:{},inverse:self.noop,fn:self.program(2, program2, data),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "> <span class=\"i18n\"></span>\n </label>\n </div>\n </td>\n </tr>\n "; return buffer; } function program2(depth0,data) { return "checked"; } buffer += "<form role=\"form\" id=\""; if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } buffer += escapeExpression(stack1) + "-options-form\">\n <div class=\"form-group\">\n <table class='table table-bordered table-hover'>\n <thead>\n <tr>\n <th>Panel</th>\n <th><span class=\"i18n\" data-i18n-id=\"i18n_subscribed\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_subscribe", "Subscribed", options) : helperMissing.call(depth0, "i18n", "i18n_subscribe", "Subscribed", options))) + "</span></th>\n <th><span class=\"i18n\" data-i18n-id=\"i18n_subscriptor\">" + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_subscriptor", "Subscriptor", options) : helperMissing.call(depth0, "i18n", "i18n_subscriptor", "Subscriptor", options))) + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.possibleSubscribers), {hash:{},inverse:self.noop,fn:self.programWithDepth(1, program1, data, depth0),data:data}); if(stack1 || stack1 === 0) { buffer += stack1; } buffer += "\n </tbody>\n </table>\n </div>\n</form>"; return buffer; }); /** * Created by alo on 5/9/15. */ var e_openCurlyBraces = '<span class="exp-brackets">{</span>'; var e_closeCurlyBraces = '<span class="exp-brackets">}</span>'; var e_colon = '<span class="exp-operators">:</span>'; var e_plus = '<span class="exp-operators">+</span>'; var e_equals = '<span class="exp-operators">=</span>'; var e_pipe = '<span class="exp-pipes">|</span>'; var panel = {}; var referenceToExpression = function(conceptReference) { return conceptReference.conceptId + " " + e_pipe + "<span class='exp-term'>" + conceptReference.defaultTerm + "</span>" + e_pipe; }; var conceptToPostCoordinatedExpression = function(concept, relsProperty, div, options) { var expression = ""; var tab = "&nbsp;&nbsp;&nbsp;&nbsp;"; if (concept.definitionStatus == "Fully defined" || concept.definitionStatus == "Sufficiently defined") { expression += "<span class='exp-operators'>===</span> "; } else { expression += "<span class='exp-operators'>&lt;&lt;&lt;</span> "; } if (concept[relsProperty] && concept[relsProperty].length > 0) { //expression += ' <span class="exp-brackets">{</span>'; var firstParent = true; var attributes = {}; $.each(concept[relsProperty], function(i, rel){ if (rel.active == true && rel.type.conceptId == "116680003") { if (!firstParent) { expression += " " + e_plus + " <br>"; expression += tab + referenceToExpression(rel.target); } else { expression += referenceToExpression(rel.target); } firstParent = false; } else if (rel.active == true && rel.type.conceptId != "116680003") { if (!attributes[rel.groupId]) { attributes[rel.groupId] = []; } attributes[rel.groupId].push(rel); } }); //console.log(attributes); var groups = Object.keys(attributes); if (groups.length > 0) { expression += " " + e_colon; } $.each(groups, function(i, group){ expression += "<br>"; var firstInGroup = true; $.each(attributes[group], function(i, rel){ if (!firstInGroup) { expression += ", <br>"; } if (group > 0) { expression += tab + tab + tab; } else { expression += tab + tab; } if (firstInGroup && group > 0) { expression += e_openCurlyBraces + " "; } else if (group > 0){ expression += "&nbsp;&nbsp;"; } firstInGroup = false; expression += referenceToExpression(rel.type) + " " + e_equals + " " + referenceToExpression(rel.target); }); if (group != 0) { expression += " " + e_closeCurlyBraces; } }); } return expression; }; var renderExpression = function(concept, inferredConcept, div, options) { var preCoordinatedHtml = referenceToExpression(concept); var tmp = document.createElement("DIV"); tmp.innerHTML = preCoordinatedHtml; var plainPreCoordinatedExpression = tmp.textContent || tmp.innerText || ""; plainPreCoordinatedExpression = plainPreCoordinatedExpression.replace(/\s\s+/g, ' '); var statedHtml = conceptToPostCoordinatedExpression(concept, "statedRelationships", div, options); var tmp = document.createElement("DIV"); tmp.innerHTML = statedHtml; var plainStatedExpression = tmp.textContent || tmp.innerText || ""; plainStatedExpression = plainStatedExpression.replace(/\s\s+/g, ' '); var inferredHtml = conceptToPostCoordinatedExpression(concept, "relationships", div, options); var tmp = document.createElement("DIV"); tmp.innerHTML = inferredHtml; var plainInferredExpression = tmp.textContent || tmp.innerText || ""; plainInferredExpression = plainInferredExpression.replace(/\s\s+/g, ' '); //console.log(div); var context = { divElementId: div.attr('id'), preCoordinatedExpressionHtml: preCoordinatedHtml, statedExpressionHtml: statedHtml, inferredExpressionHtml: inferredHtml, plainPreCoordinatedExpression: plainPreCoordinatedExpression, plainStatedExpression: plainStatedExpression, plainInferredExpression: plainInferredExpression }; div.html(JST["views/conceptDetailsPlugin/tabs/expression.hbs"](context).trim()); if (panel.clipboard) panel.clipboard.destroy(); panel.clipboard = new Clipboard('.clip-btn-exp'); panel.clipboard.on('success', function(e) { // console.info('Action:', e.action); // console.info('Text:', e.text); // console.info('Trigger:', e.trigger); alertEvent("Copied!", "info"); e.clearSelection(); }); panel.clipboard.on('error', function(e) { console.log("Error!"); alertEvent("Error", "error"); }); }; $(function() { $.extend($.fn.disableTextSelect = function() { return this.each(function() { $(this).mousedown(function() { return false; }); }); }); $('.noSelect').disableTextSelect(); //No text selection on elements with a class of 'noSelect' }); function conceptDetails(divElement, conceptId, options) { if (typeof componentsRegistry == "undefined") { componentsRegistry = []; } var languageNameOfLangRefset = { "20581000087109": "fr-CA", "19491000087109": "en-CA", "900000000000508004": "en-GB", "900000000000509007": "en-US", "450828004": "es", "900000701000122101": "es-ES", "554461000005103": "DA", "46011000052107": "SV", "32570271000036106": "AU", "999001251000000103": "UK", "11000146104": "NL" }; if (options.languageNameOfLangRefset) languageNameOfLangRefset = options.languageNameOfLangRefset; var panel = this; this.type = "concept-details"; this.conceptId = conceptId; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); this.attributesPId = ""; this.descsPId = ""; this.relsPId = ""; this.history = []; this.color = "white"; panel.preferred = false; panel.acceptable = false; panel.included = false; panel.refset = {}; panel.refset.simple = false; panel.refset.simplemap = false; panel.refset.attr = false; panel.refset.assoc = false; this.lastGroup = null; this.subscription = null; var xhr = null; var xhrChildren = null; var xhrReferences = null; var xhrParents = null; var xhrMembers = null; var componentConceptPanel = null; var conceptRequested = 0; panel.subscriptionsColor = []; panel.subscriptions = []; panel.subscribers = []; componentLoaded = false; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } this.getConceptId = function() { return this.conceptId; } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setupCanvas = function() { panel.attributesPId = panel.divElement.id + "-attributes-panel"; panel.descsPId = panel.divElement.id + "-descriptions-panel"; panel.relsPId = panel.divElement.id + "-rels-panel"; panel.childrenPId = panel.divElement.id + "-children-panel"; panel.defaultTerm = ""; $(divElement).html(); var context = { divElementId: panel.divElement.id, }; // options statedParents inferredParents firstMatch statedRoles inferredRoles allDescriptions // dataContentValue = document.URL.split("?")[0].split("#")[0] $(divElement).html(JST["views/conceptDetailsPlugin/main.hbs"](context)); // $("#" + panel.divElement.id + "-linkerButton").disableTextSelect(); $("#" + panel.divElement.id + "-subscribersMarker").disableTextSelect(); $("#" + panel.divElement.id + "-configButton").disableTextSelect(); $("#" + panel.divElement.id + "-historyButton").disableTextSelect(); $("#" + panel.divElement.id + "-collapseButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").disableTextSelect(); $("#" + panel.divElement.id + "-closeButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-subscribersMarker").hide(); $("#" + panel.divElement.id + "-closeButton").click(function(event) { $(divElement).remove(); }); $("#" + panel.divElement.id + "-configButton").click(function(event) { panel.setupOptionsPanel(); }); if (typeof panel.options.closeButton != "undefined" && panel.options.closeButton == false) { $("#" + panel.divElement.id + "-closeButton").hide(); } // if (typeof panel.options.linkerButton != "undefined" && panel.options.linkerButton == false) { // $("#" + panel.divElement.id + "-linkerButton").hide(); // } if (typeof panel.options.subscribersMarker != "undefined" && panel.options.subscribersMarker == false) { $("#" + panel.divElement.id + "-subscribersMarker").remove(); } if (typeof panel.options.collapseButton != "undefined" && panel.options.collapseButton == false) { $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").hide(); } $("#" + panel.divElement.id + "-expandButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideDown("fast"); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").show(); $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp<strong>Concept Details</strong>"); }); $("#" + panel.divElement.id + "-collapseButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideUp("fast"); $("#" + panel.divElement.id + "-expandButton").show(); $("#" + panel.divElement.id + "-collapseButton").hide(); //if (panel.defaultTerm.length > 25) { // $("#" + panel.divElement.id + "-panelTitle").html("<strong>Concept Details: " + panel.defaultTerm.substring(0, 24).trim() + "...</strong>"); //} else { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp<strong>Concept Details: " + panel.defaultTerm + "</strong>"); //} }); $('#' + panel.divElement.id).click(function(event) { if (!$(event.target).hasClass('glyphicon')) { $('#' + panel.divElement.id).find('.more-fields-button').popover('hide'); } }); $("#" + panel.divElement.id + "-historyButton").click(function(event) { $("#" + panel.divElement.id + "-historyButton").popover({ trigger: 'manual', placement: 'bottomRight', html: true, content: function() { var historyHtml = '<div style="height:100px;overflow:auto;">'; historyHtml = historyHtml + '<table>'; var reversedHistory = panel.history.slice(0); reversedHistory.reverse(); //console.log(JSON.stringify(reversedHistory)); $.each(reversedHistory, function(i, field) { var d = new Date(); var curTime = d.getTime(); var ago = curTime - field.time; var agoString = ""; if (ago < (1000 * 60)) { if (Math.round((ago / 1000)) == 1) { agoString = Math.round((ago / 1000)) + ' second ago'; } else { agoString = Math.round((ago / 1000)) + ' seconds ago'; } } else if (ago < (1000 * 60 * 60)) { if (Math.round((ago / 1000) / 60) == 1) { agoString = Math.round((ago / 1000) / 60) + ' minute ago'; } else { agoString = Math.round((ago / 1000) / 60) + ' minutes ago'; } } else if (ago < (1000 * 60 * 60 * 60)) { if (Math.round(((ago / 1000) / 60) / 60) == 1) { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hour ago'; } else { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hours ago'; } } historyHtml = historyHtml + '<tr><td><a href="javascript:void(0);" onclick="updateCD(\'' + panel.divElement.id + '\',' + field.conceptId + ');">' + field.defaultTerm + '</a>'; historyHtml = historyHtml + ' <span class="text-muted" style="font-size: 80%"><em>' + agoString + '<em></span>'; historyHtml = historyHtml + '</td></tr>'; }); historyHtml = historyHtml + '</table>'; historyHtml = historyHtml + '</div>'; return historyHtml; } }); $("#" + panel.divElement.id + "-historyButton").popover('toggle'); }); if (typeof i18n_panel_options == "undefined") { i18n_panel_options = "Panel options"; } $("#" + panel.divElement.id + "-configButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_panel_options, animation: true, delay: 1000 }); if (typeof i18n_history == "undefined") { i18n_history = 'History'; } $("#" + panel.divElement.id + "-historyButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_history, animation: true, delay: 1000 }); if (typeof i18n_panel_links == "undefined") { i18n_panel_links = 'Panel links'; } // $("#" + panel.divElement.id + "-linkerButton").tooltip({ // placement : 'left', // trigger: 'hover', // title: i18n_panel_links, // animation: true, // delay: 1000 // }); $("#" + panel.divElement.id + "-apply-button").click(function() { //console.log("apply!"); panel.readOptionsPanel(); // panel.updateCanvas(); }); // $("#" + panel.divElement.id + "-linkerButton").click(function(event) { // $("#" + panel.divElement.id + "-linkerButton").popover({ // trigger: 'manual', // placement: 'bottomRight', // html: true, // content: function() { // if (panel.subscriptions.length == 0) { // linkerHtml = '<div class="text-center text-muted"><em>Not linked yet<br>Drag to link with other panels</em></div>'; // } else { // var linkHtml = ''; // $.each(panel.subscriptions, function(i, field){ // var panelLink = {}; // $.each(componentsRegistry, function(i, panl){ // if (panl.divElement.id == field.topic){ // panelLink = panl; // } // }); // linkHtml = linkHtml + '<div class="text-center"><a href="javascript:void(0);" onclick="\'' + panel.unsubscribe(panelLink) + '\'">Clear link with '+ field.topic +'</a><br></div>'; // }); // linkHtml = linkHtml + ''; // linkerHtml = linkHtml; // } // return linkerHtml; // } // }); // $("#" + panel.divElement.id + "-linkerButton").popover('toggle'); // }); panel.updateCanvas(); channel.publish(panel.divElement.id, { term: panel.term, module: panel.module, conceptId: panel.conceptId, source: panel.divElement.id }); panel.setupOptionsPanel(); if (panel.subscriptions.length > 0 || panel.subscribers.length > 0) { $("#" + panel.divElement.id + "-subscribersMarker").show(); } $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor); } this.updateCanvas = function() { // $("#members-" + panel.divElement.id).html(""); $("#home-children-cant-" + panel.divElement.id).html(""); $('.more-fields-button').popover('hide'); if (conceptRequested == panel.conceptId) { return; } conceptRequested = panel.conceptId; $("#home-children-" + panel.divElement.id + "-body").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.attributesPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#home-attributes-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.descsPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.relsPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#home-parents-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#home-roles-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.childrenPId).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $("#diagram-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#refsets-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#product-details-' + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); // load attributes if (xhr != null) { xhr.abort(); //console.log("aborting call..."); } xhr = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/concepts/" + panel.conceptId, function(result) { }).done(function(result) { setDefaultTerm(result); var firstMatch = result; xhr = null; panel.attributesPId = divElement.id + "-attributes-panel"; panel.defaultTerm = firstMatch.defaultTerm; var d = new Date(); var time = d.getTime(); panel.history.push({ defaultTerm: firstMatch.defaultTerm, conceptId: firstMatch.conceptId, time: time }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); panel.statedParents = []; panel.inferredParents = []; panel.statedRoles = []; panel.inferredRoles = []; panel.statedParentsFromAxioms = []; panel.attributesFromAxioms = []; firstMatch.relationships.forEach(function(loopRel) { if (loopRel.characteristicType == "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId != "116680003") { panel.inferredRoles.push(loopRel); } else if(loopRel.characteristicType == "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId === "116680003"){ panel.inferredParents.push(loopRel); } else if(loopRel.characteristicType != "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId === "116680003"){ panel.statedRoles.push(loopRel); } else if (loopRel.characteristicType != "INFERRED_RELATIONSHIP" && loopRel.active && loopRel.type.conceptId != "116680003") { panel.statedRoles.push(loopRel); } }); firstMatch.classAxioms.forEach(function(axiom) { if(axiom.active){ axiom.relationships.forEach(function(rel) { if(rel.active && rel.type.conceptId === "116680003"){ panel.statedParentsFromAxioms.push(rel); } else{ rel.axiomId = axiom.axiomId; rel.type = 'Axiom'; panel.attributesFromAxioms.push(rel); } }); } }); firstMatch.gciAxioms.forEach(function(axiom) { if(axiom.active){ axiom.relationships.forEach(function(rel) { if(rel.active && rel.type.conceptId !== "116680003"){ rel.axiomId = axiom.axiomId; rel.type = 'GCI'; panel.attributesFromAxioms.push(rel); } }); } }); if (firstMatch.statedDescendants) { firstMatch.statedDescendantsString = firstMatch.statedDescendants.toLocaleString(); } if (firstMatch.inferredDescendants) { firstMatch.inferredDescendantsString = firstMatch.inferredDescendants.toLocaleString(); } var context = { options: panel.options, firstMatch: firstMatch, divElementId: panel.divElement.id, edition: options.edition, release: options.release, server: options.serverUrl.substr(0, options.serverUrl.length - 10), langRefset: panel.options.langRefset, link: document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset, // dataContentValue: options.serverUrl.substr(0, options.serverUrl.length - 10) dataContentValue: document.URL.split("?")[0].split("#")[0] }; $('#' + panel.attributesPId).html(JST["views/conceptDetailsPlugin/tabs/details/attributes-panel.hbs"](context)); $('#' + 'share-link-' + panel.divElement.id).disableTextSelect(); $('#' + 'share-link-' + panel.divElement.id).click(function(event) { setTimeout(function() { $('#' + 'share-field-' + panel.divElement.id).select(); }, 300); }); // load home-attributes Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper("if_fav", function(concept, opts) { var favs = stringToArray(localStorage.getItem("favs")); var found = false; if (favs) { $.each(favs, function(i, field) { if (field == concept) { found = true; } }); if (found) { return opts.fn(this); } else { return opts.inverse(this); } } else { return opts.inverse(this); } }); var context = { panel: panel, firstMatch: firstMatch, divElementId: panel.divElement.id, link: document.URL.split("?")[0].split("#")[0] + "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + panel.options.edition + "&release=" + panel.options.release + "&server=" + panel.options.serverUrl + "&langRefset=" + panel.options.langRefset }; $('#home-attributes-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/attributes.hbs"](context)); // Update browser history var historyUrl = "?perspective=full&conceptId1=" + firstMatch.conceptId + "&edition=" + options.edition + "&release=" + options.release + "&server=" + options.serverUrl + "&langRefset=" + options.langRefset; manualStateChange = false; var state = { name: firstMatch.defaultTerm, conceptId: firstMatch.conceptId, url: historyUrl }; History.pushState(state, "SNOMED CT - " + firstMatch.defaultTerm, historyUrl); $(".glyphicon-star-empty").click(function(e) { var concept = { module: firstMatch.module, conceptId: firstMatch.conceptId, defaultTerm: firstMatch.defaultTerm }; if ($(e.target).hasClass("glyphicon-star")) { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); localStorage.setItem("favs", auxFavs); localStorage.removeItem("conceptId:" + $(e.target).attr("data-conceptId")); $(e.target).addClass("glyphicon-star-empty"); $(e.target).removeClass("glyphicon-star"); // console.log("removed from favs"); } else { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; if (!favs) { favs = []; favs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", favs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } else { $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); auxFavs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", auxFavs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } $(e.target).addClass("glyphicon-star"); $(e.target).removeClass("glyphicon-star-empty"); } channel.publish("favsAction"); }); // console.log("paso"); //$('.clip-btn').unbind(); if (panel.clipboard) panel.clipboard.destroy(); panel.clipboard = new Clipboard('.clip-btn'); panel.clipboard.on('success', function(e) { // console.info('Action:', e.action); // console.info('Text:', e.text); // console.info('Trigger:', e.trigger); alertEvent("Copied!", "info"); e.clearSelection(); }); panel.clipboard.on('error', function(e) { console.log("Error!"); alertEvent("Error", "error"); }); //var ctrlDown = false, // ctrlKey = 17, // cmdKey = 91, // vKey = 86, // cKey = 67; // //$(document).keydown(function(e) { // if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true; //}).keyup(function(e) { // if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false; //}); // //$(document).keydown(function(e) { // if (ctrlDown && e.keyCode == cKey){ // //var copyContent = document.getElementById("copy-content"); // e.clipboardData.setData('text/plain', firstMatch.term); // e.preventDefault(); // //$("#" + panel.divElement.id + "-copy-sctid-term-details").click(); // //console.log("asd"); // } //}); document.addEventListener("copy", copyHandler, false); function copyHandler(e) { if (window.getSelection().isCollapsed) { if (e.srcElement && e.srcElement.value) {} else { e.clipboardData.setData('text/plain', firstMatch.conceptId + " | " + firstMatch.defaultTerm + " |"); e.preventDefault(); alertEvent("Copied!", "info"); } } } //Swedish extension; capture synonyms using JIRA issue collector //start var scriptUrl = "https://jira.ihtsdotools.org/s/9152b378d577114d19d6cfdcdfdeb45e-T/en_US-i9n6p8/70120/a1623a9e469981bb7c457209f1507980/2.0.8/_/download/batch/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector/com.atlassian.jira.collector.plugin.jira-issue-collector-plugin:issuecollector.js?locale=en-US&collectorId=41bec258"; $.getScript(scriptUrl); window.ATL_JQ_PAGE_PROPS = { "triggerFunction": function(showCollectorDialog) { //Requires that jQuery is available! jQuery("#fh-cd1_canvas-addsyn-sctid-details").click(function(e) { e.preventDefault(); showCollectorDialog(); }); }, fieldValues: { 'summary': 'Förslag på synonymer för begreppet: ' + state.conceptId, 'customfield_10602': state.conceptId, 'customfield_10601': state.name } }; //end $(".glyphicon-star").click(function(e) { var concept = { module: firstMatch.module, conceptId: firstMatch.conceptId, defaultTerm: firstMatch.defaultTerm }; if ($(e.target).hasClass("glyphicon-star")) { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); localStorage.setItem("favs", auxFavs); localStorage.removeItem("conceptId:" + $(e.target).attr("data-conceptId")); $(e.target).addClass("glyphicon-star-empty"); $(e.target).removeClass("glyphicon-star"); // console.log("removed from favs"); } else { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; if (!favs) { favs = []; favs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", favs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } else { $.each(favs, function(i, field) { if (field != $(e.target).attr("data-conceptId")) { auxFavs.push(field); } }); auxFavs.push($(e.target).attr("data-conceptId")); localStorage.setItem("favs", auxFavs); localStorage.setItem("conceptId:" + $(e.target).attr("data-conceptId"), JSON.stringify(concept)); } $(e.target).addClass("glyphicon-star"); $(e.target).removeClass("glyphicon-star-empty"); } channel.publish("favsAction"); }); if (!firstMatch.active) { $('#home-attributes-' + panel.divElement.id).css("background-color", "LightPink"); } else { $('#home-attributes-' + panel.divElement.id).css("background-color", "#428bca"); } if ($("#" + panel.divElement.id + "-expandButton").is(":visible")) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp;&nbsp;&nbsp;<strong>Concept Details: " + panel.defaultTerm + "</strong>"); } if (typeof i18n_drag_this == "undefined") { i18n_drag_this = "Drag this"; } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); // load descriptions panel panel.descsPId = divElement.id + "-descriptions-panel"; var languageName = ""; if (panel.options.langRefset == "900000000000508004") { languageName = "(GB)"; } else if (panel.options.langRefset == "900000000000509007") { languageName = "(US)"; } else if (panel.options.langRefset == "450828004") { languageName = "(ES)"; } else if (panel.options.langRefset == "554461000005103") { languageName = "(DA)"; } else if (panel.options.langRefset == "46011000052107") { languageName = "(SV)"; } else if (panel.options.langRefset == "32570271000036106") { languageName = "(AU)"; } else if (panel.options.langRefset == "999001251000000103") { languageName = "(UK)"; } else if (panel.options.langRefset == "31000146106") { languageName = "(NL)"; } // START FOR var allLangsHtml = ""; $.each(panel.options.langRefset, function(i, loopSelectedLangRefset) { var allDescriptions = firstMatch.descriptions.slice(0); var homeDescriptionsHtml = ""; $.each(allDescriptions, function(i, field) { field.included = false; field.preferred = false; field.acceptable = false; if (panel.options.displayInactiveDescriptions || field.active == true) { if (field.active == true) { if (homeDescriptionsHtml != "") { homeDescriptionsHtml = homeDescriptionsHtml + "<br>"; } homeDescriptionsHtml = homeDescriptionsHtml + "&nbsp;&nbsp;<i>" + field.lang + "</i>&nbsp;&nbsp;&nbsp;" + field.term; } } }); Handlebars.registerHelper('removeSemtag', function(term) { return panel.removeSemtag(term); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); var auxDescriptions = []; $.each(allDescriptions, function(i, description) { var included = false; if (description.acceptabilityMap) { $.each(description.acceptabilityMap, function(langref, acceptability) { acceptabilityPair = description.acceptabilityMap[i]; if (langref == loopSelectedLangRefset) { included = true; if (acceptability == "PREFERRED") { description.preferred = true; } else { if (acceptability == "ACCEPTABLE") { description.acceptable = true; } } } }); } if (included) { auxDescriptions.push(description); } else { description.acceptable = false; if (panel.options.hideNotAcceptable) { if (panel.options.displayInactiveDescriptions) { auxDescriptions.push(description); } } else { if (options.displayInactiveDescriptions) { auxDescriptions.push(description); } else { if (description.active) { auxDescriptions.push(description); } } } } }); allDescriptions = auxDescriptions.slice(0); allDescriptions.sort(function(a, b) { if (a.active && !b.active) return -1; if (!a.active && b.active) return 1; if (a.active == b.active) { if ((a.acceptable || a.preferred) && (!b.preferred && !b.acceptable)) return -1; if ((!a.preferred && !a.acceptable) && (b.acceptable || b.preferred)) return 1; if (a.type.conceptId < b.type.conceptId) return -1; if (a.type.conceptId > b.type.conceptId) return 1; if (a.type.conceptId == b.type.conceptId) { if (a.preferred && !b.preferred) return -1; if (!a.preferred && b.preferred) return 1; if (a.preferred == b.preferred) { if (a.term < b.term) return -1; if (a.term > b.term) return 1; } } } return 0; }); var context = { options: panel.options, languageName: "(" + languageNameOfLangRefset[loopSelectedLangRefset] + ")", longLangName: loopSelectedLangRefset, divElementId: panel.divElement.id, allDescriptions: allDescriptions }; if (panel.options.manifest) { $.each(panel.options.manifest.languageRefsets, function(i, looplr) { if (looplr.conceptId == loopSelectedLangRefset) { context.longLangName = looplr.defaultTerm; } }); } allLangsHtml += JST["views/conceptDetailsPlugin/tabs/details/descriptions-panel.hbs"](context); //if (panel.options.displaySynonyms) { $('#home-descriptions-' + panel.divElement.id).html(homeDescriptionsHtml); //} }); // END FOR $("#" + panel.descsPId).html(allLangsHtml); if (panel.options.displaySynonyms != true) { // hide synonyms $('#' + panel.descsPId).find('.synonym-row').each(function(i, val) { $(val).toggle(); }); $(this).toggleClass('glyphicon-plus'); $(this).toggleClass('glyphicon-minus'); } $("#" + panel.descsPId + "-descButton").disableTextSelect(); $("#" + panel.descsPId + "-descButton").click(function() { table = $(this).closest("table").first(); $(this).toggleClass('glyphicon-plus'); $(this).toggleClass('glyphicon-minus'); table.find('.synonym-row').each(function(i, val) { $(val).toggle(); }); }); $('#' + panel.descsPId).find("[rel=tooltip-right]").tooltip({ placement: 'right' }); // load relationships panel and home parents/roles if (panel.options.selectedView == "stated") { //$('#home-' + panel.divElement.id + '-viewLabel').html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); //$('#home-' + panel.divElement.id + '-diagram-viewLabel').html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); $('#home-' + panel.divElement.id + '-stated-button').unbind(); $('#home-' + panel.divElement.id + '-inferred-button').unbind(); $('#details-' + panel.divElement.id + '-stated-button').unbind(); $('#details-' + panel.divElement.id + '-inferred-button').unbind(); $('#home-' + panel.divElement.id + '-stated-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-stated-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-inferred-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-inferred-button').removeClass("btn-primary"); $('#details-' + panel.divElement.id + '-stated-button').addClass("btn-primary"); $('#details-' + panel.divElement.id + '-stated-button').removeClass("btn-default"); $('#details-' + panel.divElement.id + '-inferred-button').addClass("btn-default"); $('#details-' + panel.divElement.id + '-inferred-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-inferred-button').click(function(event) { panel.options.selectedView = "inferred"; panel.updateCanvas(); }); $('#details-' + panel.divElement.id + '-inferred-button').click(function(event) { panel.options.selectedView = "inferred"; panel.updateCanvas(); }); } else { //$('#home-' + panel.divElement.id + '-viewLabel').html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); //$('#home-' + panel.divElement.id + '-diagram-viewLabel').html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); $('#home-' + panel.divElement.id + '-stated-button').unbind(); $('#home-' + panel.divElement.id + '-inferred-button').unbind(); $('#home-' + panel.divElement.id + '-inferred-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-inferred-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-stated-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-stated-button').removeClass("btn-primary"); $('#details-' + panel.divElement.id + '-stated-button').unbind(); $('#details-' + panel.divElement.id + '-inferred-button').unbind(); $('#details-' + panel.divElement.id + '-inferred-button').addClass("btn-primary"); $('#details-' + panel.divElement.id + '-inferred-button').removeClass("btn-default"); $('#details-' + panel.divElement.id + '-stated-button').addClass("btn-default"); $('#details-' + panel.divElement.id + '-stated-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-stated-button').click(function(event) { panel.options.selectedView = "stated"; panel.updateCanvas(); }); $('#details-' + panel.divElement.id + '-stated-button').click(function(event) { panel.options.selectedView = "stated"; panel.updateCanvas(); }); } panel.relsPId = divElement.id + "-rels-panel"; if (firstMatch.relationships) { firstMatch.relationships.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.type.conceptId == 116680003) { return -1; } if (b.type.conceptId == 116680003) { return 1; } if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); } if (firstMatch.statedRelationships) { firstMatch.statedRelationships.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.type.conceptId == 116680003) { return -1; } if (b.type.conceptId == 116680003) { return 1; } if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); } Handlebars.registerHelper('push', function(element, array) { array.push(element); // return ; }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); var additionalRels; if (firstMatch.additionalRelationships) { $.each(firstMatch.additionalRelationships, function(i, looplr) { if (looplr.active) { if (typeof additionalRels == "undefined") additionalRels = []; additionalRels.push(looplr); } }); } var context = { options: panel.options, firstMatch: firstMatch, inferredParents: panel.inferredParents, inferredRoles: panel.inferredRoles, statedParents: panel.statedParents, statedRoles: panel.statedRoles, additionalRels: additionalRels, statedParentsFromAxioms: panel.statedParentsFromAxioms, attributesFromAxioms : panel.attributesFromAxioms }; $("#" + panel.relsPId).html(JST["views/conceptDetailsPlugin/tabs/details/rels-panel.hbs"](context)); panel.inferredParents.sort(function(a, b) { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; }); panel.statedParents.sort(function(a, b) { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; }); panel.statedParentsFromAxioms.sort(function(a, b) { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; }); panel.attributesFromAxioms.sort(function(a, b) { if (a.target.axiomId < b.target.axiomId) return -1; if (a.target.axiomId > b.target.axiomId) return 1; return 0; }); panel.inferredRoles.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); panel.statedRoles.sort(function(a, b) { if (a.groupId < b.groupId) { return -1; } else if (a.groupId > b.groupId) { return 1; } else { if (a.target.defaultTerm < b.target.defaultTerm) return -1; if (a.target.defaultTerm > b.target.defaultTerm) return 1; return 0; } }); Handlebars.registerHelper('substr', function(string, start) { var l = string.lastIndexOf("(") - 1; return string.substr(start, l); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { var s = a.lastIndexOf("("); if (s > b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); var axioms = false; if(firstMatch.classAxioms.length > 0 || firstMatch.gciAxioms.length > 0) { axioms = true; } else { axioms = false; } var context = { divElementId: panel.divElement.id, statedParents: panel.statedParents, inferredParents: panel.inferredParents, options: panel.options, firstMatch: firstMatch, statedParentsFromAxioms: panel.statedParentsFromAxioms, attributesFromAxioms : panel.attributesFromAxioms, axioms: axioms }; $('#home-parents-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/parents.hbs"](context)); if (!panel.options.diagrammingMarkupEnabled) { $('#home-parents-' + panel.divElement.id).html(panel.stripDiagrammingMarkup($('#home-parents-' + panel.divElement.id).html())); } $(".treeButton").disableTextSelect(); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); $("#home-parents-" + panel.divElement.id).unbind(); $("#home-parents-" + panel.divElement.id).click(function(event) { if ($(event.target).hasClass("treeButton")) { var ev = event.target; //firefox issue! if (navigator.userAgent.indexOf("Firefox") > -1) { ev = $(ev).context.children; } var conceptId = $(ev).closest("li").attr('data-concept-id'); event.preventDefault(); if ($(ev).hasClass("glyphicon-chevron-up")) { $(ev).closest("li").find("ul").remove(); $(ev).removeClass("glyphicon-chevron-up"); $(ev).addClass("glyphicon-chevron-right"); } else if ($(ev).hasClass("glyphicon-chevron-right")) { $(ev).removeClass("glyphicon-chevron-right"); $(ev).addClass("glyphicon-refresh"); $(ev).addClass("icon-spin"); panel.getParent(conceptId, ev); } else if ($(ev).hasClass("glyphicon-minus")) { // $("#" + iconId).removeClass("glyphicon-minus"); // $("#" + iconId).addClass("glyphicon-chevron-right"); } } else if ($(event.target).hasClass("treeLabel")) { var selectedId = $(event.target).attr('data-concept-id'); if (typeof selectedId != "undefined") { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: selectedId, source: panel.divElement.id }); } } }); $("#home-parents-" + panel.divElement.id).dblclick(function(event) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); panel.conceptId = conceptId; panel.updateCanvas(); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: conceptId, source: panel.divElement.id }); }); Handlebars.registerHelper('eqLastGroup', function(a, opts) { // console.log(a, panel.lastGroup); if (panel.lastGroup == null) { panel.lastGroup = a; return opts.fn(this); } if (a != panel.lastGroup) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('removeSemtag', function(term) { return panel.removeSemtag(term); }); Handlebars.registerHelper('setLastGroup', function(a) { panel.lastGroup = a; }); Handlebars.registerHelper('lastColor', function(a) { if (a == "get") { return ""; // return panel.color; } else { if (a == "random") { panel.color = getRandomColor(); } else { panel.color = a; } } }); Handlebars.registerHelper('getRandomColor', function() { // return getRandomColor(); return ""; }); var context = { options: panel.options, statedRoles: panel.statedRoles, inferredRoles: panel.inferredRoles, firstMatch: firstMatch, statedParentsFromAxioms: panel.statedParentsFromAxioms, attributesFromAxioms : panel.attributesFromAxioms }; // console.log(panel.statedRoles); // console.log(panel.inferredRoles); $('#home-roles-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/home/roles.hbs"](context)); if (!panel.options.diagrammingMarkupEnabled) { $('#home-roles-' + panel.divElement.id).html(panel.stripDiagrammingMarkup($('#home-roles-' + panel.divElement.id).html())); } Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('refset', function(type, data, opts) { if (data == "get") { if (panel.refset[type]) { return opts.fn(this); } else { return opts.inverse(this); } } else { panel.refset[type] = data; } }); var context = { firstMatch: firstMatch }; $('#refsets-' + panel.divElement.id).html(JST["views/conceptDetailsPlugin/tabs/refset.hbs"](context)); $.each($("#refsets-" + panel.divElement.id).find('.refset-simplemap'), function(i, field) { // console.log(field); // console.log($(field).attr('data-refsetId')); if ($(field).attr('data-refsetId') == "467614008") { channel.publish("refsetSubscription-467614008", { conceptId: $(field).attr('data-conceptId') }); } }); if ($('ul#details-tabs-' + panel.divElement.id + ' li.active').attr('id') == "references-tab") { $("#references-" + panel.divElement.id + "-resultsTable").html(""); panel.getReferences(firstMatch.conceptId); } if ($('ul#details-tabs-' + panel.divElement.id + ' li.active').attr('id') == "diagram-tab") { drawConceptDiagram(firstMatch, $("#diagram-canvas-" + panel.divElement.id), panel.options, panel); } if ($('ul#details-tabs-' + panel.divElement.id + ' li.active').attr('id') == "expression-tab") { $("#expression-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); setTimeout(function() { renderExpression(firstMatch, firstMatch, $("#expression-canvas-" + panel.divElement.id), options); }, 300); } $("#references-tab-link-" + panel.divElement.id).unbind(); $("#references-tab-link-" + panel.divElement.id).click(function(e) { $("#references-" + panel.divElement.id + "-resultsTable").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); panel.getReferences(firstMatch.conceptId); }); $("#diagram-tab-link-" + panel.divElement.id).unbind(); $("#diagram-tab-link-" + panel.divElement.id).click(function(e) { $("#diagram-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); setTimeout(function() { $("#diagram-canvas-" + panel.divElement.id).html(""); drawConceptDiagram(firstMatch, $("#diagram-canvas-" + panel.divElement.id), panel.options, panel); }, 1000); }); $("#expression-tab-link-" + panel.divElement.id).unbind(); $("#expression-tab-link-" + panel.divElement.id).click(function(e) { $("#expression-canvas-" + panel.divElement.id).html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); setTimeout(function() { $("#expression-canvas-" + panel.divElement.id).html(""); renderExpression(firstMatch, firstMatch, $("#expression-canvas-" + panel.divElement.id), options); }, 1000) }); if (firstMatch.defaultTerm.endsWith("(clinical drug)")) { $("#product-details-tab").show(); var productData = { defaultTerm: firstMatch.defaultTerm, forms: [], groups: {}, ingredients: [] }; firstMatch.relationships.forEach(function(loopRel) { if (loopRel.type.conceptId == "411116001" && loopRel.active) { productData.forms.push(loopRel); } else if (loopRel.active && loopRel.groupId != 0) { if (typeof productData.groups[loopRel.groupId] == "undefined") { productData.groups[loopRel.groupId] = []; } productData.groups[loopRel.groupId].push(loopRel); } }); Object.keys(productData.groups).forEach(function(loopKey) { var loopGroup = productData.groups[loopKey]; var loopIngredient = {}; loopGroup.forEach(function(loopRel) { if (loopRel.type.conceptId == "127489000") { loopIngredient.ingredient = loopRel.target; } else if (loopRel.type.conceptId == "732946004") { loopIngredient.denominatorValue = loopRel.target; } else if (loopRel.type.conceptId == "732944001") { loopIngredient.numeratorValue = loopRel.target; } else if (loopRel.type.conceptId == "732943007") { loopIngredient.boss = loopRel.target; } else if (loopRel.type.conceptId == "732947008") { loopIngredient.denominatorUnit = loopRel.target; } else if (loopRel.type.conceptId == "732945000") { loopIngredient.numeratorUnit = loopRel.target; } }); productData.ingredients.push(loopIngredient); // var demoIngredient1 = { // ingredient: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Atenolol (substance)"}, // boss: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Atenolol (substance)"}, // numeratorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"50 (qualifier value)"}, // numeratorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"milligram (qualifier value)"}, // denominatorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"1 (qualifier value)"}, // denominatorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Tablet (unit of presentation)"} // }; // var demoIngredient2 = { // ingredient: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Chlorthalidone (substance)"}, // boss: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Chlorthalidone (substance)"}, // numeratorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"12.5 (qualifier value)"}, // numeratorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"milligram (qualifier value)"}, // denominatorValue: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"1 (qualifier value)"}, // denominatorUnit: {definitionStatus: "PRIMITIVE",conceptId:1,defaultTerm:"Tablet (unit of presentation)"} // }; //productData.ingredients = [demoIngredient1, demoIngredient2]; }); console.log(productData); var context = { productData: productData }; $('#product-details-' + panel.divElement.id).html( JST["views/conceptDetailsPlugin/tabs/product.hbs"](context)); } else { $("#product-details-tab").hide(); $('#details-tabs-' + panel.divElement.id + ' a:first').tab('show') } $('.more-fields-button').disableTextSelect(); $('.more-fields-button').popover(); // firefox popover if (navigator.userAgent.indexOf("Firefox") > -1) { $(".more-fields-button").optionsPopover({ contents: "", disableBackButton: true }); $(".more-fields-button").click(function(e) { var auxHtml = $(e.target).attr('data-content'); $("#popoverContent").html(auxHtml); }); } if (panel.options.selectedView == "stated") { $('#' + panel.relsPId).find('.inferred-rel').each(function(i, val) { $(val).toggle(); }); } else if (panel.options.selectedView == "inferred") { $('#' + panel.relsPId).find('.stated-rel').each(function(i, val) { $(val).toggle(); }); } else if (panel.options.selectedView != "all") { // show all } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); if (typeof(switchLanguage) == "function") { switchLanguage(selectedLanguage, selectedFlag, false); } conceptRequested = 0; // membersUrl = options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + panel.conceptId + "/members"; }).fail(function() { panel.relsPId = divElement.id + "-rels-panel"; panel.attributesPId = divElement.id + "-attributes-panel"; panel.descsPId = divElement.id + "-descriptions-panel"; $("#home-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#diagram-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#members-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#references-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $("#refsets-" + panel.divElement.id).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $('#' + panel.attributesPId).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); $('#' + panel.descsPId).html(""); $('#' + panel.relsPId).html(""); }); // if (typeof xhr != "undefined") { // console.log("aborting call..."); // // } if (panel.options.displayChildren) { var context = { }; } else {} // if (panel.options.displayChildren == false) { //// $("#home-children-" + panel.divElement.id).hide(); // $('#' + panel.childrenPId).html(""); // $('#' + panel.childrenPId).hide(); // } else { // $("#home-children-" + panel.divElement.id).show(); // $('#' + panel.childrenPId).show(); if (xhrChildren != null) { xhrChildren.abort(); //console.log("aborting children call..."); } xhrChildren = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + panel.conceptId + "/children?form=" + panel.options.selectedView, function(result) { //$.getJSON(panel.url + "rest/browser/concepts/" + panel.conceptId + "/children", function(result) { }).done(function(result) { result.forEach(function(c) { setDefaultTerm(c) }); // load relationships panel result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); xhrChildren = null; panel.childrenPId = divElement.id + "-children-panel"; // console.log(result); var context = { displayChildren: panel.options.displayChildren, divElementId: panel.divElement.id, childrenResult: result, selectedView: panel.options.selectedView }; $("#home-children-cant-" + panel.divElement.id).html("(" + result.length + ")"); $('#' + panel.childrenPId).html(JST["views/conceptDetailsPlugin/tabs/details/children-panel.hbs"](context)); $("#home-children-" + panel.divElement.id + "-body").html(JST["views/conceptDetailsPlugin/tabs/home/children.hbs"](context)); $(".treeButton").disableTextSelect(); if (typeof i18n_drag_this == "undefined") { i18n_drag_this = "Drag this"; } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); $("#home-children-" + panel.divElement.id + "-body").unbind(); $("#home-children-" + panel.divElement.id + "-body").click(function(event) { if ($(event.target).hasClass("treeButton")) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); var iconId = panel.divElement.id + "-treeicon-" + conceptId; event.preventDefault(); if ($("#" + iconId).hasClass("glyphicon-chevron-down")) { //console.log("close"); $(event.target).closest("li").find("ul").remove(); $("#" + iconId).removeClass("glyphicon-chevron-down"); $("#" + iconId).addClass("glyphicon-chevron-right"); } else if ($("#" + iconId).hasClass("glyphicon-chevron-right")) { //console.log("open"); $("#" + iconId).removeClass("glyphicon-chevron-right"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); panel.getChildren($(event.target).closest("li").attr('data-concept-id'), true); } else if ($("#" + iconId).hasClass("glyphicon-minus")) { // $("#" + iconId).removeClass("glyphicon-minus"); // $("#" + iconId).addClass("glyphicon-chevron-right"); } } else if ($(event.target).hasClass("treeLabel")) { var selectedId = $(event.target).attr('data-concept-id'); if (typeof selectedId != "undefined") { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: selectedId, source: panel.divElement.id }); } } }); $("#home-children-" + panel.divElement.id + "-body").dblclick(function(event) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); panel.conceptId = conceptId; panel.updateCanvas(); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: conceptId, source: panel.divElement.id }); }); if (typeof i18n_display_children == "undefined") { i18n_display_children = "Display Children"; } $("#" + panel.divElement.id + "-showChildren").tooltip({ placement: 'right', trigger: 'hover', title: i18n_display_children, animation: true, delay: 500 }); $("#" + panel.divElement.id + "-showChildren").click(function() { panel.options.displayChildren = true; panel.updateCanvas(); }); }).fail(function() { $('#' + panel.childrenPId).html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); }); // } panel.loadMembers(100, 0); } this.getReferences = function(conceptId) { $("#references-" + panel.divElement.id + "-accordion").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); //console.log(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/references"); if (xhrReferences != null) { xhrReferences.abort(); //console.log("aborting references call..."); } xhrReferences = $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/references?form=" + panel.options.selectedView, function(result) { }).done(function(result) { Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); $.each(result, function(i, field) { if (field.statedRelationships) { field.relationship = field.statedRelationships[0].type.defaultTerm; } else { field.relationship = field.relationships[0].type.defaultTerm; } }); result.sort(function(a, b) { if (a.relationship < b.relationship) return -1; if (a.relationship > b.relationship) return 1; if (a.relationship == b.relationship) { if (a.defaultTerm < b.defaultTerm) return -1; if (a.defaultTerm > b.defaultTerm) return 1; } return 0; }); result.groups = []; var lastR = "", auxArray = []; $.each(result, function(i, field) { if (lastR == "") { auxArray.push(field); lastR = field.relationship; } else { if (lastR == field.relationship) { auxArray.push(field); } else { result.groups.push(auxArray); auxArray = []; auxArray.push(field); lastR = field.relationship; } } }); result.groups.push(auxArray); // console.log(result.groups); var context = { divElementId: panel.divElement.id, result: result, groups: result.groups }; // $("#references-" + panel.divElement.id + "-total").html(result.length + " references"); $("#references-" + panel.divElement.id + "-accordion").html(JST["views/conceptDetailsPlugin/tabs/references.hbs"](context)); $("#references-" + panel.divElement.id + "-accordion").click(function(e) { if ($($(e.target).closest("a").attr("href")).hasClass("collapse")) { //console.log("finded"); var target = $($(e.target).closest("a").attr("href") + "-span"); if (target.hasClass("glyphicon-chevron-right")) { target.removeClass("glyphicon-chevron-right"); target.addClass("glyphicon-chevron-down"); } else { target.addClass("glyphicon-chevron-right"); target.removeClass("glyphicon-chevron-down"); } } }); // console.log(result, result.length); }).fail(function() { $("#references-" + panel.divElement.id + "-accordion").html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); }); } this.getChildren = function(conceptId, forceShow) { if (typeof panel.options.selectedView == "undefined") { panel.options.selectedView = "inferred"; } if (panel.options.selectedView == "inferred") { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); } else { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); } if (xhrChildren != null) { xhrChildren.abort(); //console.log("aborting children call..."); } xhrChildren = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/children?form=" + panel.options.selectedView, function(result) {}).done(function(result) { result.forEach(function(c) { setDefaultTerm(c) }); result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); //console.log(JSON.stringify(result)); var listIconIds = []; //console.log(JSON.stringify(listIconIds)); var context = { displayChildren: panel.options.displayChildren, childrenResult: result, divElementId: panel.divElement.id, selectedView: panel.options.selectedView }; if (typeof forceShow != "undefined") { if (forceShow) { context.displayChildren = forceShow; } } Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('push', function(element) { listIconIds.push(element); }); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); if (result.length > 0) { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down"); } else { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); } $("#" + panel.divElement.id + "-treenode-" + conceptId).closest("li").append(JST["views/conceptDetailsPlugin/tabs/home/children.hbs"](context)); $(".treeButton").disableTextSelect(); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() { $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); }); } this.getParent = function(conceptId, target) { if (xhrParents != null) { xhrParents.abort(); //console.log("aborting children call..."); } xhrParents = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/parents?form=" + panel.options.selectedView, function(result) { //$.getJSON(panel.url + "rest/browser/concepts/" + panel.conceptId + "/children", function(result) { }).done(function(result) { result.forEach(function(c) { setDefaultTerm(c) }); result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); var auxHtml = ""; var ind = $(target).attr('data-ind'); if (result.length > 0) { if ($(target).attr('data-firstt')) { auxHtml = "<ul style='margin-left: 95px; list-style-type: none; padding-left: 15px'>"; } else { auxHtml = "<ul style='list-style-type: none; padding-left: 15px'>"; } $.each(result, function(i, field) { // console.log(field); auxHtml = auxHtml + "<li class='treeLabel' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'><button class='btn btn-link btn-xs treeButton' style='padding:2px'>"; if (field.conceptId == "138875005" || field.conceptId == "9999999999") { auxHtml = auxHtml + "<i class='glyphicon glyphicon-minus treeButton' data-ind='" + ind + "'></i></button>"; } else { auxHtml = auxHtml + "<i class='glyphicon glyphicon-chevron-right treeButton' data-ind='" + ind + "'></i></button>"; } if (field.definitionStatus == "PRIMITIVE") { auxHtml = auxHtml + "<span class='badge alert-warning' draggable='true' ondragstart='drag(event)' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'>&nbsp;&nbsp;</span>&nbsp;&nbsp"; } else { auxHtml = auxHtml + "<span class='badge alert-warning' draggable='true' ondragstart='drag(event)' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'>&equiv;</span>&nbsp;&nbsp"; } if (countryIcons[field.module]) { auxHtml = auxHtml + "<div class='phoca-flagbox' style='width:26px;height:26px'><span class='phoca-flag " + countryIcons[field.module] + "'></span></div>&nbsp"; } auxHtml = auxHtml + "<a id='" + ind + panel.divElement.id + "-treeicon-" + field.conceptId + "' href='javascript:void(0);' style='color: inherit;text-decoration: inherit;'>"; auxHtml = auxHtml + "<span class='treeLabel selectable-row' data-module='" + field.module + "' data-concept-id='" + field.conceptId + "' data-term='" + field.defaultTerm + "'>" + field.defaultTerm + "</span></a></li>"; }); auxHtml = auxHtml + "</ul>"; } $(target).removeClass("glyphicon-refresh"); $(target).removeClass("icon-spin"); if (result.length > 0) { $(target).addClass("glyphicon-chevron-up"); } else { $(target).addClass("glyphicon-minus"); } $(target).closest("li").prepend(auxHtml); // $("#" + ind + panel.divElement.id + "-treeicon-" + conceptId).after(auxHtml); $(".treeButton").disableTextSelect(); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() {}); } this.loadMembers = function(returnLimit, skipTo, paginate) { var membersUrl = options.serverUrl + "/" + options.edition + "/" + options.release + "/members?referenceSet=" + panel.conceptId + "&limit=100"; if (skipTo > 0) { membersUrl = membersUrl + "&offset=" + skipTo; } else { $('#members-' + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><i class='glyphicon glyphicon-refresh icon-spin'></i></td></tr>"); } var total; if (panel.options.manifest) { // console.log(panel.options.manifest); $.each(panel.options.manifest.refsets, function(i, field) { if (field.conceptId == panel.conceptId) { if (field.count) { total = field.count; } } }); } if (typeof total != "undefined") { // console.log(total); // if (total < 25000){ paginate = 1; membersUrl = membersUrl + "&paginate=1"; //} } // console.log(membersUrl); if (xhrMembers != null) { xhrMembers.abort(); //console.log("aborting call..."); } xhrMembers = $.getJSON(membersUrl, function(result) { }).done(function(result) { var remaining = "asd"; if (typeof total == "undefined") total = result.total; if (total == skipTo) { remaining = 0; } else { if (total > (skipTo + returnLimit)) { remaining = total - (skipTo + returnLimit); } else { // if (result.details.total < returnLimit && skipTo != 0){ remaining = 0; // }else{ // remaining = result.details.total; // } } } if (remaining < returnLimit) { var returnLimit2 = remaining; } else { if (remaining != 0) { var returnLimit2 = returnLimit; } else { var returnLimit2 = 0; } } var context = { result: result, returnLimit: returnLimit2, remaining: remaining, divElementId: panel.divElement.id, skipTo: skipTo, panel: panel }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); if (result.total != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#members-" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#members-' + panel.divElement.id + "-resultsTable").html(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } else { $('#members-' + panel.divElement.id + "-resultsTable").append(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); panel.loadMembers(returnLimit2, skipTo + returnLimit, paginate); }); $("#members-" + panel.divElement.id + "-sort").unbind(); $("#members-" + panel.divElement.id + "-sort").click(function() { $("#members-" + panel.divElement.id + "-sort").blur(); panel.loadMembers(returnLimit, 0, 1); }); } else { if (skipTo != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#members-" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#members-' + panel.divElement.id + "-resultsTable").html(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } else { $('#members-' + panel.divElement.id + "-resultsTable").append(JST["views/conceptDetailsPlugin/tabs/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); panel.loadMembers(returnLimit2, skipTo + returnLimit, paginate); }); $("#members-" + panel.divElement.id + "-sort").unbind(); $("#members-" + panel.divElement.id + "-sort").click(function() { $("#members-" + panel.divElement.id + "-sort").blur(); panel.loadMembers(returnLimit, 0, 1); }); } else { $('#members-' + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } } $('#members-' + panel.divElement.id).find(".member-row").unbind(); $('#members-' + panel.divElement.id).find(".member-row").click(function(e) { var clickedConceptId = $(e.target).data("concept-id"); //var clickedTerm = $(e.target).data("term"); panel.conceptId = clickedConceptId; $('#details-tabs-' + panel.divElement.id + ' a:first').tab('show'); panel.updateCanvas(); }); }).fail(function() { $('#members-' + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); }); }; this.stripDiagrammingMarkup = function(htmlString) { if (!htmlString) htmlString = ""; htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-primitive-concept-compact"), 'g'), ""); htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-defined-concept-compact"), 'g'), ""); htmlString = htmlString.replace(new RegExp(panel.escapeRegExp("sct-attribute-compact"), 'g'), ""); return htmlString; }; this.escapeRegExp = function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); }; // this.setSubscription = function(subscriptionPanel) { // panel.subscription = subscriptionPanel; // $("#" + panel.divElement.id + "-subscribersMarker").css('color', subscriptionPanel.markerColor); // $("#" + panel.divElement.id + "-subscribersMarker").show(); // } // this.clearSubscription = function() { // panel.subscription = null; // $("#" + panel.divElement.id + "-subscribersMarker").hide(); // } this.removeSemtag = function(term) { if (term) { if (term.lastIndexOf("(") > 0) { return term.substr(0, term.lastIndexOf("(") - 1) } else { return term; } } } this.loadMarkers = function() { var auxMarker = "", right = 0, top = 0, aux = false, visible = false; $.each(componentsRegistry, function(i, field) { var panelId = field.divElement.id; if ($("#" + panelId + "-subscribersMarker").is(':visible')) { visible = true; } }); if (panel.subscribers.length == 0) { right = 14; $("#" + panel.divElement.id + "-ownMarker").hide(); } else { if (!visible) { $("#" + panel.divElement.id + "-ownMarker").hide(); } aux = true; } if ($("#" + panel.divElement.id + "-subscribersMarker").is(':visible')) { $("#" + panel.divElement.id + "-panelTitle").html($("#" + panel.divElement.id + "-panelTitle").html().replace(/&nbsp;/g, '')); if (aux) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); } $.each(panel.subscriptionsColor, function(i, field) { auxMarker = auxMarker + "<i class='glyphicon glyphicon-bookmark' style='color: " + field + "; top:" + top + "px; right: " + right + "px;'></i>"; $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); top = top + 5; right = right + 10; }); $("#" + panel.divElement.id + "-subscribersMarker").html(auxMarker); } } // Subsription methods this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; var alreadySubscribed = false; $.each(panel.subscriptionsColor, function(i, field) { if (field == panelToSubscribe.markerColor) { alreadySubscribed = true; } }); //console.log('Subscribing to id: ' + panelId, !alreadySubscribed); if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { // console.log("listening in " + panel.divElement.id); panel.conceptId = data.conceptId; if (data.showConcept) { $('a[href="#fh-cd1_canvas-pane"]').click(); } if ($("#home-children-" + panel.divElement.id + "-body").length > 0) {} else { panel.setupCanvas(); if (panel.loadMarkers) panel.loadMarkers(); } panel.updateCanvas(); // This creates a cycle // channel.publish(panel.divElement.id, { // term: data.term, // conceptId: data.conceptId, // source: data.source // }); }); panel.subscriptions.push(subscription); panelToSubscribe.subscribers.push(panel.divElement.id); panel.subscriptionsColor.push(panelToSubscribe.markerColor); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-ownMarker").show(); } this.unsubscribe = function(panelToUnsubscribe) { var aux = [], colors = [], unsubscribed = true; $.each(panel.subscriptionsColor, function(i, field) { if (field != panelToUnsubscribe.markerColor) { colors.push(field); } else { unsubscribed = false; } }); if (!unsubscribed) { panel.subscriptionsColor = colors; // console.log(panel.divElement.id); // console.log(panel.subscriptionsColor); colors = []; $.each(panelToUnsubscribe.subscribers, function(i, field) { if (field != panel.divElement.id) { aux.push(field); } }); panelToUnsubscribe.subscribers = aux; $.each(panelToUnsubscribe.subscriptionsColor, function(i, field) { colors.push(field); }); if (panelToUnsubscribe.subscribers.length == 0) { if (panelToUnsubscribe.subscriptions.length == 0) { $("#" + panelToUnsubscribe.divElement.id + "-subscribersMarker").hide(); } } else { // colors.push(panelToUnsubscribe.markerColor); } panelToUnsubscribe.subscriptionsColor = colors; // console.log(panelToUnsubscribe.divElement.id); // console.log(panelToUnsubscribe.subscriptionsColor); aux = []; $.each(panel.subscriptions, function(i, field) { if (panelToUnsubscribe.divElement.id == field.topic) { field.unsubscribe(); } else { aux.push(field); } }); panel.subscriptions = aux; if (panel.subscriptions.length == 0 && panel.subscribers.length == 0) { $("#" + panel.divElement.id + "-subscribersMarker").hide(); } } } this.setupOptionsPanel = function() { //var possibleSubscribers = []; //$.each(componentsRegistry, function(i, field){ // if (field.divElement.id != panel.divElement.id){ // var object = {}; // object.subscriptions = field.subscriptions; // object.id = field.divElement.id; // possibleSubscribers.push(object); // } //}); //var aux = false; //$.each(possibleSubscribers, function(i, field){ // aux = false; // $.each(panel.subscriptions, function(j, subscription){ // if (field.id == subscription.topic){ // aux = true; // } // }); // field.subscribed = aux; // aux = false; // $.each(field.subscriptions, function(i, subscription){ // if (subscription.topic == panel.divElement.id){ // aux = true; // } // }); // field.subscriptor = aux; //}); //panel.options.possibleSubscribers = possibleSubscribers; if (!panel.options.manifest) { $("#" + panel.divElement.id + "-modal-body").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); xhr = $.getJSON(options.serverUrl.replace("snomed", "") + "server/releases", function(result) { // nothing }).done(function(result) { $.each(result, function(i, field) { manifests.push(field); if (field.databaseName == options.edition) { panel.options.manifest = field; } }); var context = { options: panel.options, divElementId: panel.divElement.id }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('ifIn', function(elem, list, options) { if (list.indexOf(elem) > -1) { return options.fn(this); } return options.inverse(this); }); $("#" + panel.divElement.id + "-modal-body").html(JST["views/conceptDetailsPlugin/options.hbs"](context)); }); } else { var context = { options: panel.options, divElementId: panel.divElement.id }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('ifIn', function(elem, list, options) { if (list.indexOf(elem) > -1) { return options.fn(this); } return options.inverse(this); }); $("#" + panel.divElement.id + "-modal-body").html(JST["views/conceptDetailsPlugin/options.hbs"](context)); } } this.readOptionsPanel = function() { panel.options.displaySynonyms = $("#" + panel.divElement.id + "-displaySynonymsOption").is(':checked'); panel.options.showIds = $("#" + panel.divElement.id + "-displayIdsOption").is(':checked'); panel.options.displayChildren = $("#" + panel.divElement.id + "-childrenOption").is(':checked'); panel.options.hideNotAcceptable = $("#" + panel.divElement.id + "-hideNotAcceptableOption").is(':checked'); panel.options.displayInactiveDescriptions = $("#" + panel.divElement.id + "-displayInactiveDescriptionsOption").is(':checked'); panel.options.diagrammingMarkupEnabled = $("#" + panel.divElement.id + "-diagrammingMarkupEnabledOption").is(':checked'); panel.options.selectedView = $("#" + panel.divElement.id + "-relsViewOption").val(); panel.options.langRefset = []; $.each($("#" + panel.divElement.id).find(".langOption"), function(i, field) { if ($(field).is(':checked')) { panel.options.langRefset.push($(field).val()); } }); //console.log(panel.options.langRefset); //panel.options.langRefset = $("#" + panel.divElement.id + "-langRefsetOption").val(); panel.options.displayChildren = $("#" + panel.divElement.id + "-displayChildren").is(':checked'); //$.each(panel.options.possibleSubscribers, function (i, field){ // field.subscribed = $("#" + panel.divElement.id + "-subscribeTo-" + field.id).is(':checked'); // field.subscriptor = $("#" + panel.divElement.id + "-subscriptor-" + field.id).is(':checked'); // var panelToSubscribe = {}; // $.each(componentsRegistry, function(i, panelS){ // if (panelS.divElement.id == field.id){ // panelToSubscribe = panelS; // } // }); // if (field.subscribed){ // panel.subscribe(panelToSubscribe); // }else{ // panel.unsubscribe(panelToSubscribe); // } // if (field.subscriptor){ // panelToSubscribe.subscribe(panel); // }else{ // panelToSubscribe.unsubscribe(panel); // } //}); $.each(componentsRegistry, function(i, field) { if (field.loadMarkers) field.loadMarkers(); }); panel.updateCanvas(); } } function updateCD(divElementId, conceptId) { $.each(componentsRegistry, function(i, field) { //console.log(field.divElement.id + ' == ' + divElementId.id); if (field.divElement.id == divElementId) { field.conceptId = conceptId; field.updateCanvas(); channel.publish(field.divElement.id, { term: field.term, conceptId: field.conceptId, module: field.module, source: field.divElement.id }); } }); $('.history-button').popover('hide'); } //function cancelSubscription(divElementId1, divElementId2) { // var d1; // var d2; // $.each(componentsRegistry, function(i, field) { // if (field.divElement.id == divElementId1) { // d1 = field; // } else if (field.divElement.id == divElementId2) { // d2 = field; // } // }); // d1.unsubscribe(d2); // $(d2.divElement).find('.linker-button').popover('toggle'); //} function getRandomColor() { var letters = '0123456789ABCDEF'.split(''); var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.round(Math.random() * 15)]; } return color; } (function($) { $.fn.addConceptDetails = function(conceptId, options) { this.filter("div").each(function() { var cd = new conceptDetails(this, conceptId, options); cd.setupCanvas(); }); }; }(jQuery)); $(document).keypress(function(event) { if (event.which == '13') { event.preventDefault(); } }); /** * Updated by rda on 2017-12-15. */ countryIcons = { '999000041000000102': 'gb', '999000011000000103': 'gb', '999000021000000109': 'gb', '999000031000000106': 'gb', '450829007': 'es', '11000221109': 'ar', '11000220105': 'ie', "900000001000122104": "es-ES", '731000124108': 'us', '5991000124107': 'us', '161771000036108': 'au', '32570231000036109': 'au', '32506021000036107': 'au', '32570491000036106': 'au', '45991000052106': 'se', '554471000005108': 'dk', '9999999998': 'gmdn', '466707005': 'mdp', '11000146104': 'nl', '20621000087109': 'ca', '19481000087107': 'ca', '20611000087101': 'ca', '22091000087100': 'ca', '5641000179103': 'uy', '5631000179106': 'uy', '11000172109': 'be', '21000210109': 'nz', '51000202101': 'no' }; Handlebars.registerHelper('countryIcon', function(moduleId) { return countryIcons[moduleId]; }); function drawConceptDiagram (concept, div, options, panel) { var svgIsaModel = []; var svgAttrModel = []; var axioms = []; if (options.selectedView == "stated") { $.each(concept.statedRelationships, function(i, field) { if (field.active == true) { if (field.type.conceptId == 116680003) { svgIsaModel.push(field); } else { svgAttrModel.push(field); } } }); $.each(concept.gciAxioms, function (i, axiom) { var axiomToPush = {}; axiomToPush.relationships = []; axiomToPush.type = 'gci'; $.each(axiom.relationships, function (i, field) { if (field.type.conceptId === '116680003') { axiomToPush.relationships.push(field); } else { axiomToPush.relationships.push(field); } }); axioms.push(axiomToPush); }); $.each(concept.classAxioms, function (i, axiom) { var axiomToPush = { relationships : [], type : 'add', definitionStatus: axiom.definitionStatus }; $.each(axiom.relationships, function (i, field) { if (field.type.conceptId === '116680003') { axiomToPush.relationships.push(field); } else { axiomToPush.relationships.push(field); } }); axioms.push(axiomToPush); }); } else { if (concept.relationships) { $.each(concept.relationships, function (i, field) { if (field.active == true) { if (field.type.conceptId == 116680003) { svgIsaModel.push(field); } else { svgAttrModel.push(field); } } }); } } var context = { divElementId: div.attr('id') }; //console.log(context); div.html(JST["views/conceptDetailsPlugin/tabs/details/diagram.hbs"](context)); var parentDiv = $("#" + div.attr('id') + "-diagram-body"); var height = 350; var width = 700; $.each(svgIsaModel, function (i, field) { height = height + 50; width = width + 80; }); $.each(svgAttrModel, function (i, field) { height = height + 65; width = width + 110; }); if(options.selectedView === 'stated'){ $.each(concept.classAxioms, function (i, axiom) { height = height + 40; width = width + 80; $.each(axiom.relationships, function (i, field) { height = height + 55; width = width + 110; }); }); $.each(concept.gciAxioms, function (i, axiom) { height = height + 40; width = width + 80; $.each(axiom.relationships, function (i, field) { height = height + 55; width = width + 110; }); }); } // parentDiv.svg('destroy'); parentDiv.svg({ settings: { width: width + 'px', height: height + 'px'}}); var svg = parentDiv.svg('get'); loadDefs(svg); var x = 10; var y = 10; var maxX = 10; var sctClass = ""; if (concept.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } //console.log("In draw: " + concept.defaultTerm + " " + concept.conceptId + " " + sctClass); var rect1 = drawSctBox(svg, x, y, concept.fsn, concept.conceptId, sctClass); x = x + 90; y = y + rect1.getBBox().height + 40; if(options.selectedView === 'stated' && svgIsaModel && svgIsaModel.length > 0 || options.selectedView != 'stated'){ var circle1; if (concept.definitionStatus == "PRIMITIVE") { circle1 = drawSubsumedByNode(svg, x, y); } else { circle1 = drawEquivalentNode(svg, x, y); } connectElements(svg, rect1, circle1, 'bottom-50', 'left'); x = x + 55; var circle2 = drawConjunctionNode(svg, x, y); connectElements(svg, circle1, circle2, 'right', 'left', 'LineMarker'); x = x + 40; y = y - 18; } if (!svgIsaModel || svgIsaModel.length === 0) { x = x + 20; y = y + 3; } maxX = ((maxX < x) ? x : maxX); // load stated parents sctClass = "sct-defined-concept"; $.each(svgIsaModel, function(i, relationship) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectParent = drawSctBox(svg, x, y, relationship.target.fsn.term, relationship.target.conceptId, sctClass); // $("#" + rectParent.id).css({"top": // (rectParent.outerHeight()/2) + "px"}); connectElements(svg, circle2, rectParent, 'center', 'left', 'ClearTriangle'); y = y + rectParent.getBBox().height + 25; maxX = ((maxX < x + rectParent.getBBox().width + 50) ? x + rectParent.getBBox().width + 50 : maxX); }); // load ungrouped attributes var maxRoleNumber = 0; $.each(svgAttrModel, function(i, relationship) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } if (relationship.groupId == 0) { var rectAttr = drawSctBox(svg, x, y, relationship.type.fsn.term,relationship.type.conceptId, "sct-attribute"); connectElements(svg, circle2, rectAttr, 'center', 'left'); var rectTarget = drawSctBox(svg, x + rectAttr.getBBox().width + 50, y, relationship.target.fsn.term,relationship.target.conceptId, sctClass); connectElements(svg, rectAttr, rectTarget, 'right', 'left'); y = y + rectTarget.getBBox().height + 25; maxX = ((maxX < x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50) ? x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50 : maxX); } else { if (relationship.groupId > maxRoleNumber) { maxRoleNumber = relationship.groupId; } } }); y = y + 15; for (var i = 1; i <= maxRoleNumber; i++) { var groupNode = drawAttributeGroupNode(svg, x, y); connectElements(svg, circle2, groupNode, 'center', 'left'); var conjunctionNode = drawConjunctionNode(svg, x + 55, y); connectElements(svg, groupNode, conjunctionNode, 'right', 'left'); $.each(svgAttrModel, function(m, relationship) { if (relationship.groupId == i) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectRole = drawSctBox(svg, x + 85, y - 18, relationship.type.fsn.term, relationship.type.conceptId,"sct-attribute"); connectElements(svg, conjunctionNode, rectRole, 'center', 'left'); var rectRole2 = drawSctBox(svg, x + 85 + rectRole.getBBox().width + 30, y - 18, relationship.target.fsn.term,relationship.target.conceptId, sctClass); connectElements(svg, rectRole, rectRole2, 'right', 'left'); y = y + rectRole2.getBBox().height + 25; maxX = ((maxX < x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50) ? x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50 : maxX); } }); } $.each(axioms, function (i, axiom) { console.log(axiom); x = 100; y = y -3; var circle1; if(axiom.type === "gci"){ circle1 = drawSubsumesNode(svg, x, y); } else if(axiom.type !== "gci" && axiom.definitionStatus === "FULLY_DEFINED"){ circle1 = drawEquivalentNode(svg, x, y); } else{ console.log('drawing 2'); circle1 = drawSubsumedByNode(svg, x, y); } connectElements(svg, rect1, circle1, 'bottom-50', 'left'); x = x + 55; var circle2 = drawConjunctionNode(svg, x, y); connectElements(svg, circle1, circle2, 'right', 'left', 'LineMarker'); x = x + 40; y = y - 18; maxX = ((maxX < x) ? x : maxX); var axiomRoleNumber = 0; $.each(axiom.relationships, function (i, relationship) { console.log('here'); if(relationship.type.conceptId === '116680003'){ if (relationship.target.definitionStatus === "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectParent = drawSctBox(svg, x, y, relationship.target.fsn.term, relationship.target.conceptId, sctClass); // $("#" + rectParent.id).css({"top": // (rectParent.outerHeight()/2) + "px"}); connectElements(svg, circle2, rectParent, 'center', 'left', 'ClearTriangle'); y = y + rectParent.getBBox().height + 25; maxX = ((maxX < x + rectParent.getBBox().width + 50) ? x + rectParent.getBBox().width + 50 : maxX); } else{ if (relationship.target.definitionStatus === "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } if (relationship.groupId === 0) { var rectAttr = drawSctBox(svg, x, y, relationship.type.fsn.term, relationship.type.conceptId, "sct-attribute"); connectElements(svg, circle2, rectAttr, 'center', 'left'); var rectTarget = drawSctBox(svg, x + rectAttr.getBBox().width + 50, y, relationship.target.fsn.term, relationship.target.conceptId, sctClass); connectElements(svg, rectAttr, rectTarget, 'right', 'left'); y = y + rectTarget.getBBox().height + 25; maxX = ((maxX < x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50) ? x + rectAttr.getBBox().width + 50 + rectTarget.getBBox().width + 50 : maxX); } else { if (relationship.groupId > axiomRoleNumber) { axiomRoleNumber = relationship.groupId; } } } }); y = y + 15; for (var i = 1; i <= axiomRoleNumber; i++) { var groupNode = drawAttributeGroupNode(svg, x, y); connectElements(svg, circle2, groupNode, 'center', 'left'); var conjunctionNode = drawConjunctionNode(svg, x + 55, y); connectElements(svg, groupNode, conjunctionNode, 'right', 'left'); $.each(axiom.relationships, function (m, relationship) { if (relationship.groupId === i) { if (relationship.target.definitionStatus == "PRIMITIVE") { sctClass = "sct-primitive-concept"; } else { sctClass = "sct-defined-concept"; } var rectRole = drawSctBox(svg, x + 85, y - 18, relationship.type.fsn.term, relationship.type.conceptId, "sct-attribute"); connectElements(svg, conjunctionNode, rectRole, 'center', 'left'); var rectRole2 = drawSctBox(svg, x + 85 + rectRole.getBBox().width + 30, y - 18, relationship.target.fsn.term, relationship.target.conceptId, sctClass); connectElements(svg, rectRole, rectRole2, 'right', 'left'); y = y + rectRole2.getBBox().height + 25; maxX = ((maxX < x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50) ? x + 85 + rectRole.getBBox().width + 30 + rectRole2.getBBox().width + 50 : maxX); } }); } }); var svgCode = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' + parentDiv.html(); svgCode = svgCode.substr(0, svgCode.indexOf("svg") + 4) + ' xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://web.resource.org/cc/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" ' + svgCode.substr(svgCode.indexOf("svg") + 4) svgCode = svgCode.replace('width="1000px" height="2000px"', 'width="' + maxX + '" height="' + y + '"'); var b64 = Base64.encode(svgCode); $("#" + div.attr('id') + "-download-button").disableTextSelect(); $("#" + div.attr('id') + "-progress-button").disableTextSelect(); $("#" + div.attr('id') + "-png-button").disableTextSelect(); $("#" + div.attr('id') + "-svg-button").disableTextSelect(); $("#" + div.attr('id') + "-download-button").removeClass('disabled'); $("#" + div.attr('id') + "-download-button").unbind().click(function(event) { $("#" + div.attr('id') + "-download-button").hide(); $("#" + div.attr('id') + "-progress-button").show(); $.post(options.serverUrl.replace("snomed", "") + "util/svg2png", { svgContent: svgCode}).done(function( response ) { //console.log(response); $("#" + div.attr('id') + "-progress-button").hide(); $("#" + div.attr('id') + "-png-button").show(); $("#" + div.attr('id') + "-svg-button").show(); $("#" + div.attr('id') + "-png-button").unbind().click(function(event) { window.open(options.serverUrl.replace("snomed", "") + response); }); $("#" + div.attr('id') + "-svg-button").unbind().click(function(event) { window.open(options.serverUrl.replace("snomed", "") + response.replace(".png", ".svg")); }); //$(div).prepend($("<a href-lang='image/svg+xml' href=options.serverUrl.replace("snomed", "")+response+"' download='diagram.png'>Download as PNG</a>&nbsp;&nbsp;&nbsp;")); }).fail(function() { //console.log("Error"); }); }); if (panel.options.selectedView == "stated") { $("#" + div.attr('id') + '-stated-button-d').unbind(); $("#" + div.attr('id') + '-inferred-button-d').unbind(); $("#" + div.attr('id') + '-stated-button-d').addClass("btn-primary"); $("#" + div.attr('id') + '-stated-button-d').removeClass("btn-default"); $("#" + div.attr('id') + '-inferred-button-d').addClass("btn-default"); $("#" + div.attr('id') + '-inferred-button-d').removeClass("btn-primary"); $("#" + div.attr('id') + '-inferred-button-d').click(function (event) { panel.options.selectedView = "inferred"; panel.updateCanvas(); }); } else { $("#" + div.attr('id') + '-stated-button-d').unbind(); $("#" + div.attr('id') + '-inferred-button-d').unbind(); $("#" + div.attr('id') + '-inferred-button-d').addClass("btn-primary"); $("#" + div.attr('id') + '-inferred-button-d').removeClass("btn-default"); $("#" + div.attr('id') + '-stated-button-d').addClass("btn-default"); $("#" + div.attr('id') + '-stated-button-d').removeClass("btn-primary"); $("#" + div.attr('id') + '-stated-button-d').click(function (event) { panel.options.selectedView = "stated"; panel.updateCanvas(); }); } //$(div).prepend($("<a href-lang='image/svg+xml' href='data:image/svg+xml;base64,\n"+b64+"' download='diagram.svg'>Download as SVG</a>")); } function saveAsPng(svg) { //Create PNG Image //Get the svg //Create the canvas element var canvas = document.createElement('canvas'); canvas.id = "canvas"; document.body.appendChild(canvas); //Load the canvas element with our svg canvg(document.getElementById('canvas'), svg); //Save the svg to png Canvas2Image.saveAsPNG(canvas); //Clear the canvas canvas.width = canvas.width; } !function ($) { /* ======================= * Popover jQuery Plugin * ======================= * Current version: v1.0.0, Last updated: 01-28-2013 * Description: Cross-browser, mobile compatible popover. * * Author: Jordan Kelly * Github: https://github.com/FoundOPS/popover * * Compatible browsers: IE 9+, Chrome ?+, FF 3.6+, Android 2.3+, iOS 4+ * * jQuery functions: * $(selector).popover([methods] or [config]); * $(selector).optionsPopover([methods] or [config]); * * Config parameters: Example usage - $(selector).popover({..., fontColor: "#000", ...}); * id - When passed for initial menu, id must be the same as the id/class used in selector. * eg) "#popoverButton" * * title - Title to be displayed on header. * * contents - popover: An html string to be inserted. * - optionsPopover: An array of row data. * //TODO: Document more. * * backgroundColor - Sets the background color for all popups. Accepts hex and color keywords. * eg) "#000000", "black", etc. * * fontColor - Sets the font color for all popups. Accepts hex and color keywords. * eg) "#000000", "black", etc. * * borderColor - Sets the border color for all popups. Accepts hex and color keywords. * eg) "#000000", "black", etc. * * keepData - Boolean that indicates if header and content should be cleared/set on visible. * WARNING: MAY BE REMOVED IN FUTURE VERSIONS. * eg) truthy or falsesy values * * childToAppend - A documentFragment or dom element to be appended after content is set. * WARNING: MAY BE REMOVED IN FUTURE VERSIONS. * eg) * * onCreate - A function to be called after popover is created. * eg) function(){ console.log("popover has been created!"); } * * onVisible - A function to be called after popover is visible. * eg) function(){ console.log("popover is visible!"); } * * disableHeader - Boolean that indicates if a header should not be used on parent listener. * eg) Truthy/Falsey values * * Methods: Example usage - $(selector).popover("methodName", argument1, argument2 ...); * [Internal] - Functions needed for setup/initialization. * _popoverInit - Internal function used to setup popover. * Arguments: options_config, popover_instance * _optionsPopoverInit - Internal function used to setup optionsPopover. * Arguments: options_config, popover_instance * [Public] * disableHeader - Function used to disable header for a popover instance. * Arguments: popover_instance * enableHeader - Function used to enable header for a popover instance. * Arguments: popover_instance * lockPopover - Function used to lock all popovers. Prevents popover from opening/closing. * Arguments: none * unlockPopover - Function used to unlock all popovers. * Arguments: none * addMenu - Function used to add a new menu. Menus can be accessed by all popover instances. * Arguments: id, title, contents * closePopover - Function used to close popover. * Arguments: none * [Private] - Note: Only use if you have to. * _getPopoverClass - Function used to return internal Popover class. * Arguments: none * * Triggers: Currently all events are namespaced under popover.* This may change in future versions. * popover.created - Fired when popup is created and placed in DOM. * popover.listenerClicked - Fired when root popup listener is clicked. * popover.action - Fired when a menu changes. * Arguments: DOM Element causing action. * popover.visible - Fired when popover is visible. * popover.updatePositions - Fired when left and top positions are updated. * popover.resize - Fired when popover is resized. * popover.closing - Fired before popover closes. * popover.setContent - Fired after popover's contenet is set. ================================================================================================================*/ var methods = { _init: function(options, popover) { //Theme modifiers if(typeof(options.backgroundColor) !== 'undefined'){ Popover.setBackgroundColor(options.backgroundColor); } if(typeof(options.fontColor) !== 'undefined'){ Popover.setFontColor(options.fontColor); } if(typeof(options.borderColor) !== 'undefined'){ Popover.setBorderColor(options.borderColor); } //Functionality modifiers //TODO: Rename disableBackButton option. if(typeof(options.disableBackButton) !== "undefined"){ if(options.disableBackButton === true){ popover.disableBackButton(); }else if(options.disableBackButton === false){ popover.enableBackButton(); } } if(typeof(options.enableBackButton) !== "undefined"){ if(options.enableBackButton === true){ popover.enableBackButton(); }else if(options.enableBackButton === false){ popover.disableBackButton(); } } if(typeof(options.disableHeader) !== 'undefined'){ if(options.disableHeader === true){ popover.disableHeader(); }else if(options.disableHeader === false){ popover.enableHeader(); } } if(typeof(options.keepData) !== 'undefined'){ popover.keepData(options.keepData); } if(typeof(options.childToAppend) !== 'undefined'){ popover.childToAppend = options.childToAppend; } //Callbacks if(typeof(options.onCreate) !== 'undefined'){ popover._onCreate = options.onCreate; } if(typeof(options.onVisible) !== 'undefined'){ popover._onVisible = options.onVisible; } Popover.addMenu(options.id, options.title, options.contents); }, _popoverInit: function(options) { var popover = new Popover(this.selector); methods._init(options, popover); return popover; }, _optionsPopoverInit: function (options) { var popover = new OptionsPopover(this.selector); methods._init(options, popover); return popover; }, //Requires instance to be passed. disableHeader: function(popover) { popover.disableHeader(); }, //Requires instance to be passed. enableHeader: function(popover) { popover.enableHeader(); }, //Static functions lockPopover: function() { Popover.lockPopover(); }, unlockPopover: function() { Popover.unlockPopover(); }, addMenu: function (menu) { Popover.addMenu(menu.id, menu.title, menu.contents); }, closePopover: function () { Popover.closePopover(); }, _getPopoverClass: function() { return Popover; } }; $.fn.optionsPopover = function (method) { // Create some defaults, extending them with any options that were provided //var settings = $.extend({}, options); // Method calling logic if (methods[method]) { return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods._optionsPopoverInit.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.optionsPopover'); } return this.each(function () {}); }; $.fn.ppopover = function (method) { // Create some defaults, extending them with any options that were provided //var settings = $.extend({}, options); // Method calling logic if (methods[method]) { return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods._popoverInit.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.popover'); } return this.each(function () {}); }; //////////////////////////////////////////////////////////// // Popover Block //////////////////////////////////////////////////////////// /** Popover CONSTRUCTOR **/ function Popover(popoverListener) { this.constructor = Popover; //Set this popover's number and increment Popover count. this.popoverNumber = ++Popover.popoverNum; //Class added to detect clicks on primary buttons triggering popovers. this.popoverListenerID = "popoverListener"+this.popoverNumber; this.isHeaderDisabled = true; this.isDataKept = false; this.hasBeenOpened = false; var thisPopover = this; var listenerElements = $(popoverListener); listenerElements.addClass(this.popoverListenerID); listenerElements.css("cursor", "pointer"); listenerElements.click(function (e) { thisPopover.toggleVisible(e, $(this)); $(document).trigger("popover.listenerClicked"); }); } Popover.prototype.disableHeader = function() { this.isHeaderDisabled = true; }; Popover.prototype.enableHeader = function() { this.isHeaderDisabled = false; }; Popover.prototype.disablePopover = function() { this.isDisabled = true; }; Popover.prototype.enablePopover = function() { this.isDisabled = false; }; Popover.prototype.keepData = function(bool){ this.isDataKept = bool; }; Popover.prototype.appendChild = function(){ var child = this.childToAppend; if(!child)return; $("#popoverContent")[0].appendChild(child); }; Popover.prototype.toggleVisible = function (e, clicked) { Popover.lastPopoverClicked = this; var clickedDiv = $(clicked); if (!clickedDiv) { //console.log("ERROR: No element clicked!"); return; } var popoverWrapperDiv = $("#popoverWrapper"); if (popoverWrapperDiv.length === 0) { //console.log("Popover not initialized; initializing."); popoverWrapperDiv = this.createPopover(); if (popoverWrapperDiv.length === 0) { //console.log("ERROR: Failed to create Popover!"); return; } } //TODO: In the future, add passed id to selected div's data-* or add specific class. var id = clickedDiv.attr("id"); var identifierList = clickedDiv.attr('class').split(/\s+/); //NOTE: identifierList contains the clicked element's id and class names. This is used to find its // associated menu. The next version will have a specialized field to indicate this. identifierList.push(id); //console.log("List: "+identifierList); //TODO: Fix repetition. if ($("#popover").is(":visible") && Popover.lastElementClick) { if (clickedDiv.is("#" + Popover.lastElementClick)) { //console.log("Clicked on same element!"); //console.log("Last clicked: " + Popover.lastElementClick); Popover.closePopover(); return; } //console.log("Clicked on different element!"); Popover.closePopover(); } //Blocking statement that waits until popover closing animation is complete. $("#popover").promise().done(function () {}); //If popover is locked, don't continue actions. if(Popover.isLocked||this.isDisabled)return; //Update content this.populate(identifierList); clickedDiv.trigger("popover.action", clickedDiv); if(Popover.backgroundColor){ $("#popoverHeader").css("backgroundColor", Popover.backgroundColor); $("#popoverContent").css("backgroundColor", Popover.backgroundColor); } if(Popover.fontColor){ $("#popover").css("color", Popover.fontColor); //TODO: Trigger color change event and move to OptionsPopover. $("#popover a").css("color", Popover.fontColor); } if(Popover.borderColor){ $("#popoverHeader").css("border-color", Popover.borderColor); $("#popoverContent").css("border-color", Popover.borderColor); $(".popoverContentRow").css("border-color", Popover.borderColor); } //Make popover visible $("#popover").stop(false, true).fadeIn('fast'); $("#popoverWrapper").css("visibility", "visible"); $("#popover").promise().done(function () {}); popoverWrapperDiv.trigger("popover.visible"); if(this._onVisible){ //console.log("LOG: Executing onVisible callback."); this._onVisible(); } if((this.isDataKept && !this.hasBeenOpened) || (!this.isDataKept)){ var child = this.childToAppend; if(child){ this.appendChild(child); } } this.hasBeenOpened = true; //Update left, right and caret positions for popover. //NOTE: Must be called after popover.visible event, in order to trigger jspScrollPane update. Popover.updatePositions(clickedDiv); Popover.lastElementClick = clickedDiv.attr("id"); }; Popover.updatePositions = function(target){ Popover.updateTopPosition(target); Popover.updateLeftPosition(target); $(document).trigger("popover.updatePositions"); }; Popover.updateTopPosition = function(target){ var top = Popover.getTop(target); $("#popoverWrapper").css("padding-top", top + "px"); }; Popover.updateLeftPosition = function(target){ var offset = Popover.getLeft(target); $("#popoverWrapper").css("left", offset.popoverLeft); Popover.setCaretPosition(offset.targetLeft - offset.popoverLeft + Popover.padding); }; //Function returns the left offset of the popover and target element. Popover.getLeft = function (target) { var popoverWrapperDiv = $("#popoverWrapper"); Popover.currentTarget = target; var targetLeft = target.offset().left + target.outerWidth() / 2; var rightOffset = targetLeft + popoverWrapperDiv.outerWidth() / 2; var offset = targetLeft - popoverWrapperDiv.outerWidth() / 2 + Popover.padding + 1; var windowWidth = $(window).width(); Popover.offScreenX = false; if (offset < 0) { Popover.offScreenX = true; offset = Popover.padding; } else if (rightOffset > windowWidth) { Popover.offScreenX = true; offset = windowWidth - popoverWrapperDiv.outerWidth(); } //Returns left offset of popover from window. return {targetLeft: targetLeft, popoverLeft: offset}; }; Popover.getTop = function(target){ var caretHeight = $("#popoverArrow").height(); //TODO: Make more readable. //If absolute position from mobile css, don't offset from scroll. var scrollTop = ($("#popoverWrapper").css("position")==="absolute")?0:$(window).scrollTop(); var targetTop = target.offset().top - scrollTop; var targetBottom = targetTop + target.outerHeight(); var popoverTop = targetBottom + caretHeight; var windowHeight = $(window).height(); var popoverContentHeight = $("#popoverContent").height(); var popoverHeight = popoverContentHeight + $("#popoverHeader").outerHeight() + caretHeight; Popover.above = false; Popover.offScreenY = false; //If popover is past the bottom of the screen. //else if popover is above the top of the screen. if (windowHeight < targetBottom + popoverHeight) { Popover.offScreenY = true; //If there is room above, move popover above target //else keep popover bottom at bottom of screen. if(targetTop >= popoverHeight){ popoverTop = targetTop - popoverHeight; Popover.above = true; }else{ popoverTop = windowHeight - popoverHeight; } } else if (popoverTop < 0) { Popover.offScreenY = true; popoverTop = Popover.padding + caretHeight; } /* //Debug logs console.log("------------------------------------------------------------"); console.log("Caret Height: " + caretHeight); console.log("TargetTop: " + targetTop); console.log("Popover Cont Height: " + popoverContentHeight); console.log("Cont Height: " + $("#popoverContent").height()); console.log("Header Height: " + $("#popoverHeader").outerHeight()); console.log("targetBottom: " + targetBottom); console.log("popoverHeight: " + popoverHeight); console.log("popoverBottom: " + (targetBottom + popoverHeight)); console.log("Popover Height: " + $("#popover").height()); console.log("PopoverWrapper Height: " + $("#popoverWrapper").height()); console.log("PopoverWrapper2 Height: " + $("#popoverWrapper").height(true)); console.log("popoverTop: " + popoverTop); console.log("windowHeight: " + windowHeight); console.log("offScreenY: " + Popover.offScreenY); console.log("Popover.above: " + Popover.above); console.log("\n"); */ return popoverTop; }; Popover.setCaretPosition = function(offset){ //console.log("LOG: Setting caret position."); var caretPos = "50%"; var caret = $("#popoverArrow"); if (Popover.offScreenX) { caretPos = offset; } //Moves carrot on popover div. caret.css("left", caretPos); //console.log("LOG: Popover.above: "+Popover.above); if(Popover.above){ var popoverHeight = $("#popoverContent").outerHeight() - 4; $("#popoverArrow").css("margin-top", popoverHeight+"px") .addClass("flipArrow") .html("▼"); }else{ $("#popoverArrow").css("margin-top", "") .removeClass("flipArrow") .html("▲"); } Popover.caretLeftOffset = caretPos; }; // createPopover: Prepends popover to dom Popover.prototype.createPopover = function () { //Creates popover div that will be populated in the future. var popoverWrapperDiv = $(document.createElement("div")); popoverWrapperDiv.attr("id", "popoverWrapper"); var s = "<div id='popover'>" + "<div id='popoverArrow'>▲</div>" + "<div id='currentPopoverAction' style='display: none;'></div>" + "<div id='popoverContentWrapper'>" + "<div id='popoverContent'></div>" + "</div>" + "</div>"; popoverWrapperDiv.html(s); popoverWrapperDiv.find("#popover").css("display", "none"); //Appends created div to page. $("body").prepend(popoverWrapperDiv); //Window resize listener to check if popover is off screen. $(window).on('resize', function () { if ($("#popover").is(":visible")) { Popover.updatePositions(Popover.currentTarget); } var popoverWrapperDiv = $("#popoverWrapper"); if(popoverWrapperDiv.css("position")==="absolute"){ popoverWrapperDiv.css("height", $(document).height()); }else{ popoverWrapperDiv.css("height", ""); } }); //Click listener to detect clicks outside of popover $('html') .on('click touchend', function (e) { var clicked = $(e.target); //TODO: Return if not visible. var popoverHeaderLen = clicked.parents("#popoverHeader").length + clicked.is("#popoverHeader") ? 1 : 0; var popoverContentLen = (clicked.parents("#popoverContentWrapper").length && !clicked.parent().is("#popoverContentWrapper")) ? 1 : 0; var isListener = clicked.parents("."+Popover.lastPopoverClicked.popoverListenerID).length + clicked.is("."+Popover.lastPopoverClicked.popoverListenerID) ? 1 : 0; if (popoverHeaderLen === 0 && popoverContentLen === 0 && isListener === 0) { Popover.closePopover(); } } ); var popoverContentWrapperDiv = $("#popoverContentWrapper"); var throttleTimeout; $(window).bind('resize', function () { if ($.browser.msie) { if (!throttleTimeout) { throttleTimeout = setTimeout(function () { popoverContentWrapperDiv.trigger("popover.resize"); throttleTimeout = null; }, 50 ); } } else { popoverContentWrapperDiv.trigger("popover.resize"); } }); popoverContentWrapperDiv.trigger("popover.created"); if(this._onCreate)this._onCreate(); //Function also returns the popover div for ease of use. return popoverWrapperDiv; }; //Closes the popover Popover.closePopover = function () { if(Popover.isLocked)return; Popover.lastElementClick = null; $(document).trigger("popover.closing"); Popover.history = []; $("#popover").stop(false, true).fadeOut('fast'); $("#popoverWrapper").css("visibility", "hidden"); }; Popover.getAction = function () { return $("#currentPopoverAction").html(); }; Popover.setAction = function (id) { $("#currentPopoverAction").html(id); }; Popover.prototype.disableBackButton = function(){ this.isBackEnabled = false; }; Popover.prototype.enableBackButton = function(){ this.isBackEnabled = true; }; Popover.prototype.previousPopover = function(){ Popover.history.pop(); if (Popover.history.length <= 0) { Popover.closePopover(); return; } var menu = Popover.history[Popover.history.length - 1]; this.populateByMenu(menu); }; //Public setter function for static var title and sets title of the html popover element. Popover.setTitle = function (t) { Popover.title = t; $("#popoverTitle").html(t); }; // Public getter function that returns a popover menu. // Returns: Popover menu object if found, null if not. // Arguments: id - id of menu to lookup Popover.getMenu = function (id) { //Searches for a popover data object by the id passed, returns data object if found. var i; for (i = 0; i < Popover.menus.length; i += 1) { //console.log("LOG: getMenu - Popover.menus["+i+"]: "+Popover.menus[i].id); if (Popover.menus[i].id === id) { return Popover.menus[i]; } } //Null result returned if popover data object is not found. //console.log("LOG: getMenu - No data found, returning null."); return null; }; Popover.addMenu = function (id, title, contents) { Popover.menus.push({'id': id, 'title': title, 'contents': contents}); }; Popover.prototype.populateByMenu = function(menu){ $(document).trigger('popover.populating'); this.lastContentHeight = Popover.getPopoverContentHeight(); if(!this.isDataKept){ this.clearData(); } //If data is kept, header and other content will still be in dom, so don't do either. if(!this.isHeaderDisabled && !this.isDataKept) { this.insertHeader(); }else{ this.removeHeader(); } var popoverDisplay = $("#popover").css("display"); if(!this.isDataKept || !this.hasBeenOpened)this.setData(menu); this.currentContentHeight = Popover.getPopoverContentHeight(); if(Popover.above && popoverDisplay!=="none"){ var oldPopoverTop = parseInt($("#popoverWrapper").css("padding-top"), 10); var contentHeightDelta = this.currentContentHeight - this.lastContentHeight; var popoverTop = oldPopoverTop - (contentHeightDelta); $("#popoverWrapper").css("padding-top", popoverTop + "px"); Popover.setCaretPosition(Popover.caretLeftOffset); } return true; }; //Public void function that populates setTitle and setContent with data found by id passed. Popover.prototype.populate = function(identifierList){ //console.log(identifierList); var newMenu = null; var i=0; for(i; i<identifierList.length; i++){ newMenu = Popover.getMenu(identifierList[i]); if(newMenu){ //console.log("Found menu! id: "+identifierList[i]); break; } } if (!newMenu) { //console.log("ID not found."); return false; } Popover.history.push(newMenu); return this.populateByMenu(newMenu); }; Popover.getPopoverContentHeight = function(){ var popoverDisplay = $("#popover").css("display"); $("#popover").show(); var popoverHeight = $("#popoverContent").height(); $("#popover").css("display",popoverDisplay); return popoverHeight; }; Popover.prototype.insertHeader = function (){ var header = "<div id='popoverHeader'>" + "<div id='popoverTitle'></div>" + "<a id='popoverClose'><span id='popoverCloseIcon'>✕</span></a>" + "</div>"; $("#popoverContentWrapper").before(header); //Create back button //Don't create back button or listener if disabled. if(this.isBackEnabled){ //console.log("LOG: Creating back button."); var thisPopover = this; $("#popoverHeader").prepend("<a id='popoverBack'><span id='popoverBackIcon'>◄</span></a>"); $("#popoverBack").on("click", function () { thisPopover.previousPopover(); }); } //Click listener for popover close button. $("#popoverClose").on("click", function () { Popover.closePopover(); }); $("#popoverContent").css("paddingTop", "47px"); }; Popover.prototype.removeHeader = function() { $("#popoverBack").off("click"); $("#popoverClose").off("click"); $("#popoverHeader").remove(); $("#popoverContent").css("paddingTop", ""); }; Popover.prototype.clearData = function (){ this.removeHeader(); $("#popoverTitle").html(""); $("#popoverContent").html(""); }; Popover.prototype.setData = function (data) { Popover.setAction(data.id); Popover.setTitle(data.title); Popover.setContent(data.contents); }; Popover.prototype.replaceMenu = function (menu, newMenu){ var property; for(property in menu){ delete menu[property]; } for(property in newMenu){ menu[property] = newMenu[property]; } }; //Public setter function for private var content and sets content of the html popover element. Popover.setContent = function (cont) { Popover.content = cont; //$("#popoverContentWrapper").data('jsp').getContentPane().find("#popoverContent").html(cont); //Note: Popover content set without using jscrollpane api. $("#popoverContent").html(cont); //Note: Removed 'this' reference passed. $("#popoverContentWrapper").trigger("popover.setContent"); }; /** STATIC VARIABLES **/ Popover.popoverNum = 0; Popover.lastElementClick = null; Popover.currentTarget = null; Popover.title = ""; Popover.content = ""; Popover.menus = []; Popover.history = []; Popover.backgroundColor = null; Popover.fontColor = null; Popover.borderColor = null; Popover.padding = 3; Popover.offScreenX = false; Popover.offScreenY = false; Popover.isLocked = false; Popover.above = false; Popover.caretLeftOffset = "50%"; Popover.lastPopoverClicked = null; /** STATIC FUNCTIONS **/ Popover.setBackgroundColor = function(color){ Popover.backgroundColor = color; }; Popover.setFontColor = function(color){ Popover.fontColor = color; }; Popover.setBorderColor = function(color){ Popover.borderColor = color; }; Popover.lockPopover = function(){ Popover.isLocked = true; }; Popover.unlockPopover = function(){ Popover.isLocked = false; }; //////////////////////////////////////////////////////////// // OptionsPopover Block //////////////////////////////////////////////////////////// /** OptionsPopover CONSTRUCTOR **/ function OptionsPopover(popoverListener){ //Super constructor call. Popover.apply(this, [popoverListener]); this.constructor = OptionsPopover; this.superConstructor = Popover; this.isHeaderDisabled = false; this.isBackEnabled = true; if(!OptionsPopover.hasRun){ this.init(); OptionsPopover.hasRun = true; } } //Inherit Popover OptionsPopover.prototype = new Popover(); OptionsPopover.constructor = OptionsPopover; /** STATIC VARIABLES **/ OptionsPopover.hasRun = false; /** PROTOTYPE FUNCTIONS **/ //Run-once function for listeners OptionsPopover.prototype.init = function(){ $(document) .on('touchstart mousedown', '#popover a', function () { $(this).css({backgroundColor: "#488FCD"}); }) .on('touchend mouseup mouseout', '#popover a', function () { $(this).css({backgroundColor: ""}); }) .on('click', '.popoverContentRow', function () { var newId = []; newId.push($(this).attr('id')); if ($(this).hasClass("popoverEvent")) { $(this).trigger("popover.action", $(this)); } var keepOpen = Popover.lastPopoverClicked.populate(newId); if (!keepOpen) Popover.closePopover(); }); }; OptionsPopover.prototype.setData = function (data) { var contArray = data.contents; var c = ""; var i; for (i = 0; i < contArray.length; i++) { var lastElement = ""; var popoverEvent = ""; var menuId = ""; var menuUrl = ""; if (i === contArray.length - 1) { lastElement = " last"; } //Links are given the popoverEvent class if no url passed. If link has popoverEvent, // event is fired based on currentPopoverAction. if (typeof(contArray[i].id) !== 'undefined') { menuId = " id='" + contArray[i].id + "'"; } if (typeof(contArray[i].url) !== 'undefined') { menuUrl = " href='" + contArray[i].url + "'"; } else { popoverEvent = " popoverEvent"; } c += "<a" + menuUrl + menuId + " class='popoverContentRow" + popoverEvent + lastElement + "'>" + contArray[i].name + "</a>"; } Popover.setAction(data.id); Popover.setTitle(data.title); Popover.setContent(c); }; }(window.jQuery); /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function searchPanel(divElement, options) { var thread = null; var panel = this; var lastT = ""; var xhr = null; if (typeof componentsRegistry == "undefined") { componentsRegistry = []; } this.markerColor = 'black'; if (typeof globalMarkerColor == "undefined") { globalMarkerColor = 'black'; } this.type = "search"; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var componentLoaded = false; panel.shown0 = false; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } panel.subscribers = []; panel.subscriptions = []; panel.subscriptionsColor = []; this.history = []; this.setupCanvas = function() { var context = { divElementId: panel.divElement.id }; $(divElement).html(JST["views/searchPlugin/aux.hbs"](context)); $('#' + panel.divElement.id + '-searchBox').keyup(function() { clearTimeout(thread); var $this = $(this); thread = setTimeout(function() { panel.search($this.val(), 0, 100, false); }, 500); }); // $("#" + panel.divElement.id + "-linkerButton").disableTextSelect(); $("#" + panel.divElement.id + "-subscribersMarker").disableTextSelect(); $("#" + panel.divElement.id + "-configButton").disableTextSelect(); $("#" + panel.divElement.id + "-historyButton").disableTextSelect(); $("#" + panel.divElement.id + "-collapseButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").disableTextSelect(); $("#" + panel.divElement.id + "-closeButton").disableTextSelect(); $("#" + panel.divElement.id + "-clearButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-subscribersMarker").hide(); $("#" + panel.divElement.id).find('.semtag-button').click(function(event) { //console.log("Semtag click: " + $(this).html()); }); //$("#" + panel.divElement.id + "-searchConfigBar").slideUp('fast'); if (options.searchMode != "fullText") { $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').hide(); } $("#" + panel.divElement.id + "-configButton").click(function(event) { panel.setupOptionsPanel(); // $("#" + panel.divElement.id + "-searchConfigBar").slideToggle('slow'); }); if (typeof panel.options.closeButton != "undefined" && panel.options.closeButton == false) { $("#" + panel.divElement.id + "-closeButton").hide(); } // if (typeof panel.options.linkerButton != "undefined" && panel.options.linkerButton == false) { // $("#" + panel.divElement.id + "-linkerButton").hide(); // } if (typeof panel.options.subscribersMarker != "undefined" && panel.options.subscribersMarker == false) { $("#" + panel.divElement.id + "-subscribersMarker").remove(); } if (typeof panel.options.collapseButton != "undefined" && panel.options.collapseButton == false) { $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").hide(); } $("#" + panel.divElement.id + "-expandButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideDown("fast"); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").show(); }); $("#" + panel.divElement.id + "-collapseButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideUp("fast"); $("#" + panel.divElement.id + "-expandButton").show(); $("#" + panel.divElement.id + "-collapseButton").hide(); }); if (typeof i18n_panel_options == "undefined") { i18n_panel_options = "Panel options"; } $("#" + panel.divElement.id + "-configButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_panel_options, animation: true, delay: 1000 }); if (typeof i18n_history == "undefined") { i18n_history = 'History'; } $("#" + panel.divElement.id + "-historyButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_history, animation: true, delay: 1000 }); if (typeof i18n_panel_links == "undefined") { i18n_panel_links = 'Panel links'; } // $("#" + panel.divElement.id + "-linkerButton").tooltip({ // placement : 'left', // trigger: 'hover', // title: i18n_panel_links, // animation: true, // delay: 1000 // }); $("#" + panel.divElement.id + "-apply-button").click(function() { panel.readOptionsPanel(); }); $("#" + panel.divElement.id + "-clearButton").click(function() { panel.options.semTagFilter = "none"; panel.options.langFilter = "none"; panel.options.moduleFilter = "none"; panel.options.refsetFilter = "none"; $('#' + panel.divElement.id + '-searchBox').val(''); $('#' + panel.divElement.id + '-searchFilters').html(""); $('#' + panel.divElement.id + '-resultsTable').html(""); $('#' + panel.divElement.id + '-searchBar').html(""); $('#' + panel.divElement.id + '-searchBar2').html(""); $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-ok'); $('#' + panel.divElement.id + '-typeIcon').removeClass('text-success'); $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-remove'); $('#' + panel.divElement.id + '-typeIcon').addClass('text-danger'); lastT = ""; }); $("#" + panel.divElement.id + "-historyButton").click(function(event) { $("#" + panel.divElement.id + "-historyButton").popover({ trigger: 'manual', placement: 'bottomRight', html: true, content: function() { historyHtml = '<div style="height:100px;overflow:auto;">'; if (typeof i18n_no_search_terms == "undefined") { i18n_no_search_terms = "No search terms" } if (panel.history.length == 0) { historyHtml = historyHtml + '<div class="text-center text-muted" style="width:100%"><em>' + i18n_no_search_terms + '</span>...</em></div>'; } historyHtml = historyHtml + '<table>'; var reversedHistory = panel.history.slice(0); reversedHistory.reverse(); //console.log(JSON.stringify(reversedHistory)); $.each(reversedHistory, function(i, field) { var d = new Date(); var curTime = d.getTime(); var ago = curTime - field.time; var agoString = ""; if (ago < (1000 * 60)) { if (Math.round((ago / 1000)) == 1) { agoString = Math.round((ago / 1000)) + ' second ago'; } else { agoString = Math.round((ago / 1000)) + ' seconds ago'; } } else if (ago < (1000 * 60 * 60)) { if (Math.round((ago / 1000) / 60) == 1) { agoString = Math.round((ago / 1000) / 60) + ' minute ago'; } else { agoString = Math.round((ago / 1000) / 60) + ' minutes ago'; } } else if (ago < (1000 * 60 * 60 * 60)) { if (Math.round(((ago / 1000) / 60) / 60) == 1) { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hour ago'; } else { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hours ago'; } } historyHtml = historyHtml + '<tr><td><a href="javascript:void(0);" onclick="searchInPanel(\'' + panel.divElement.id + '\',\'' + field.searchTerm + '\');">' + field.searchTerm + '</a>'; historyHtml = historyHtml + ' <span class="text-muted" style="font-size: 80%"><em>' + agoString + '<em></span>'; historyHtml = historyHtml + '</td></tr>'; }); historyHtml = historyHtml + '</table>'; historyHtml = historyHtml + '</div>'; return historyHtml; } }); $("#" + panel.divElement.id + "-historyButton").popover('toggle'); }); // $("#" + panel.divElement.id + "-linkerButton").click(function (event) { // $("#" + panel.divElement.id + "-linkerButton").popover({ // trigger: 'manual', // placement: 'bottomRight', // html: true, // content: function () { // var linkerHtml = '<div class="text-center text-muted"><em><span class="i18n" data-i18n-id="i18n_drag_to_link">Drag to link with other panels</span><br>'; // if (panel.subscriptions.length == 1) { // linkerHtml = linkerHtml + panel.subscriptions.length + ' link established</em></div>'; // } else { // linkerHtml = linkerHtml + panel.subscriptions.length + ' links established</em></div>'; // } // linkerHtml = linkerHtml + '<div class="text-center"><a href="javascript:void(0);" onclick="clearSearchPanelSubscriptions(\'' + panel.divElement.id + '\');"><span class="i18n" data-i18n-id="i18n_clear_links">Clear links</span></a></div>'; // return linkerHtml; // } // }); // $("#" + panel.divElement.id + "-linkerButton").popover('toggle'); // }); $("#" + panel.divElement.id + "-fullTextButton").click(function(event) { panel.options.searchMode = 'fullText'; panel.updateSearchLabel(); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').show(); if (searchTerm.charAt(0) == "^") { $("#" + panel.divElement.id + '-searchBox').val(searchTerm.slice(1)); } if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-partialMatchingButton").click(function(event) { panel.options.searchMode = 'partialMatching'; panel.updateSearchLabel(); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').hide(); if (searchTerm.charAt(0) == "^") { $("#" + panel.divElement.id + '-searchBox').val(searchTerm.slice(1)); } if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-regexButton").click(function(event) { panel.options.searchMode = 'regex'; panel.updateSearchLabel(); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); $("#" + panel.divElement.id + '-navLanguageLabel').closest('a').hide(); if (searchTerm.charAt(0) != "^") { $("#" + panel.divElement.id + '-searchBox').val("^" + searchTerm); } if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-danishLangButton").click(function(event) { panel.options.searchLang = 'danish'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_danish_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-englishLangButton").click(function(event) { panel.options.searchLang = 'english'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_english_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-spanishLangButton").click(function(event) { panel.options.searchLang = 'spanish'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_spanish_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); $("#" + panel.divElement.id + "-swedishLangButton").click(function(event) { panel.options.searchLang = 'swedish'; $("#" + panel.divElement.id + '-navLanguageLabel').html(i18n_swedish_stemmer); var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } }); panel.updateStatusFilterLabel(); $("#" + panel.divElement.id + "-activeOnlyButton").click(function(event) { panel.options.statusSearchFilter = 'activeOnly'; panel.updateStatusFilterLabel(); }); $("#" + panel.divElement.id + "-activeInactiveButton").click(function(event) { panel.options.statusSearchFilter = 'activeAndInactive'; panel.updateStatusFilterLabel(); }); $("#" + panel.divElement.id + "-inactiveOnlyButton").click(function(event) { panel.options.statusSearchFilter = 'inactiveOnly'; panel.updateStatusFilterLabel(); }); $("#" + panel.divElement.id + "-partialMatchingButton").click(); $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor); }; this.setupOptionsPanel = function() { var possibleSubscribers = []; $.each(componentsRegistry, function(i, field) { if (field.divElement.id != panel.divElement.id) { var object = {}; object.subscriptions = field.subscriptions; object.id = field.divElement.id; possibleSubscribers.push(object); } }); var aux = false; $.each(possibleSubscribers, function(i, field) { aux = false; $.each(panel.subscriptions, function(j, subscription) { if (field.id == subscription.topic) { aux = true; } }); field.subscribed = aux; aux = false; $.each(field.subscriptions, function(i, subscription) { if (subscription.topic == panel.divElement.id) { aux = true; } }); field.subscriptor = aux; }); panel.options.possibleSubscribers = possibleSubscribers; var context = { options: panel.options, divElementId: panel.divElement.id }; $("#" + panel.divElement.id + "-modal-body").html(JST["views/taxonomyPlugin/options.hbs"](context)); } this.readOptionsPanel = function() { $.each(panel.options.possibleSubscribers, function(i, field) { field.subscribed = $("#" + panel.divElement.id + "-subscribeTo-" + field.id).is(':checked'); field.subscriptor = $("#" + panel.divElement.id + "-subscriptor-" + field.id).is(':checked'); var panelToSubscribe = {}; $.each(componentsRegistry, function(i, panelS) { if (panelS.divElement.id == field.id) { panelToSubscribe = panelS; } }); if (field.subscribed) { panel.subscribe(panelToSubscribe); } else { panel.unsubscribe(panelToSubscribe); } if (field.subscriptor) { panelToSubscribe.subscribe(panel); } else { panelToSubscribe.unsubscribe(panel); } }); $.each(componentsRegistry, function(i, field) { if (field.loadMarkers) field.loadMarkers(); }); } this.updateStatusFilterLabel = function() { if (typeof i18n_active_and_inactive == "undefined") { i18n_active_and_inactive = 'Active and Inactive'; } if (typeof i18n_inactive_only == "undefined") { i18n_inactive_only = 'Inactive Only'; } if (typeof i18n_active_only == "undefined") { i18n_active_only = 'Active Only'; } if (panel.options.statusSearchFilter == 'activeAndInactive') { $("#" + panel.divElement.id + '-searchStatus').html(i18n_active_and_inactive); $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_active_and_inactive); } else if (panel.options.statusSearchFilter == 'inactiveOnly') { $("#" + panel.divElement.id + '-searchStatus').html(i18n_inactive_only); $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_inactive_only); } else { panel.options.statusSearchFilter = 'activeOnly'; $("#" + panel.divElement.id + '-searchStatus').html(i18n_active_only); $("#" + panel.divElement.id + '-navStatusFilterLabel').html(i18n_active_only); } var searchTerm = $('#' + panel.divElement.id + '-searchBox').val(); if (searchTerm.length > 0) { panel.search(searchTerm, 0, 100, true); } } this.search = function(t, skipTo, returnLimit, forceSearch) { if (typeof panel.options.searchMode == "undefined") { panel.options.searchMode = "partialMatching"; } if (typeof panel.options.semTagFilter == "undefined") { panel.options.semTagFilter = "none"; } if (typeof panel.options.langFilter == "undefined") { panel.options.langFilter = "none"; } if (typeof panel.options.moduleFilter == "undefined") { panel.options.moduleFilter = "none"; } if (typeof panel.options.textIndexNormalized == "undefined") { panel.options.textIndexNormalized = "none"; } if (typeof panel.options.refsetFilter == "undefined") { panel.options.refsetFilter = "none"; } if (typeof forceSearch == "undefined") { forceSearch = false; } // panel.divElement.id + '-typeIcon if (t != "" && (t != lastT || forceSearch)) { if (t.length < 3) { $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-ok'); $('#' + panel.divElement.id + '-typeIcon').removeClass('text-success'); $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-remove'); $('#' + panel.divElement.id + '-typeIcon').addClass('text-danger'); } else { $('#' + panel.divElement.id + '-typeIcon').removeClass('glyphicon-remove'); $('#' + panel.divElement.id + '-typeIcon').removeClass('text-danger'); $('#' + panel.divElement.id + '-typeIcon').addClass('glyphicon-ok'); $('#' + panel.divElement.id + '-typeIcon').addClass('text-success'); //if (t != lastT) { // panel.options.semTagFilter = "none"; // panel.options.langFilter = "none"; // panel.options.moduleFilter ="none"; // panel.options.refsetFilter = "none"; // //panel.options.textIndexNormalized = "none"; //} lastT = t; //console.log(t); var d = new Date(); var time = d.getTime(); panel.history.push({ searchTerm: t, time: time }); //t = t.charAt(0).toUpperCase() + t.slice(1); //console.log("Capitalized t: " + t); $('#' + panel.divElement.id + '-searchFilters').html(""); if (skipTo == 0) { $('#' + panel.divElement.id + '-resultsTable').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); } else { $('#' + panel.divElement.id + '-resultsTable').find('.more-row').html("<td colspan='2' class='text-center'><i class='glyphicon glyphicon-refresh icon-spin'></i>&nbsp;&nbsp;</td>"); } var resultsHtml = ""; if (xhr != null) { xhr.abort(); //console.log("aborting call..."); } $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'>Searching..</span>"); //console.log("panel.options.searchMode " + panel.options.searchMode); t = t.trim(); if (isNumber(t)) { if (t.substr(-2, 1) == "0") { // Search conceptId xhr = $.getJSON(options.serverUrl + "/browser/" + options.edition + "/concepts/" + t, function(result) { }).done(function(result) { console.log(result); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); var resDescriptions = []; $.each(result.descriptions, function(i, field) { var aux = field; aux.definitionStatus = result.definitionStatus; if (!aux.active) { aux.danger = true; } if (field.active) { if (panel.options.statusSearchFilter == "activeOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } else { aux.danger = true; if (panel.options.statusSearchFilter == "inactiveOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } }); result.descriptions = resDescriptions; var context = { result: result }; //console.log(context); $('#' + panel.divElement.id + '-resultsTable').html(JST["views/searchPlugin/body/0.hbs"](context)); $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'></span>"); $('#' + panel.divElement.id + '-resultsTable').find(".result-item").click(function(event) { // $.each(panel.subscribers, function (i, field) { // //console.log("Notify to " + field.divElement.id + " selected " + $(event.target).attr('data-concept-id')); // field.conceptId = $(event.target).attr('data-concept-id'); // field.updateCanvas(); // }); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function() { resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar2').html(""); }); } else if (t.substr(-2, 1) == "1") { xhr = $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/descriptions/" + t, function(result) { }).done(function(result) { //console.log(result); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); var context = { result: result }; $('#' + panel.divElement.id + '-resultsTable').html(JST["views/searchPlugin/body/1.hbs"](context)); $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'></span>"); $('#' + panel.divElement.id + '-resultsTable').find(".result-item").click(function(event) { // $.each(panel.subscribers, function (i, field) { // //console.log("Notify to " + field.divElement.id + " selected " + $(event.target).attr('data-concept-id')); // field.conceptId = $(event.target).attr('data-concept-id'); // field.updateCanvas(); // }); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function() { resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar2').html(""); }); } else { // console.log(t.substr(-2, 1)); resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar').html("<span class='text-muted'></span>"); $('#' + panel.divElement.id + '-searchBar2').html(""); } } else { if (panel.options.searchMode == "partialMatching") { t = t.toLowerCase(); t = t.replace("(", ""); t = t.replace(")", ""); } var startTime = Date.now(); var conceptActiveParam; if (panel.options.statusSearchFilter == "activeOnly") { conceptActiveParam = "true"; } else if (panel.options.statusSearchFilter == "inactiveOnly") { conceptActiveParam = "false"; } else { conceptActiveParam = ""; } var searchUrl = options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/descriptions?" + "term=" + encodeURIComponent(t) + "&limit=50" + "&searchMode=" + panel.options.searchMode + "&lang=" + panel.options.searchLang + "&active=" + "true" + "&skipTo=" + skipTo + "&returnLimit=" + returnLimit; if (panel.options.semTagFilter != "none") { searchUrl = searchUrl + "&semanticTag=" + panel.options.semTagFilter; } if (panel.options.langFilter != "none") { searchUrl = searchUrl + "&langFilter=" + panel.options.langFilter; } if (panel.options.moduleFilter != 'none') { searchUrl = searchUrl + "&moduleFilter=" + panel.options.moduleFilter; } if (panel.options.refsetFilter != 'none') { searchUrl = searchUrl + "&refsetFilter=" + panel.options.refsetFilter; } if (panel.options.textIndexNormalized != "none") { searchUrl = searchUrl + "&normalize=" + panel.options.textIndexNormalized; } if ($("#" + panel.divElement.id + "-groupConcept").is(":checked")) { searchUrl = searchUrl + "&groupByConcept=1"; } //console.log(searchUrl); xhr = $.getJSON(searchUrl, function(result) { }).done(function(result) { var resDescriptions = []; $.each(result.items, function(i, field) { var aux = field; aux.definitionStatus = result.definitionStatus; aux.conceptActive = field.concept.active; if (!aux.active || !aux.conceptActive) { aux.danger = true; } if (field.active && field.concept.active) { if (panel.options.statusSearchFilter == "activeOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } else { aux.danger = true; if (panel.options.statusSearchFilter == "inactiveOnly") { resDescriptions.push(aux); } if (panel.options.statusSearchFilter == "activeAndInactive") { resDescriptions.push(aux); } } }); // Convert response format result.matches = resDescriptions; result.matches.forEach(function(match) { match.fsn = match.concept.fsn; match.conceptActive = match.concept.active; match.conceptId = match.concept.conceptId; match.definitionStatus = match.concept.definitionStatus; }) result.filters = {}; result.filters.lang = result.filters.language; result.filters.module = result.filters.module; result.filters.refsetId = result.filters.membership; result.filters.semTag = result.filters.semanticTags; $('#' + panel.divElement.id + '-resultsTable').find('.more-row').remove(); var endTime = Date.now(); var elapsed = (endTime - startTime) / 1000; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper("first20chars", function(string) { return (string.substr(0, 18) + "..."); }); var auxArray = []; if (result.filters) { if (result.filters.refsetId) { $.each(result.filters.refsetId, function(i, refset) { var auxObject = {}; var bucketTerm = null; if (result.bucketConcepts[i]) { bucketTerm = result.bucketConcepts[i].fsn.term; } auxObject.term = bucketTerm; auxObject.value = i; auxObject.cant = refset; auxArray.push(auxObject); }); result.filters.refsetId = []; result.filters.refsetId = auxArray; result.filters.refsetId.sort(function(a, b) { if (a.cant > b.cant) return -1; if (a.cant < b.cant) return 1; return 0; }); } else { result.filters.refsetId = []; } auxArray = []; $.each(result.filters.module, function(i, field) { var auxObject = {}; var bucketTerm = null; if (result.bucketConcepts[i]) { bucketTerm = result.bucketConcepts[i].fsn.term; } auxObject.term = bucketTerm; auxObject.value = i; auxObject.cant = field; auxArray.push(auxObject); }); result.filters.module = []; result.filters.module = auxArray; result.filters.module.sort(function(a, b) { if (a.cant > b.cant) return -1; if (a.cant < b.cant) return 1; return 0; }); if (result.filters.lang && result.filters.semTag) { function sortObject(object) { var sortable = [], sortedObj = {}; for (var attr in object) sortable.push([attr, object[attr]]); sortable.sort(function(a, b) { return b[1] - a[1] }); $.each(sortable, function(i, field) { sortedObj[field[0]] = field[1]; }); return sortedObj; } result.filters.lang = sortObject(result.filters.lang); result.filters.semTag = sortObject(result.filters.semTag); } } // console.log(auxArray); // console.log(result.filters.module); // var ind = 0; // $.each(result.filters.refsetId, function (i, field){ // ind++; // }); // if (ind == 0){ // result.filters.refsetId = 0; // } var context = { result: result, elapsed: elapsed, divElementId: panel.divElement.id, options: panel.options }; $('#' + panel.divElement.id + '-searchBar').html(JST["views/searchPlugin/body/bar.hbs"](context)); $('#' + panel.divElement.id + '-searchBar2').html(JST["views/searchPlugin/body/bar2.hbs"](context)); $('#' + panel.divElement.id + '-moduleResumed').tooltip({ placement: 'left auto', trigger: 'hover', title: $('#' + panel.divElement.id + '-moduleResumed').attr("data-name"), animation: true, delay: 500 }); $('#' + panel.divElement.id + '-refsetResumed').tooltip({ placement: 'left auto', trigger: 'hover', title: $('#' + panel.divElement.id + '-refsetResumed').attr("data-name"), animation: true, delay: 500 }); $("#" + panel.divElement.id + '-searchBar2').find('.semtag-link').click(function(event) { panel.options.semTagFilter = $(event.target).attr('data-semtag'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.module-link').click(function(event) { panel.options.moduleFilter = $(event.target).attr('data-module'); panel.options.moduleFilterName = $(event.target).attr('data-term'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.lang-link').click(function(event) { panel.options.langFilter = $(event.target).attr('data-lang'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.refset-link').click(function(event) { panel.options.refsetFilter = $(event.target).attr('data-refset'); panel.options.refsetFilterName = $(event.target).attr('data-term'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-semtag').click(function(event) { panel.options.semTagFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-lang').click(function(event) { panel.options.langFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-module').click(function(event) { panel.options.moduleFilter = "none"; panel.options.moduleFilterName = null; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar2').find('.remove-refset').click(function(event) { panel.options.refsetFilter = "none"; panel.options.refsetFilterName = null; panel.search(t, 0, returnLimit, true); }); //original filter $("#" + panel.divElement.id + '-searchBar').find('.semtag-link').click(function(event) { panel.options.semTagFilter = $(event.target).attr('data-semtag'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.module-link').click(function(event) { panel.options.moduleFilter = $(event.target).attr('data-module'); panel.options.moduleFilterName = $(event.target).attr('data-term'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.lang-link').click(function(event) { panel.options.langFilter = $(event.target).attr('data-lang'); panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.remove-semtag').click(function(event) { panel.options.semTagFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.remove-lang').click(function(event) { panel.options.langFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + '-searchBar').find('.remove-module').click(function(event) { panel.options.moduleFilter = "none"; panel.options.moduleFilterName = null; panel.search(t, 0, returnLimit, true); }); if (result.details) { var searchComment = "<span class='text-muted'>" + result.details.total + " matches found in " + elapsed + " seconds.</span>"; } xhr = null; var matchedDescriptions = result.matches; //console.log(JSON.stringify(result)); var remaining = result.totalElements - (skipTo + returnLimit); if (panel.options.searchMode == "regex") { result.matches.sort(function(a, b) { if (a.term.length < b.term.length) return -1; if (a.term.length > b.term.length) return 1; return 0; }); } Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > parseInt(b)) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gre', function(a, b, opts) { if (a) { if (parseInt(a) >= b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('hasFilters', function(options, opts) { if (options.semTagFilter != "none" || options.langFilter != "none" || options.moduleFilter != "none" || options.refsetFilter != "none") { return opts.fn(this);; } else { return opts.inverse(this); } }); var context = { options: panel.options, result: result, divElementId: panel.divElement.id, remaining: remaining, returnLimit: returnLimit }; if (skipTo == 0) { $('#' + panel.divElement.id + '-resultsTable').html(JST["views/searchPlugin/body/default.hbs"](context)); } else { $('#' + panel.divElement.id + '-resultsTable').append(JST["views/searchPlugin/body/default.hbs"](context)); } $("#" + panel.divElement.id + "-groupConcept").click(function() { panel.search(t, parseInt(skipTo), returnLimit, true); }); $("#" + panel.divElement.id + "-remove-all-filters").unbind(); $("#" + panel.divElement.id + "-remove-all-filters").click(function(event) { panel.options.semTagFilter = "none"; panel.options.langFilter = "none"; panel.options.moduleFilter = "none"; panel.options.refsetFilter = "none"; panel.search(t, 0, returnLimit, true); }); $("#" + panel.divElement.id + "-more").unbind(); $("#" + panel.divElement.id + "-more").click(function(event) { panel.search(t, (parseInt(skipTo) + parseInt(returnLimit)), returnLimit, true); }); $('#' + panel.divElement.id + '-resultsTable').find(".result-item").click(function(event) { channel.publish(panel.divElement.id, { term: $(event.target).attr("data-term"), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() { resultsHtml = resultsHtml + "<tr><td class='text-muted'>No results</td></tr>"; $('#' + panel.divElement.id + '-resultsTable').html(resultsHtml); $('#' + panel.divElement.id + '-searchBar2').html(""); }); } } } } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); // Subscription methods this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; // console.log('Subscribing to id: ' + panelId); var alreadySubscribed = false; $.each(panel.subscriptionsColor, function(i, field) { if (field == panelToSubscribe.markerColor) { alreadySubscribed = true; } }); if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { // console.log("listening in " + panel.divElement.id); panel.options.searchMode = "fullText"; panel.search(data.conceptId, 0, 100, false); $('#' + panel.divElement.id + '-searchBox').val(data.term); }); panel.subscriptions.push(subscription); panelToSubscribe.subscribers.push(panel.divElement.id); panel.subscriptionsColor.push(panelToSubscribe.markerColor); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-subscribersMarker").show(); } this.unsubscribe = function(panelToUnsubscribe) { var aux = [], colors = [], unsubscribed = true; $.each(panel.subscriptionsColor, function(i, field) { if (field != panelToUnsubscribe.markerColor) { colors.push(field); } else { unsubscribed = false; } }); if (!unsubscribed) { panel.subscriptionsColor = colors; // console.log(panel.divElement.id); // console.log(panel.subscriptionsColor); colors = []; $.each(panelToUnsubscribe.subscribers, function(i, field) { if (field != panel.divElement.id) { aux.push(field); } }); panelToUnsubscribe.subscribers = aux; $.each(panelToUnsubscribe.subscriptionsColor, function(i, field) { colors.push(field); }); if (panelToUnsubscribe.subscribers.length == 0) { if (panelToUnsubscribe.subscriptions.length == 0) { $("#" + panelToUnsubscribe.divElement.id + "-subscribersMarker").hide(); } } else { // colors.push(panelToUnsubscribe.markerColor); } panelToUnsubscribe.subscriptionsColor = colors; // console.log(panelToUnsubscribe.divElement.id); // console.log(panelToUnsubscribe.subscriptionsColor); aux = []; $.each(panel.subscriptions, function(i, field) { if (panelToUnsubscribe.divElement.id == field.topic) { field.unsubscribe(); } else { aux.push(field); } }); panel.subscriptions = aux; if (panel.subscriptions.length == 0 && panel.subscribers.length == 0) { $("#" + panel.divElement.id + "-subscribersMarker").hide(); } } } this.loadMarkers = function() { var auxMarker = "", right = 0, top = 0, aux = false, visible = false; $.each(componentsRegistry, function(i, field) { var panelId = field.divElement.id; if ($("#" + panelId + "-subscribersMarker").is(':visible')) { visible = true; } }); if (panel.subscribers.length == 0) { right = 14; $("#" + panel.divElement.id + "-ownMarker").hide(); } else { if (!visible) { $("#" + panel.divElement.id + "-ownMarker").hide(); } aux = true; } if ($("#" + panel.divElement.id + "-subscribersMarker").is(':visible')) { $("#" + panel.divElement.id + "-panelTitle").html($("#" + panel.divElement.id + "-panelTitle").html().replace(/&nbsp;/g, '')); if (aux) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); } $.each(panel.subscriptionsColor, function(i, field) { auxMarker = auxMarker + "<i class='glyphicon glyphicon-bookmark' style='color: " + field + "; top:" + top + "px; right: " + right + "px;'></i>"; $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); top = top + 5; right = right + 10; }); $("#" + panel.divElement.id + "-subscribersMarker").html(auxMarker); } } this.updateSearchLabel = function() { if (typeof panel.options.searchMode == "undefined") { panel.options.searchMode = "partialMatching"; } if (typeof i18n_search_examp_1 == "undefined") { i18n_search_examp_1 = 'Example 1'; } if (typeof i18n_search_examp_2 == "undefined") { i18n_search_examp_2 = 'Example 2'; } if (typeof i18n_search_examp_3 == "undefined") { i18n_search_examp_3 = 'Example 3'; } if (typeof i18n_regex_search_mode == "undefined") { i18n_regex_search_mode = 'Regex'; } if (typeof i18n_partial_match_search_mode == "undefined") { i18n_partial_match_search_mode = 'Partial'; } if (typeof i18n_full_text_search_mode == "undefined") { i18n_full_text_search_mode = 'Full'; } if (panel.options.searchMode == "regex") { $("#" + panel.divElement.id + "-searchMode").html("<span class='i18n' data-i18n-id='i18n_regex_search_mode'>" + i18n_regex_search_mode + "</span>"); $("#" + panel.divElement.id + '-searchExample').html("<span class='i18n text-muted' data-i18n-id='i18n_search_examp_1'>" + i18n_search_examp_1 + "</span> "); $("#" + panel.divElement.id + '-navSearchModeLabel').html("<span class='i18n' data-i18n-id='i18n_regex_search_mode'>" + i18n_regex_search_mode + "</span>"); } else if (panel.options.searchMode == "fullText") { $("#" + panel.divElement.id + "-searchMode").html("<span class='i18n' data-i18n-id='i18n_full_text_search_mode'>" + i18n_full_text_search_mode + "</span>"); $("#" + panel.divElement.id + '-searchExample').html("<span class='i18n text-muted' data-i18n-id='i18n_search_examp_2'>" + i18n_search_examp_2 + "</em></span> "); $("#" + panel.divElement.id + '-navSearchModeLabel').html("<span class='i18n' data-i18n-id='i18n_full_text_search_mode'>" + i18n_full_text_search_mode + "</span>"); } else if (panel.options.searchMode == "partialMatching") { $("#" + panel.divElement.id + "-searchMode").html("<span class='i18n' data-i18n-id='i18n_partial_match_search_mode'>" + i18n_partial_match_search_mode + "</span>"); $("#" + panel.divElement.id + '-searchExample').html("<span class='i18n text-muted' data-i18n-id='i18n_search_examp_3'>" + i18n_search_examp_3 + "</span> "); $("#" + panel.divElement.id + '-navSearchModeLabel').html("<span class='i18n' data-i18n-id='i18n_partial_match_search_mode'>" + i18n_partial_match_search_mode + "</span>"); } if (typeof panel.options.searchLang == "undefined") { panel.options.searchLang = "english"; } if (typeof i18n_danish_stemmer == "undefined") { i18n_danish_stemmer = 'Danish Stemmer'; } if (typeof i18n_english_stemmer == "undefined") { i18n_english_stemmer = 'English Stemmer'; } if (typeof i18n_spanish_stemmer == "undefined") { i18n_spanish_stemmer = 'Spanish Stemmer'; } if (panel.options.searchLang == "danish") { $("#" + panel.divElement.id + '-navLanguageLabel').html("<span class='i18n' data-i18n-id='i18n_danish_stemmer'>" + i18n_danish_stemmer + "</span>"); } else if (panel.options.searchLang == "english") { $("#" + panel.divElement.id + '-navLanguageLabel').html("<span class='i18n' data-i18n-id='i18n_english_stemmer'>" + i18n_english_stemmer + "</span>"); } else if (panel.options.searchLang == "spanish") { $("#" + panel.divElement.id + '-navLanguageLabel').html("<span class='i18n' data-i18n-id='i18n_spanish_stemmer'>" + i18n_spanish_stemmer + "</span>"); } } this.setupCanvas(); this.updateSearchLabel(); } function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function clearSearchPanelSubscriptions(divElementId1) { var d1; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == divElementId1) { d1 = field; } }); d1.unsubscribeAll(); $("#" + divElementId1).find('.linker-button').popover('toggle'); } function searchInPanel(divElementId, searchTerm) { $.each(componentsRegistry, function(i, field) { //console.log(field.divElement.id + ' == ' + divElementId); if (field.divElement.id == divElementId) { $('#' + divElementId + '-searchBox').val(searchTerm); field.search(searchTerm, 0, 100, false); } }); $('.history-button').popover('hide'); } $(document).keypress(function(event) { if (event.which == '13') { event.preventDefault(); } }); (function($) { $.fn.addSearch = function(options) { this.filter("div").each(function() { var tx = new conceptDetails(this, options); }); }; }(jQuery)); /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ var idSequence = 0; function drawSctBox(svg, x, y, label, sctid, cssClass) { //console.log("In svg: " + label + " " + sctid + " " + cssClass); // x,y coordinates of the top-left corner var testText = "Test"; if (label && sctid) { if (label.length > sctid.toString().length) { testText = label; } else { testText = sctid.toString(); } } else if (label) { testText = label; } else if (sctid) { testText = sctid.toString(); } var fontFamily = '"Helvetica Neue",Helvetica,Arial,sans-serif'; //var fontFamily = 'sans-serif'; var tempText = svg.text(x, y , testText, {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); var textHeight = tempText.getBBox().height; var textWidth = tempText.getBBox().width; textWidth = Math.round(textWidth* 1.2); svg.remove(tempText); var rect = null; var widthPadding = 20; var heightpadding = 25; if (!sctid || !label) { heightpadding = 15; } if (cssClass == "sct-primitive-concept") { rect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: '#99ccff', stroke: '#333', strokeWidth: 2}); } else if (cssClass == "sct-defined-concept") { rect = svg.rect(x-2, y-2, textWidth + widthPadding + 4, textHeight + heightpadding + 4, {fill: 'white', stroke: '#333', strokeWidth: 1}); var innerRect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: '#ccccff', stroke: '#333', strokeWidth: 1}); } else if (cssClass == "sct-attribute") { rect = svg.rect(x-2, y-2, textWidth + widthPadding + 4, textHeight + heightpadding + 4, 18, 18, {fill: 'white', stroke: '#333', strokeWidth: 1}); var innerRect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, 18, 18, {id: 'rect'+idSequence, fill: '#ffffcc', stroke: '#333', strokeWidth: 1}); }else if (cssClass == "sct-slot") { rect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: '#99ccff', stroke: '#333', strokeWidth: 2}); } else { rect = svg.rect(x, y, textWidth + widthPadding, textHeight + heightpadding, {id: 'rect'+idSequence, fill: 'white', stroke: 'black', strokeWidth: 1}); } if (sctid && label) { svg.text(x + 10, y + 16, sctid.toString(), {fontFamily: fontFamily, fontSize: '10', fill: 'black'}); svg.text(x + 10, y + 31, label, {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); } else if (label) { svg.text(x + 10, y + 18, label, {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); } else if (sctid) { svg.text(x + 10, y + 18, sctid.toString(), {fontFamily: fontFamily, fontSize: '12', fill: 'black'}); } idSequence++; $('rect').click(function(evt){ //console.log(evt.target); }); return rect; } function connectElements(svg, fig1, fig2, side1, side2, endMarker) { var rect1cx = fig1.getBBox().x; var rect1cy = fig1.getBBox().y; var rect1cw = fig1.getBBox().width; var rect1ch = fig1.getBBox().height; var rect2cx = fig2.getBBox().x; var rect2cy = fig2.getBBox().y ; var rect2cw = fig2.getBBox().width; var rect2ch = fig2.getBBox().height; var markerCompensantion1 = 15; var markerCompensantion2 = 15; switch(side1) { case 'top': originY = rect1cy; originX = rect1cx + (rect1cw/2); break; case 'bottom': originY = rect1cy + rect1ch; originX = rect1cx + (rect1cw/2); break; case 'left': originX = rect1cx - markerCompensantion1; originY = rect1cy + (rect1ch/2); break; case 'right': originX = rect1cx + rect1cw; originY = rect1cy + (rect1ch/2); break; case 'bottom-50': originY = rect1cy + rect1ch; originX = rect1cx + 40; break; default: originX = rect1cx + (rect1cw/2); originY = rect1cy + (rect1ch/2); break; } switch(side2) { case 'top': destinationY = rect2cy; destinationX = rect2cx + (rect2cw/2); break; case 'bottom': destinationY = rect2cy + rect2ch; destinationX = rect2cx + (rect2cw/2); break; case 'left': destinationX = rect2cx - markerCompensantion2; destinationY = rect2cy + (rect2ch/2); break; case 'right': destinationX = rect2cx + rect2cw; destinationY = rect2cy + (rect2ch/2); break; case 'bottom-50': destinationY = rect2cy + rect2ch; destinationX = rect2cx + 50; break; default: destinationX = rect2cx + (rect2cw/2); destinationY = rect2cy + (rect2ch/2); break; } if (endMarker == null) endMarker = "BlackTriangle"; polyline1 = svg.polyline([[originX, originY], [originX, destinationY], [destinationX, destinationY]] , {id: 'poly1', fill: 'none', stroke: 'black', strokeWidth: 2, 'marker-end': 'url(#' + endMarker + ')'}); } function loadDefs(svg) { var defs = svg.defs('SctDiagramsDefs'); blackTriangle = svg.marker(defs, 'BlackTriangle', 0, 0, 20, 20, { viewBox: '0 0 22 20', refX: '0', refY: '10', markerUnits: 'strokeWidth', markerWidth: '8', markerHeight: '6', fill: 'black',stroke: 'black', strokeWidth: 2}); svg.path(blackTriangle, 'M 0 0 L 20 10 L 0 20 z'); clearTriangle = svg.marker(defs, 'ClearTriangle', 0, 0, 20, 20, { viewBox: '0 0 22 20', refX: '0', refY: '10', markerUnits: 'strokeWidth', markerWidth: '8', markerHeight: '8', fill: 'white',stroke: 'black', strokeWidth: 2}); svg.path(clearTriangle, 'M 0 0 L 20 10 L 0 20 z'); lineMarker = svg.marker(defs, 'LineMarker', 0, 0, 20, 20, { viewBox: '0 0 22 20', refX: '0', refY: '10', markerUnits: 'strokeWidth', markerWidth: '8', markerHeight: '8', fill: 'white',stroke: 'black', strokeWidth: 2}); svg.path(lineMarker, 'M 0 10 L 20 10'); } function drawAttributeGroupNode(svg, x, y) { circle = svg.circle(x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); return circle; } function drawConjunctionNode(svg, x, y) { circle = svg.circle(x, y, 10, {fill: 'black',stroke: 'black', strokeWidth: 2}); return circle; } function drawEquivalentNode(svg, x, y) { g = svg.group(); svg.circle(g, x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y-5, x+7, y-5, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y, x+7, y, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+5, x+7, y+5, {stroke: 'black', strokeWidth: 2}); return g; } function drawSubsumedByNode(svg, x, y) { g = svg.group(); svg.circle(g, x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y-8, x+7, y-8, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+3, x+7, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-6, y-8, x-6, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+7, x+7, y+7, {stroke: 'black', strokeWidth: 2}); return g; } function drawSubsumesNode(svg, x, y) { g = svg.group(); svg.circle(g, x, y, 20, {fill: 'white',stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y-8, x+7, y-8, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+3, x+7, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x+6, y-8, x+6, y+3, {stroke: 'black', strokeWidth: 2}); svg.line(g, x-7, y+7, x+7, y+7, {stroke: 'black', strokeWidth: 2}); return g; } /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function taxonomyPanel(divElement, conceptId, options) { var nodeCount = 0; var panel = this; var xhr = null; if (typeof componentsRegistry == "undefined") { componentsRegistry = []; } this.markerColor = 'black'; if (typeof globalMarkerColor == "undefined") { globalMarkerColor = 'black'; } this.type = "taxonomy"; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var componentLoaded = false; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } panel.default = {}; panel.default.conceptId = conceptId; panel.subscribers = []; panel.subscriptions = []; panel.subscriptionsColor = []; this.history = []; if (!options.rootConceptDescendants) { console.log(options); $.ajax({ type: "GET", url: options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts", data: { ecl: "< 138875005|SNOMED CT Concept|", offset: 0, limit: 1 }, dataType: "json", success: function(result) { options.rootConceptDescendants = result.total; } }).done(function(result) { // done }); } this.setupCanvas = function() { var context = { divElementId: panel.divElement.id }; $(divElement).html(JST["views/taxonomyPlugin/main.hbs"](context)); $("#" + panel.divElement.id + "-resetButton").disableTextSelect(); // $("#" + panel.divElement.id + "-linkerButton").disableTextSelect(); $("#" + panel.divElement.id + "-subscribersMarker").disableTextSelect(); $("#" + panel.divElement.id + "-historyButton").disableTextSelect(); $("#" + panel.divElement.id + "-configButton").disableTextSelect(); $("#" + panel.divElement.id + "-collapseButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").disableTextSelect(); $("#" + panel.divElement.id + "-closeButton").disableTextSelect(); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-subscribersMarker").hide(); $("#" + panel.divElement.id + "-closeButton").click(function(event) { $(divElement).remove(); }); $("#" + panel.divElement.id + "-configButton").click(function(event) { panel.setupOptionsPanel(); // $("#" + panel.divElement.id + "-taxonomyConfigBar").slideToggle('slow'); }); if (typeof panel.options.closeButton != "undefined" && panel.options.closeButton == false) { $("#" + panel.divElement.id + "-closeButton").hide(); } // if (typeof panel.options.linkerButton != "undefined" && panel.options.linkerButton == false) { // $("#" + panel.divElement.id + "-linkerButton").hide(); // } if (typeof panel.options.subscribersMarker != "undefined" && panel.options.subscribersMarker == false) { $("#" + panel.divElement.id + "-subscribersMarker").remove(); } if (typeof panel.options.collapseButton != "undefined" && panel.options.collapseButton == false) { $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").hide(); } $("#" + panel.divElement.id + "-expandButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideDown("fast"); $("#" + panel.divElement.id + "-expandButton").hide(); $("#" + panel.divElement.id + "-collapseButton").show(); }); $("#" + panel.divElement.id + "-collapseButton").click(function(event) { $("#" + panel.divElement.id + "-panelBody").slideUp("fast"); $("#" + panel.divElement.id + "-expandButton").show(); $("#" + panel.divElement.id + "-collapseButton").hide(); }); if (typeof i18n_panel_options == "undefined") { i18n_panel_options = 'Options'; } $("#" + panel.divElement.id + "-configButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_panel_options, animation: true, delay: 1000 }); if (typeof i18n_history == "undefined") { i18n_history = 'History'; } $("#" + panel.divElement.id + "-historyButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_history, animation: true, delay: 1000 }); if (typeof i18n_reset == "undefined") { i18n_reset = 'Reset'; } $("#" + panel.divElement.id + "-resetButton").tooltip({ placement: 'left', trigger: 'hover', title: i18n_reset, animation: true, delay: 1000 }); if (typeof i18n_panel_links == "undefined") { i18n_panel_links = 'Panel links'; } // $("#" + panel.divElement.id + "-linkerButton").tooltip({ // placement : 'left', // trigger: 'hover', // title: i18n_panel_links, // animation: true, // delay: 1000 // }); $("#" + panel.divElement.id + "-resetButton").click(function() { // panel.setupParents([], {conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); panel.setToConcept(panel.default.conceptId); }); $("#" + panel.divElement.id + "-apply-button").click(function() { //console.log("apply!"); panel.readOptionsPanel(); // panel.setupParents([], {conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-historyButton").click(function(event) { $("#" + panel.divElement.id + "-historyButton").popover({ trigger: 'manual', placement: 'bottomRight', html: true, content: function() { historyHtml = '<div style="height:100px;overflow:auto;">'; if (typeof i18n_no_terms == "undefined") { i18n_no_terms = "No terms" } if (panel.history.length == 0) { historyHtml = historyHtml + '<div class="text-center text-muted" style="width:100%"><em>' + i18n_no_terms + '</span>...</em></div>'; } historyHtml = historyHtml + '<table>'; var reversedHistory = panel.history.slice(0); reversedHistory.reverse(); //console.log(JSON.stringify(reversedHistory)); $.each(reversedHistory, function(i, field) { var d = new Date(); var curTime = d.getTime(); var ago = curTime - field.time; var agoString = ""; if (ago < (1000 * 60)) { if (Math.round((ago / 1000)) == 1) { agoString = Math.round((ago / 1000)) + ' second ago'; } else { agoString = Math.round((ago / 1000)) + ' seconds ago'; } } else if (ago < (1000 * 60 * 60)) { if (Math.round((ago / 1000) / 60) == 1) { agoString = Math.round((ago / 1000) / 60) + ' minute ago'; } else { agoString = Math.round((ago / 1000) / 60) + ' minutes ago'; } } else if (ago < (1000 * 60 * 60 * 60)) { if (Math.round(((ago / 1000) / 60) / 60) == 1) { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hour ago'; } else { agoString = Math.round(((ago / 1000) / 60) / 60) + ' hours ago'; } } historyHtml = historyHtml + '<tr><td><a href="javascript:void(0);" onclick="historyInTaxPanel(\'' + panel.divElement.id + '\',\'' + field.conceptId + '\');">' + field.term + '</a>'; historyHtml = historyHtml + ' <span class="text-muted" style="font-size: 80%"><em>' + agoString + '<em></span>'; historyHtml = historyHtml + '</td></tr>'; }); historyHtml = historyHtml + '</table>'; historyHtml = historyHtml + '</div>'; return historyHtml; } }); $("#" + panel.divElement.id + "-historyButton").popover('toggle'); }); // $("#" + panel.divElement.id + "-linkerButton").click(function(event) { // $("#" + panel.divElement.id + "-linkerButton").popover({ // trigger: 'manual', // placement: 'bottomRight', // html: true, // content: function() { // linkerHtml = '<div class="text-center text-muted"><em>Drag to link with other panels<br>'; // if (panel.subscriptions.length == 1) { // linkerHtml = linkerHtml + panel.subscriptions.length + ' link established</em></div>'; // } else { // linkerHtml = linkerHtml + panel.subscriptions.length + ' links established</em></div>'; // } // linkerHtml = linkerHtml + '<div class="text-center"><a href="javascript:void(0);" onclick="clearTaxonomyPanelSubscriptions(\'' + panel.divElement.id + '\');">Clear links</a></div>'; // return linkerHtml; // } // }); // $("#" + panel.divElement.id + "-linkerButton").popover('toggle'); // }); $("#" + panel.divElement.id + "-descendantsCountTrue").click(function(event) { panel.options.descendantsCount = true; $("#" + panel.divElement.id + '-txViewLabel2').html("Descendants Count: On"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "inferredDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-descendantsCountFalse").click(function(event) { panel.options.descendantsCount = false; $("#" + panel.divElement.id + '-txViewLabel2').html("Descendants Count: Off"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "inferredDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-inferredViewButton").click(function(event) { panel.options.selectedView = 'inferred'; $("#" + panel.divElement.id + '-txViewLabel').html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "inferredDescendants": options.rootConceptDescendants }); }); $("#" + panel.divElement.id + "-statedViewButton").click(function(event) { panel.options.selectedView = 'stated'; $("#" + panel.divElement.id + '-txViewLabel').html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); panel.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); }); //$("#" + panel.divElement.id + "-inferredViewButton").click(); $("#" + panel.divElement.id + "-ownMarker").css('color', panel.markerColor); } this.setupOptionsPanel = function() { var possibleSubscribers = []; $.each(componentsRegistry, function(i, field) { if (field.divElement.id != panel.divElement.id) { var object = {}; object.subscriptions = field.subscriptions; object.id = field.divElement.id; possibleSubscribers.push(object); } }); var aux = false; $.each(possibleSubscribers, function(i, field) { aux = false; $.each(panel.subscriptions, function(j, subscription) { if (field.id == subscription.topic) { aux = true; } }); field.subscribed = aux; aux = false; $.each(field.subscriptions, function(i, subscription) { if (subscription.topic == panel.divElement.id) { aux = true; } }); field.subscriptor = aux; }); panel.options.possibleSubscribers = possibleSubscribers; var context = { options: panel.options, divElementId: panel.divElement.id }; $("#" + panel.divElement.id + "-modal-body").html(JST["views/taxonomyPlugin/options.hbs"](context)); } this.readOptionsPanel = function() { $.each(panel.options.possibleSubscribers, function(i, field) { field.subscribed = $("#" + panel.divElement.id + "-subscribeTo-" + field.id).is(':checked'); field.subscriptor = $("#" + panel.divElement.id + "-subscriptor-" + field.id).is(':checked'); var panelToSubscribe = {}; $.each(componentsRegistry, function(i, panelS) { if (panelS.divElement.id == field.id) { panelToSubscribe = panelS; } }); if (field.subscribed) { panel.subscribe(panelToSubscribe); } else { panel.unsubscribe(panelToSubscribe); } if (field.subscriptor) { panelToSubscribe.subscribe(panel); } else { panelToSubscribe.unsubscribe(panel); } }); $.each(componentsRegistry, function(i, field) { if (field.loadMarkers) field.loadMarkers(); }); } this.setupParents = function(parents, focusConcept) { var lastParent; $.each(parents, function(i, parent) { lastParent = parent; }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a > b) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_def', function(conceptId, opts) { if (conceptId == panel.default.conceptId) return opts.fn(this); else return opts.inverse(this); }); var context = { parents: parents, focusConcept: focusConcept, divElementId: panel.divElement.id }; Handlebars.registerHelper('slice', function(a, b) { $("#" + panel.divElement.id + "-panelBody").html($("#" + panel.divElement.id + "-panelBody").html().slice(a, b)); }); $("#" + panel.divElement.id + "-panelBody").html(JST["views/taxonomyPlugin/body/parents.hbs"](context)); if (panel.options.descendantsCount == true) { var auxArray = parents; auxArray.push(focusConcept); auxArray.forEach(function(concept) { var descedants = concept.inferredDescendants; if (panel.options.selectedView == 'stated') { descedants = concept.statedDescendants; } // $.ajax({ // type: "POST", // url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", // data: { // expression: "< " + concept.conceptId + "|" + concept.defaultTerm + "|", // limit : 1, // skip : 0, // form: panel.options.selectedView // }, // dataType: "json", // success: function(result) { // if (result.computeResponse) { $("#" + panel.divElement.id + "-panelBody").find('.selectable-row[data-concept-id="' + concept.conceptId + '"]').append("&nbsp;&nbsp;&nbsp;&nbsp;<span class='text-muted'>" + descedants + "</span>"); // } // } // }).done(function(result){ // // done // }); }); } //console.log(JST["views/taxonomyPlugin/body/parents.hbs"](context)); $(".treeButton").disableTextSelect(); $("#" + panel.divElement.id + "-panelBody").unbind("dblclick"); $("#" + panel.divElement.id + "-panelBody").dblclick(function(event) { if ($(event.target).hasClass("treeLabel")) { var d = new Date(); var time = d.getTime(); var selectedModule = $(event.target).attr('data-module'); var selectedId = $(event.target).attr('data-concept-id'); var selectedLabel = $(event.target).attr('data-term'); var statedDescendants = $(event.target).attr('data-statedDescendants'); var inferredDescendants = $(event.target).attr('data-inferredDescendants'); panel.history.push({ term: selectedLabel, conceptId: selectedId, time: time }); if (typeof selectedId != "undefined") { $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + selectedId + "/parents?form=" + panel.options.selectedView, function(result) { // done }).done(function(result) { panel.setupParents(result, { conceptId: selectedId, defaultTerm: selectedLabel, definitionStatus: "PRIMITIVE", module: selectedModule, statedDescendants: statedDescendants, inferredDescendants: inferredDescendants }); }).fail(function() {}); } } }); $("#" + panel.divElement.id + "-panelBody").unbind("click"); $("#" + panel.divElement.id + "-panelBody").click(function(event) { if ($(event.target).hasClass("treeButton")) { var conceptId = $(event.target).closest("li").attr('data-concept-id'); var iconId = panel.divElement.id + "-treeicon-" + conceptId; event.preventDefault(); if ($("#" + iconId).hasClass("glyphicon-chevron-down")) { //console.log("close"); $(event.target).closest("li").find("ul").remove(); $("#" + iconId).removeClass("glyphicon-chevron-down"); $("#" + iconId).addClass("glyphicon-chevron-right"); } else if ($("#" + iconId).hasClass("glyphicon-chevron-right")) { //console.log("open"); $("#" + iconId).removeClass("glyphicon-chevron-right"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); panel.getChildren($(event.target).closest("li").attr('data-concept-id')); } else if ($("#" + iconId).hasClass("glyphicon-chevron-up")) { $("#" + iconId).removeClass("glyphicon-chevron-up"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); panel.wrapInParents($(event.target).closest("li").attr('data-concept-id'), $(event.target).closest("li")); } else if ($("#" + iconId).hasClass("glyphicon-minus")) { // $("#" + iconId).removeClass("glyphicon-minus"); // $("#" + iconId).addClass("glyphicon-chevron-right"); } } else if ($(event.target).hasClass("treeLabel")) { var selectedId = $(event.target).attr('data-concept-id'); if (typeof selectedId != "undefined") { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: selectedId, source: panel.divElement.id }); } } }); var iconId = panel.divElement.id + "-treeicon-" + focusConcept.conceptId; $("#" + iconId).removeClass("glyphicon-chevron-right"); $("#" + iconId).addClass("glyphicon-refresh"); $("#" + iconId).addClass("icon-spin"); //console.log("getChildren..." + focusConcept.conceptId); panel.getChildren(focusConcept.conceptId); }; this.getChildren = function(conceptId) { if (typeof panel.options.selectedView == "undefined") { panel.options.selectedView = "inferred"; } if (panel.options.selectedView == "inferred") { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_inferred_view'>Inferred view</span>"); } else { $("#" + panel.divElement.id + "-txViewLabel").html("<span class='i18n' data-i18n-id='i18n_stated_view'>Stated view</span>"); } if (panel.options.descendantsCount == true) $("#" + panel.divElement.id + "-txViewLabel2").html("Descendants Count: On"); else $("#" + panel.divElement.id + "-txViewLabel2").html("Descendants Count: Off"); $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/children?form=" + panel.options.selectedView, function(result) {}).done(function(result) { if (result && result[0] && typeof result[0].statedDescendants == "undefined") $("#" + panel.divElement.id + "-txViewLabel2").closest("li").hide(); result.forEach(function(c) {setDefaultTerm(c)}); result.sort(function(a, b) { if (a.defaultTerm.toLowerCase() < b.defaultTerm.toLowerCase()) return -1; if (a.defaultTerm.toLowerCase() > b.defaultTerm.toLowerCase()) return 1; return 0; }); //console.log(JSON.stringify(result)); var listIconIds = []; //console.log(JSON.stringify(listIconIds)); var context = { result: result, divElementId: panel.divElement.id, selectedView: panel.options.selectedView }; Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('push', function(element) { listIconIds.push(element); }); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); if (result.length > 0) { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down"); } else { $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); } $("#" + panel.divElement.id + "-treenode-" + conceptId).closest("li").append(JST["views/taxonomyPlugin/body/children.hbs"](context)); if (panel.options.descendantsCount == true) { result.forEach(function(concept) { if (concept.active) { var descedants = concept.inferredDescendants; if (panel.options.selectedView == 'stated') { descedants = concept.statedDescendants; } // $.ajax({ // type: "POST", // url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", // data: { // expression: "< " + concept.conceptId + "|" + concept.defaultTerm + "|", // limit : 1, // skip : 0, // form: panel.options.selectedView // }, // dataType: "json", // success: function(result) { // if (result.computeResponse) { $("#" + panel.divElement.id + "-treenode-" + conceptId).closest("li").find('.selectable-row[data-concept-id="' + concept.conceptId + '"]').append("&nbsp;&nbsp;&nbsp;&nbsp;<span class='text-muted'>" + descedants + "</span>"); // } // } // }).done(function(result){ // // done // }); } }); } $(".treeButton").disableTextSelect(); if (typeof i18n_drag_this == "undefined") { i18n_drag_this = "Drag this"; } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() { $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-minus"); }); } this.wrapInParents = function(conceptId, liItem) { var topUl = $("#" + panel.divElement.id + "-panelBody").find('ul:first'); $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/parents?form=" + panel.options.selectedView, function(parents) { // done }).done(function(parents) { if (parents.length > 0) { var firstParent = "empty"; var parentsStrs = []; $.each(parents, function(i, parent) { var parentLiHtml = "<li data-concept-id='" + parent.conceptId + "' data-term='" + parent.defaultTerm + "' class='treeLabel'>"; parentLiHtml = parentLiHtml + "<button class='btn btn-link btn-xs treeButton' style='padding:2px'><i class='glyphicon glyphicon-chevron-"; if (parent.conceptId == "138875005" || parent.conceptId == "9999999999") { parentLiHtml = parentLiHtml + "down"; } else { parentLiHtml = parentLiHtml + "up"; } parentLiHtml = parentLiHtml + " treeButton' id='" + panel.divElement.id + "-treeicon-" + parent.conceptId + "'></i></button>"; if (parent.definitionStatus == "PRIMITIVE") { parentLiHtml = parentLiHtml + '<span class="badge alert-warning" data-concept-id="' + parent.conceptId + '" data-term="' + parent.defaultTerm + '" draggable="true" ondragstart="drag(event)" class="treeLabel selectable-row" id="' + panel.divElement.id + '-treenode-' + parent.conceptId + '">&nbsp;&nbsp;</span>&nbsp;&nbsp;'; } else { parentLiHtml = parentLiHtml + '<span class="badge alert-warning" data-concept-id="' + parent.conceptId + '" data-term="' + parent.defaultTerm + '" draggable="true" ondragstart="drag(event)" class="treeLabel selectable-row" id="' + panel.divElement.id + '-treenode-' + parent.conceptId + '">&equiv;</span>&nbsp;&nbsp;'; } if (countryIcons[parent.module]) { parentLiHtml = parentLiHtml + "<div class='phoca-flagbox' style='width:33px;height:33px'><span class='phoca-flag " + countryIcons[parent.module] + "'></span></div> "; } parentLiHtml = parentLiHtml + '<a href="javascript:void(0);" style="color: inherit;text-decoration: inherit;"><span class="treeLabel selectable-row" data-concept-id="' + parent.conceptId + '" data-term="' + parent.defaultTerm + '"> ' + parent.defaultTerm + '</span></a>'; parentLiHtml = parentLiHtml + "</li>"; parentsStrs.push(parentLiHtml); if (firstParent == "empty") { firstParent = parent.conceptId; } }); var staticChildren = topUl.children().slice(0); topUl.append(parentsStrs[0]); $('#' + panel.divElement.id + '-treenode-' + firstParent).closest('li').append("<ul id='parent-ul-id-" + firstParent + "' style='list-style-type: none; padding-left: 15px;'></ul>"); if (panel.options.descendantsCount == true) { parents.forEach(function(concept) { var descedants = concept.inferredDescendants; if (panel.options.selectedView == 'stated') { descedants = concept.statedDescendants; } // $.ajax({ // type: "POST", // url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", // data: { // expression: "< " + concept.conceptId + "|" + concept.defaultTerm + "|", // limit : 1, // skip : 0, // form: panel.options.selectedView // }, // dataType: "json", // success: function(result) { // if (result.computeResponse) { $(topUl).find('.selectable-row[data-concept-id="' + concept.conceptId + '"]').append("&nbsp;&nbsp;&nbsp;&nbsp;<span class='text-muted'>" + descedants + "</span>"); // } // } // }).done(function(result){ // // done // }); }); } var newMainChild; $.each(staticChildren, function(i, child) { if ($(child).attr('data-concept-id') == conceptId) { newMainChild = $(child); var newUl = $('#' + panel.divElement.id + '-treenode-' + firstParent).closest('li').find('ul:first'); newUl.append($(child)); $(child).find('i:first').removeClass("glyphicon-chevron-up"); $(child).find('i:first').addClass("glyphicon-chevron-down"); } }); $.each(staticChildren, function(i, child) { if ($(child).attr('data-concept-id') != conceptId) { $.each($(child).children(), function(i, subchild) { if ($(subchild).is('ul')) { newMainChild.append(subchild); } }); $('#' + panel.divElement.id + '-treenode-' + $(child).attr('data-concept-id')).closest('li').remove(); } }); $.each(parentsStrs, function(i, parentsStr) { if (parentsStr != parentsStrs[0]) { topUl.prepend(parentsStr); } }); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-down"); } else { $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("glyphicon-refresh"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).removeClass("icon-spin"); $("#" + panel.divElement.id + "-treeicon-" + conceptId).addClass("glyphicon-chevron-up"); } $("[draggable='true']").tooltip({ placement: 'left auto', trigger: 'hover', title: i18n_drag_this, animation: true, delay: 500 }); $("[draggable='true']").mouseover(function(e) { // console.log(e); var term = $(e.target).attr("data-term"); if (typeof term == "undefined") { term = $($(e.target).parent()).attr("data-term"); } icon = iconToDrag(term); }); }).fail(function() {}); } this.setToConcept = function(conceptId, term, definitionStatus, module, statedDescendants) { $("#" + panel.divElement.id + "-panelBody").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $.getJSON(options.serverUrl + "/browser/" + options.edition + "/" + options.release + "/concepts/" + conceptId + "/parents?form=" + panel.options.selectedView, function(result) { $.each(result, function(i, item) { if (typeof item.defaultTerm == "undefined") { item.defaultTerm = item.fsn.term; } }); }).done(function(result) { if (definitionStatus != "PRIMITIVE" && definitionStatus != "FULLY_DEFINED") { definitionStatus = "PRIMITIVE"; } if (conceptId == 138875005) statedDescendants = options.rootConceptDescendants; if (typeof term == "undefined" || typeof statedDescendants == "undefined") { $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId, function(res) { term = res.fsn.term; if (typeof res.statedDescendants == "undefined") $("#" + panel.divElement.id + "-txViewLabel2").closest("li").hide(); statedDescendants = res.statedDescendants; panel.setupParents(result, { conceptId: conceptId, defaultTerm: term, definitionStatus: definitionStatus, module: module, statedDescendants: statedDescendants }); }); } else { panel.setupParents(result, { conceptId: conceptId, defaultTerm: term, definitionStatus: definitionStatus, module: module, statedDescendants: statedDescendants }); } }).fail(function() { $("#" + panel.divElement.id + "-panelBody").html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); }); } // Subscription methods this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; // console.log('Subscribing to id: ' + panelId); var alreadySubscribed = false; $.each(panel.subscriptionsColor, function(i, field) { if (field == panelToSubscribe.markerColor) { alreadySubscribed = true; } }); if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { // console.log("listening in " + panel.divElement.id); panel.setToConcept(data.conceptId, data.term, data.definitionStatus, data.module, data.statedDescendants); }); panel.subscriptions.push(subscription); panelToSubscribe.subscribers.push(panel.divElement.id); panel.subscriptionsColor.push(panelToSubscribe.markerColor); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-subscribersMarker").show(); } this.refsetSubscribe = function(refsetId) { channel.subscribe("refsetSubscription-" + refsetId, function(data, envelope) { panel.setToConcept(data.conceptId); }); } this.unsubscribe = function(panelToUnsubscribe) { var aux = [], colors = [], unsubscribed = true; $.each(panel.subscriptionsColor, function(i, field) { if (field != panelToUnsubscribe.markerColor) { colors.push(field); } else { unsubscribed = false; } }); if (!unsubscribed) { panel.subscriptionsColor = colors; // console.log(panel.divElement.id); // console.log(panel.subscriptionsColor); colors = []; $.each(panelToUnsubscribe.subscribers, function(i, field) { if (field != panel.divElement.id) { aux.push(field); } }); panelToUnsubscribe.subscribers = aux; $.each(panelToUnsubscribe.subscriptionsColor, function(i, field) { colors.push(field); }); if (panelToUnsubscribe.subscribers.length == 0) { if (panelToUnsubscribe.subscriptions.length == 0) { $("#" + panelToUnsubscribe.divElement.id + "-subscribersMarker").hide(); } } else { // colors.push(panelToUnsubscribe.markerColor); } panelToUnsubscribe.subscriptionsColor = colors; // console.log(panelToUnsubscribe.divElement.id); // console.log(panelToUnsubscribe.subscriptionsColor); aux = []; $.each(panel.subscriptions, function(i, field) { if (panelToUnsubscribe.divElement.id == field.topic) { field.unsubscribe(); } else { aux.push(field); } }); panel.subscriptions = aux; if (panel.subscriptions.length == 0 && panel.subscribers.length == 0) { $("#" + panel.divElement.id + "-subscribersMarker").hide(); } } } this.loadMarkers = function() { var auxMarker = "", right = 0, top = 0, aux = false, visible = false; $.each(componentsRegistry, function(i, field) { var panelId = field.divElement.id; if ($("#" + panelId + "-subscribersMarker").is(':visible')) { visible = true; } }); if (panel.subscribers.length == 0) { right = 14; $("#" + panel.divElement.id + "-ownMarker").hide(); } else { if (!visible) { $("#" + panel.divElement.id + "-ownMarker").hide(); } aux = true; } if ($("#" + panel.divElement.id + "-subscribersMarker").is(':visible')) { $("#" + panel.divElement.id + "-panelTitle").html($("#" + panel.divElement.id + "-panelTitle").html().replace(/&nbsp;/g, '')); if (aux) { $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); } $.each(panel.subscriptionsColor, function(i, field) { auxMarker = auxMarker + "<i class='glyphicon glyphicon-bookmark' style='color: " + field + "; top:" + top + "px; right: " + right + "px;'></i>"; $("#" + panel.divElement.id + "-panelTitle").html("&nbsp&nbsp" + $("#" + panel.divElement.id + "-panelTitle").html()); top = top + 5; right = right + 10; }); $("#" + panel.divElement.id + "-subscribersMarker").html(auxMarker); } } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setupCanvas(); if (!conceptId || conceptId == 138875005) { this.setupParents([], { conceptId: 138875005, defaultTerm: "SNOMED CT Concept", definitionStatus: "PRIMITIVE", "statedDescendants": options.rootConceptDescendants }); } else { if (xhr != null) { xhr.abort(); //console.log("aborting call..."); } xhr = $.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/" + conceptId, function(result) { if (typeof result.statedDescendants == "undefined") $("#" + panel.divElement.id + "-txViewLabel2").closest("li").hide(); }).done(function(result) { if (panel.options.selectedView == 'stated') { panel.setToConcept(conceptId, result.defaultTerm, result.definitionStatus, result.module, result.statedDescendants); } else { panel.setToConcept(conceptId, result.defaultTerm, result.definitionStatus, result.module, result.inferredDescendants); } }).fail(function() { //console.log("Error"); }); } } function clearTaxonomyPanelSubscriptions(divElementId1) { var d1; $.each(componentsRegistry, function(i, field) { if (field.divElement.id == divElementId1) { d1 = field; } }); d1.unsubscribeAll(); $("#" + divElementId1).find('.linker-button').popover('toggle'); } function historyInTaxPanel(divElementId, conceptId) { $.each(componentsRegistry, function(i, field) { //console.log(field.divElement.id + ' == ' + divElementId); if (field.divElement.id == divElementId) { // $('#' + divElementId + '-searchBox').val(searchTerm); // field.search(searchTerm,0,100,false); field.setToConcept(conceptId); } }); $('.history-button').popover('hide'); } (function($) { $.fn.addTaxonomy = function(options) { this.filter("div").each(function() { var tx = new conceptDetails(this, options); }); }; }(jQuery)); /** * Created by termmed on 9/2/14. */ /** * Created by termmed on 9/1/14. */ function refsetPanel(divElement, options) { var panel = this; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var favoriteCall = null; this.type = "favorites"; panel.subscribers = []; var xhrMembers = null; this.getConceptId = function() { return this.conceptId; } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setUpPanel = function() { var context = { divElementId: panel.divElement.id } $(divElement).html(JST["views/refsetPlugin/main.hbs"](context)); } panel.setUpPanel(); this.loadRefsets = function() { // console.log(panel.options.manifest); if (panel.options.manifest) { panel.options.manifest.refsets.sort(function(a, b) { if (a.type == "daily-build" && a.type != b.type) return -1; if (a.type < b.type) return -1; if (a.type > b.type) return 1; if (a.defaultTerm < b.defaultTerm) return -1; if (a.defaultTerm > b.defaultTerm) return 1; return 0; }); var context = { divElementId: panel.divElement.id, refsets: panel.options.manifest.refsets } $("#" + panel.divElement.id + "-panelBody").html(JST["views/refsetPlugin/body.hbs"](context)); $('#' + panel.divElement.id + '-panelBody').find(".refset-item").click(function(event) { panel.loadMembers($(event.target).attr('data-concept-id'), $(event.target).attr('data-term'), 100, 0); channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); } else { $("#" + panel.divElement.id + "-panelBody").html("<div class='alert alert-danger'><span class='i18n' data-i18n-id='i18n_ajax_failed'><strong>Error</strong> while retrieving data from server...</span></div>"); } } panel.loadRefsets(); this.loadMembers = function(conceptId, term, returnLimit, skipTo, paginate) { var membersUrl = options.serverUrl + "/" + options.edition + "/" + options.release + "/members?referenceSet=" + conceptId + "&limit=100"; if (skipTo > 0) { membersUrl = membersUrl + "&offset=" + skipTo; } else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><i class='glyphicon glyphicon-refresh icon-spin'></i></td></tr>"); } var total; if (panel.options.manifest) { $.each(panel.options.manifest.refsets, function(i, field) { if (field.conceptId == panel.conceptId) { if (field.count) { total = field.count; } } }); } if (typeof total != "undefined") { //if (total < 25000){ paginate = 1; membersUrl = membersUrl + "&paginate=1"; //} } // console.log(membersUrl); if (xhrMembers != null) { xhrMembers.abort(); //console.log("aborting call..."); } xhrMembers = $.getJSON(membersUrl, function(result) { }).done(function(result) { var remaining = "asd"; if (typeof total == "undefined") total = result.total; if (total == skipTo) { remaining = 0; } else { if (total > (skipTo + returnLimit)) { remaining = total - (skipTo + returnLimit); } else { // if (result.details.total < returnLimit && skipTo != 0){ remaining = 0; // }else{ // remaining = result.details.total; // } } } if (remaining < returnLimit) { var returnLimit2 = remaining; } else { if (remaining != 0) { var returnLimit2 = returnLimit; } else { var returnLimit2 = 0; } } var context = { result: result, returnLimit: returnLimit2, remaining: remaining, divElementId: panel.divElement.id, skipTo: skipTo, term: term, conceptId: conceptId }; Handlebars.registerHelper('if_eq', function(a, b, opts) { if (opts != "undefined") { if (a == b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('if_gr', function(a, b, opts) { if (a) { if (a > b) return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper('hasCountryIcon', function(moduleId, opts) { if (countryIcons[moduleId]) return opts.fn(this); else return opts.inverse(this); }); if (result.total != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#' + panel.divElement.id + "-resultsTable").html(JST["views/refsetPlugin/members.hbs"](context)); } else { $('#' + panel.divElement.id + "-resultsTable").append(JST["views/refsetPlugin/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); skipTo = skipTo + returnLimit; panel.loadMembers(conceptId, term, returnLimit2, skipTo, paginate); }); $("#" + panel.divElement.id + "-sort").unbind(); $("#" + panel.divElement.id + "-sort").click(function() { $("#" + panel.divElement.id + "-sort").blur(); panel.loadMembers(conceptId, term, returnLimit2, 0, 1); }); } else { if (skipTo != 0) { $("#" + panel.divElement.id + "-moreMembers").remove(); $("#" + panel.divElement.id + "-resultsTable").find(".more-row").remove(); if (skipTo == 0) { $('#' + panel.divElement.id + "-resultsTable").html(JST["views/refsetPlugin/members.hbs"](context)); } else { $('#' + panel.divElement.id + "-resultsTable").append(JST["views/refsetPlugin/members.hbs"](context)); } $("#" + panel.divElement.id + "-moreMembers").click(function() { $("#" + panel.divElement.id + "-moreMembers").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); skipTo = skipTo + returnLimit; panel.loadMembers(conceptId, term, returnLimit2, skipTo, paginate); }); $("#" + panel.divElement.id + "-sort").unbind(); $("#" + panel.divElement.id + "-sort").click(function() { $("#" + panel.divElement.id + "-sort").blur(); panel.loadMembers(conceptId, term, returnLimit2, 0, 1); }); } else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } } $('#' + panel.divElement.id + '-resultsTable').find(".member-concept-row").click(function(event) { var clickedBadge = $(event.target).closest(".member-concept-row").find(".badge"); channel.publish(panel.divElement.id, { term: clickedBadge.attr('data-term'), module: clickedBadge.attr("data-module"), conceptId: clickedBadge.attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function(err) { if (xhrMembers.status === 0) { if (xhrMembers.statusText === 'abort') {} else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } } else { $("#" + panel.divElement.id + "-resultsTable").html("<tr><td class='text-muted' colspan='2'><span data-i18n-id='i18n_no_members' class='i18n'>This concept has no members</span></td></tr>"); } }); } } /** * Created by termmed on 9/1/14. */ function favoritePanel(divElement, options) { var panel = this; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); var favoriteCall = null; this.type = "favorites"; panel.subscribers = []; // if (!componentsRegistry){ // componentsRegistry = []; // componentsRegistry.push(panel); // }else{ // componentLoaded = false; // $.each(componentsRegistry, function(i, field) { // if (field.divElement.id == panel.divElement.id) { // componentLoaded = true; // } // }); // if (componentLoaded == false) { // componentsRegistry.push(panel); // } // } this.getConceptId = function() { return this.conceptId; } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); this.setUpFavs = function (){ // var context = { // divElementId: panel.divElement.id // } // $(divElement).html(JST["views/favorites/main.hbs"](context)); } //panel.setUpFavs(); this.loadFavs = function (){ $("#" + panel.divElement.id + "-panelBody").html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); var favs = stringToArray(localStorage.getItem("favs")), concepts = []; function loadFavsTemplate(concepts){ var context = { concepts: concepts } $("#" + panel.divElement.id + "-panelBody").html(JST["views/favorites/body.hbs"](context)); $('#' + panel.divElement.id + '-panelBody').find(".glyphicon-remove-circle").click(function (e) { var favs = stringToArray(localStorage.getItem("favs")), auxFavs = []; $.each(favs, function(i,field){ if (field != $(e.target).attr("data-concept-id")){ auxFavs.push(field); } }); localStorage.setItem("favs", auxFavs); localStorage.removeItem("conceptId:" + $(e.target).attr("data-concept-id")); panel.loadFavs(); }); $("#exportFavsXls").click(function(){ return ExcellentExport.excel(this, 'tableFavs'); }); $('#' + panel.divElement.id + '-panelBody').find(".fav-item").click(function (event) { channel.publish(panel.divElement.id, { term: $(event.target).attr('data-term'), module: $(event.target).attr("data-module"), conceptId: $(event.target).attr('data-concept-id'), source: panel.divElement.id }); }); } var length = favs.length - 1; $.each(favs, function(i, field){ var concept = localStorage.getItem("conceptId:" + field); concept = JSON.parse(concept); concepts.push(concept); }); loadFavsTemplate(concepts); } channel.subscribe("favsAction", function() { panel.loadFavs(); }); $("#" + panel.divElement.id + "-li").click(function(){ panel.loadFavs(); }); } /** * Created by termmed on 9/1/14. */ function queryComputerPanel(divElement, options) { var panel = this; panel.showId = false; var limit = 100; var skip = 0; var xhrTotal = null; var xhrExecute = null; panel.currentEx = 0; this.divElement = divElement; this.options = jQuery.extend(true, {}, options); this.type = "query-computer"; panel.subscribers = []; panel.totalResults = []; if (!componentsRegistry) { componentsRegistry = []; componentsRegistry.push(panel); } else { var componentLoaded = false; $.each(componentsRegistry, function(i, field) { if (field.divElement && field.divElement.id == panel.divElement.id) { componentLoaded = true; } }); if (componentLoaded == false) { componentsRegistry.push(panel); } } this.getDivId = function() { return this.divId; } this.getNextMarkerColor = function(color) { //console.log(color); var returnColor = 'black'; if (color == 'black') { returnColor = 'green'; } else if (color == 'green') { returnColor = 'purple'; } else if (color == 'purple') { returnColor = 'red'; } else if (color == 'red') { returnColor = 'blue'; } else if (color == 'blue') { returnColor = 'green'; } //console.log(returnColor); globalMarkerColor = returnColor; return returnColor; } //panel.markerColor = panel.getNextMarkerColor(globalMarkerColor); panel.markerColor = "asdasdasdas"; this.subscribe = function(panelToSubscribe) { var panelId = panelToSubscribe.divElement.id; var alreadySubscribed = false; if (!alreadySubscribed) { var subscription = channel.subscribe(panelId, function(data, envelope) { if (data) { panel.updateCanvas(data); } }); } $("#" + panelId + "-ownMarker").show(); $("#" + panel.divElement.id + "-subscribersMarker").show(); $("#" + panelId + "-ownMarker").show(); } this.setUpPanel = function() { var context = { divElementId: panel.divElement.id, examples: [{ title: "All excision procedures that are also procedures on the digestive system", context: [{ modifier: "Include", criterias: [ { criteria: "descendantOf", conceptId: "65801008", term: "Excision (procedure)" }, { criteria: "descendantOf", conceptId: "118673008", term: "Procedure on digestive system (procedure)" } ] }] }, { title: "All pneumonias except intersticial pneumonias", context: [{ modifier: "Include", criterias: [ { criteria: "descendantOf", conceptId: "233604007", term: "Pneumonia (disorder)" } ] }, { modifier: "Exclude", criterias: [ { criteria: "descendantOrSelfOf", conceptId: "64667001", term: "Interstitial pneumonia (disorder)" } ] } ] }, { title: "Hypertension related concepts, disorders, personal history and family history", context: [{ modifier: "Include", criterias: [ { criteria: "descendantOf", conceptId: "38341003", term: "Hypertensive disorder, systemic arterial (disorder)" } ] }, { modifier: "Include", criterias: [ { criteria: "self", conceptId: "160273004", term: "No family history: Hypertension (situation)" } ] }, { modifier: "Include", criterias: [ { criteria: "descendantOrSelfOf", conceptId: "161501007", term: "History of hypertension (situation)" } ] }, { modifier: "Include", criterias: [ { criteria: "descendantOrSelfOf", conceptId: "160357008", term: "Family history: Hypertension (situation)" } ] } ] } //{ // title: "", // context: [ // { // modifier: "", // criterias: [ // {criteria: "", conceptId: "", term: "", type: {conceptId: "", term: ''}} // ] // } // ] //}, ] }; $(divElement).html(JST["views/developmentQueryPlugin/main.hbs"](context)); $(divElement).find('textarea').unbind(); $(divElement).find('textarea').keypress(function(event) { if (event.which == 13) { event.preventDefault(); var s = $(this).val(); $(this).val(s + "\n"); } }); $('[data-toggle="tooltip"]').tooltip(); $("#" + panel.divElement.id + "-ExamplesModal").scrollspy({ target: '#' + panel.divElement.id + '-sidebar', offset: 80 }); var clicked = false; $("#" + panel.divElement.id + "-mynav li a").click( function() { //console.log('click...'); $('#' + panel.divElement.id + '-mycontent > div > h4').css('padding-top', 0); $($(this).attr('href') + ' > h4').css('padding-top', '50px'); clicked = true; } ); $("#" + panel.divElement.id + "-ExamplesModal").on('activate.bs.scrollspy', function() { //console.log('scrolling...'); if (!clicked) $('#' + panel.divElement.id + '-mycontent > div > h4').css('padding-top', 0); clicked = false; }); $("#" + panel.divElement.id + "-ExamplesModal").on('shown.bs.modal', function() { $("#" + panel.divElement.id + "-mycontentExamples").html(JST["views/developmentQueryPlugin/examples.hbs"](context)); context.examples.forEach(function(item, index) { var contextHtml = ""; item.context.forEach(function(loopContext) { //contextHtml+= JST[""(loopContext)]; contextHtml += JST["views/developmentQueryPlugin/criteria.hbs"](loopContext); }); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().html(contextHtml); if ($("#" + panel.divElement.id + "-ExpTab").hasClass("active")) { contextHtml = panel.exportToConstraintGrammar(true, false, false, $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first()); if (contextHtml.indexOf("(") == 0) contextHtml = contextHtml.substr(1, contextHtml.length - 2); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().html(contextHtml); } $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().find(".btn").addClass("disabled"); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".query-condition").each(function(index) { $(this).find(".line-number").html(index + 1); }); $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".loadExample").first().attr("data-htmlValue", $("#" + panel.divElement.id + "-" + index + "-modal-examples").find(".contentExamples").first().html()); }); $("#" + panel.divElement.id + "-mycontentExamples").find(".loadExample").unbind(); $("#" + panel.divElement.id + "-mycontentExamples").find(".loadExample").click(function(e) { var htmlToPut = $(e.target).attr("data-htmlValue"); if ($("#" + panel.divElement.id + "-ExpTab").hasClass("active")) { $('#' + panel.divElement.id + '-ExpText').html(htmlToPut); $('#' + panel.divElement.id + '-ExpText').val(htmlToPut.replace(/(<([^>]+)>)/ig, "").replace(/&nbsp;/g, " ").replace(/&lt;/g, "<")); $("#" + panel.divElement.id + "-ExamplesModal").modal("hide"); } else { $('#' + panel.divElement.id + '-listGroup').html(htmlToPut); $('#' + panel.divElement.id + '-listGroup').find(".btn").removeClass("disabled"); $('#' + panel.divElement.id + '-listGroup').find(".query-condition").each(function(i) { var critToUpdate = $(this); $(critToUpdate).find("small").remove(); $(critToUpdate).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); $("#" + panel.divElement.id + "-ExamplesModal").modal("hide"); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critToUpdate), true, function(resultCount) { $(critToUpdate).find("small").remove(); $(critToUpdate).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critToUpdate).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").unbind(); $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").click(function(e) { var prevValue = $(e.target).closest(".constraint").attr('data-criteria'); var newValue = $(e.target).html(); if (prevValue != newValue) { $(e.target).closest(".constraint").attr('data-criteria', newValue); $(e.target).closest("div").find("button").first().html(newValue + "&nbsp;"); var critToUpdate = $(e.target).closest(".query-condition"); $(critToUpdate).find("small").remove(); $(critToUpdate).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critToUpdate), true, function(resultCount) { $(critToUpdate).find("small").remove(); $(critToUpdate).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critToUpdate).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); } }); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); }); } }); }); if (!panel.typeArray || !panel.typeArray.length) { $.ajax({ type: "POST", url: options.serverUrl.replace("snomed", "expressions/") + options.edition + "/" + options.release + "/execute/brief", data: { expression: "< 410662002|Concept model attribute (attribute)|", limit: 5000, skip: 0, form: "inferred" }, dataType: "json", //timeout: 300000, success: function(result) { //console.log(result); //console.log(result.computeResponse.matches); result.computeResponse.matches.push({ conceptId: "<< 47429007", defaultTerm: "Associated with (attribute) [<<]" }); result.computeResponse.matches.push({ conceptId: "<< 405815000", defaultTerm: "Procedure device (attribute) [<<]" }); result.computeResponse.matches.push({ conceptId: "<< 405816004", defaultTerm: "Procedure morphology (attribute) [<<]" }); result.computeResponse.matches.push({ conceptId: "<< 363704007", defaultTerm: "Procedure site (attribute) [<<]" }); panel.typeArray = result.computeResponse.matches; panel.typeArray.sort(function(a, b) { if (a.defaultTerm < b.defaultTerm) return -1; if (a.defaultTerm > b.defaultTerm) return 1; return 0; }); } }).done(function(result) { }); } //$.getJSON(options.serverUrl + "/" + options.edition + "/" + options.release + "/concepts/410662002/children?form=inferred").done(function(result) { // //console.log(result); // result.sort(function (a, b) { // if (a.defaultTerm < b.defaultTerm) // return -1; // if (a.defaultTerm > b.defaultTerm) // return 1; // return 0; // }); // panel.typeArray = result; //}); //$("#" + panel.divElement.id + "-ExamplesModal").find(".btn").addClass("disabled"); //$("#" + panel.divElement.id + "-ExamplesModal").find(".loadExample").removeClass("disabled"); //$("#" + panel.divElement.id + "-ExamplesModal-close").removeClass("disabled"); var bindAddCriteriaFunction = function() { $(divElement).find(".addCriteria").unbind(); $(divElement).find(".addCriteria").disableTextSelect(); $(divElement).find(".addCriteria").click(function(e) { $(e.target).closest(".form-group").hide(); var criteria = $('#' + panel.divElement.id + '-selectedCriteria').html(); var typeSelected = $(e.target).attr("data-type"); if ($(divElement).find(".addedCriteria").length) typeSelected = $(divElement).find(".addedCriteria").first().attr("data-typeSelected"); $(e.target).closest(".form-inline").append(JST["views/developmentQueryPlugin/andCriteria.hbs"]({ criteria: criteria, typeSelected: typeSelected, types: panel.typeArray })); $(divElement).find(".addedCriteria").find(".selectTypeOpt").unbind(); $(divElement).find(".addedCriteria").find(".selectTypeOpt").click(function(e) { $(e.target).closest(".typeCritCombo").attr("data-type-term", $(e.target).attr("data-term")); $(e.target).closest(".typeCritCombo").attr("data-type-concept-id", $(e.target).attr("data-id")); var term = $(e.target).attr("data-term"); if (term.length > 15) term = term.substr(0, 14) + "..."; $(e.target).closest("div").find("span").first().html(term); }); $(divElement).find(".addedCriteria").find(".removeCriteria").unbind(); $(divElement).find(".addedCriteria").find(".removeCriteria").click(function(e) { $(e.target).closest(".addedCriteria").remove(); var foundAddedCriteria = $(divElement).find(".addedCriteria"); if (!foundAddedCriteria.length) { $("#" + panel.divElement.id + "-addCriteriaAnd").show(); } else { $(divElement).find(".addedCriteria").find(".dropFirstType").hide(); $(divElement).find(".addedCriteria").first().find(".dropFirstType").first().show(); //console.log($(foundAddedCriteria[foundAddedCriteria.length - 1]).find(".addCriteria").first().closest(".form-group")); $(foundAddedCriteria[foundAddedCriteria.length - 1]).find(".addCriteria").first().closest(".form-group").show(); } }); $(divElement).find(".addedCriteria").find("a[data-role='criteria-selector']").unbind(); $(divElement).find(".addedCriteria").find("a[data-role='criteria-selector']").click(function(e) { $(e.target).closest(".dropdown").find("span").first().html($(e.target).html()); }); bindAddCriteriaFunction(); }); }; bindAddCriteriaFunction(); $('#' + panel.divElement.id + '-addCriteriaAnd').unbind(); $('#' + panel.divElement.id + '-clearButton').unbind(); $('#' + panel.divElement.id + '-clearButton').disableTextSelect(); $('#' + panel.divElement.id + '-clearButton').click(function() { if (xhrExecute != null) xhrExecute.abort(); panel.setUpPanel(); }); $('#' + panel.divElement.id + '-copyConstraint').unbind(); $("#" + panel.divElement.id + "-copyConstraint").disableTextSelect(); var clientGrammar = new ZeroClipboard(document.getElementById(panel.divElement.id + "-copyConstraint")); clientGrammar.on("ready", function(readyEvent) { clientGrammar.on("copy", function(event) { // var grammar = panel.exportToConstraintGrammar(false, fullSyntax); //console.log(grammar); $("#" + panel.divElement.id + "-copyConstraint").addClass("animated rubberBand"); window.setTimeout(function() { $("#" + panel.divElement.id + "-copyConstraint").removeClass('animated rubberBand'); }, 1000); alertEvent("Constraint Grammar copied to clipboard", "success"); var clipboard = event.clipboardData; clipboard.setData("text/plain", panel.grammarToCopy); }); }); panel.options.devQuery = true; $('#' + panel.divElement.id + '-exportXls').unbind(); $('#' + panel.divElement.id + '-exportXls').click(function(e) { // var rowsHtml = ""; // alertEvent("Please wait", "info"); // panel.getTotalResults(function(){ // $.each(panel.allResults, function(i, field){ // rowsHtml+= "<tr><td>" + field.defaultTerm + "</td><td>" + field.conceptId + "</td></tr>"; // }); // $("#" + panel.divElement.id + "-outputBody2").html(rowsHtml); if (panel.allResults) { return ExcellentExport.excel(this, panel.divElement.id + '-output2'); } else { e.preventDefault(); e.stopPropagation(); panel.getTotalResults(); } // }); }); $('#' + panel.divElement.id + '-exportBriefcase').unbind(); $('#' + panel.divElement.id + '-exportBriefcase').click(function(e) { function exportToBriefcase() { var result = []; $.each(panel.allResults, function(i, field) { var loopConcept = {}; loopConcept.conceptId = field.conceptId; loopConcept.defaultTerm = field.defaultTerm; loopConcept.module = field.module; result.push(loopConcept); }); briefcase.addConcepts(result); } if (panel.allResults) { exportToBriefcase(); } else { alertEvent("Exporting concepts, please wait", "info"); panel.getTotalResults(function() { exportToBriefcase(); }); } }); $('#' + panel.divElement.id + '-open-grammar').unbind(); $("#" + panel.divElement.id + "-open-grammar").disableTextSelect(); $("#" + panel.divElement.id + "-open-grammar").click(function(e) { panel.updateGrammarModal(false); }); //-brief-syntax-button $('#home-' + panel.divElement.id + '-full-syntax-button').unbind(); $('#home-' + panel.divElement.id + '-full-syntax-button').disableTextSelect(); $('#home-' + panel.divElement.id + '-full-syntax-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-full-syntax-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-full-syntax-button').click(function(event) { panel.updateGrammarModal(true); }); $('#home-' + panel.divElement.id + '-brief-syntax-button').unbind(); $('#home-' + panel.divElement.id + '-brief-syntax-button').disableTextSelect(); $('#home-' + panel.divElement.id + '-brief-syntax-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-brief-syntax-button').click(function(event) { panel.updateGrammarModal(false); }); $('#' + panel.divElement.id + '-exportBriefcaseClean').unbind(); $('#' + panel.divElement.id + '-exportBriefcaseClean').click(function(e) { function exportToBriefcase() { var result = []; briefcase.emptyBriefcase(); $.each(panel.allResults, function(i, field) { var loopConcept = {}; loopConcept.conceptId = field.conceptId; loopConcept.defaultTerm = field.defaultTerm; loopConcept.module = field.module; result.push(loopConcept); }); briefcase.addConcepts(result); } if (panel.allResults) { exportToBriefcase(); } else { alertEvent("Exporting concepts, please wait", "info"); panel.getTotalResults(function() { exportToBriefcase(); }); } }); $('#' + panel.divElement.id + '-computeButton').unbind(); $('#' + panel.divElement.id + '-computeButton').click(function(e) { var query = $('#' + panel.divElement.id + '-input').val(); var request = { query: JSON.parse(query), pathId: options.path.id }; panel.compute(request); }); $("#" + panel.divElement.id).find("a[data-role='modifier-selector']").unbind(); $("#" + panel.divElement.id).find("a[data-role='modifier-selector']").click(function(e) { $('#' + panel.divElement.id + '-selectedModifier').html($(e.target).html()); }); $('#' + panel.divElement.id + '-selectedConcept').show(); $('#' + panel.divElement.id + '-selectedType').hide(); $('#' + panel.divElement.id + '-selectedTarget').hide(); $('#' + panel.divElement.id + '-searchTerm').hide(); $('#' + panel.divElement.id + '-searchTerm').unbind(); $('#' + panel.divElement.id + '-searchTerm').keyup(function(e) { if (e.keyCode === 13) { $('#' + panel.divElement.id + '-addCriteriaButton').click(); } }); $('#' + panel.divElement.id + '-formdropdown').hide(); $("#" + panel.divElement.id).find("a[data-role='criteria-selector']").unbind(); $("#" + panel.divElement.id).find("a[data-role='criteria-selector']").click(function(e) { $('#' + panel.divElement.id + '-selectedCriteria').html($(e.target).html()); //$(e.target).closest(".dropdown").find("span").first().html($(e.target).html()); var selectedCriteria = $(e.target).html(); if (selectedCriteria == "hasDescription") { $('#' + panel.divElement.id + '-selectedConcept').hide(); $('#' + panel.divElement.id + '-selectedType').hide(); $('#' + panel.divElement.id + '-selectedTarget').hide(); $('#' + panel.divElement.id + '-searchTerm').show(); $('#' + panel.divElement.id + '-formdropdown').hide(); } else if (selectedCriteria == "hasRelationship") { $('#' + panel.divElement.id + '-selectedConcept').hide(); $('#' + panel.divElement.id + '-selectedType').show(); $('#' + panel.divElement.id + '-selectedTarget').show(); $('#' + panel.divElement.id + '-searchTerm').hide(); $('#' + panel.divElement.id + '-formdropdown').show(); } else { $('#' + panel.divElement.id + '-selectedConcept').show(); $('#' + panel.divElement.id + '-selectedType').hide(); $('#' + panel.divElement.id + '-selectedTarget').hide(); $('#' + panel.divElement.id + '-searchTerm').hide(); $('#' + panel.divElement.id + '-formdropdown').hide(); } }); $("#" + panel.divElement.id).find("a[data-role='form-selector']").unbind(); $("#" + panel.divElement.id).find("a[data-role='form-selector']").click(function(e) { $('#' + panel.divElement.id + '-selectedForm').html($(e.target).html()); }); $('#' + panel.divElement.id + '-addCriteriaButton').unbind(); $('#' + panel.divElement.id + '-addCriteriaButton').click(function(e) { var modifier = $('#' + panel.divElement.id + '-selectedModifier').html(); var criteria = $('#' + panel.divElement.id + '-selectedCriteria').html(); var conceptIdDroped = $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId"); if ($('#' + panel.divElement.id + '-listGroup').find('.constraint[data-criteria="' + criteria + '"][data-concept-id="' + conceptIdDroped + '"]').length) { if ($('#' + panel.divElement.id + '-listGroup').find('.constraint[data-criteria="' + criteria + '"][data-concept-id="' + conceptIdDroped + '"]').closest(".query-condition").attr("data-modifier") == modifier) { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Criteria already added..."); } else { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Contradictory criteria..."); } } //if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-criteria="' + criteria + '"][data-modifier="' + modifier + '"][data-concept-id="' + conceptIdDroped + '"]').length){ // $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); // $('#' + panel.divElement.id + '-addmsg').html("Criteria already added..."); //}else if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-criteria="' + criteria + '"][data-concept-id="' + conceptIdDroped + '"]').length){ // $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); // $('#' + panel.divElement.id + '-addmsg').html("Contradictory criteria..."); //} else if (criteria == "hasDescription") { var searchTerm = $('#' + panel.divElement.id + '-searchTerm').val(); if (searchTerm == "") { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Enter a search term..."); } else { $('#' + panel.divElement.id + '-addmsg').html(""); $('#' + panel.divElement.id + '-conceptField').removeClass("has-error"); var context2 = { modifier: modifier, criteria: criteria, searchTerm: searchTerm }; $('#' + panel.divElement.id + '-listGroup').append(JST["views/developmentQueryPlugin/searchCriteria.hbs"](context2)); panel.renumLines(); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); $('#' + panel.divElement.id + '-selectedConcept').val(""); $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedType').val(""); $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedTarget').val(""); $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-searchTerm').val(""); } } else if (criteria == "hasRelationship") { var typeId = $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId"); var typeTerm = $('#' + panel.divElement.id + '-selectedType').val(); var targetId = $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId"); var targetTerm = $('#' + panel.divElement.id + '-selectedTarget').val(); var form = $('#' + panel.divElement.id + '-selectedForm').html(); if ((typeof typeId == "undefined" || typeId == "") && typeTerm == "" && (typeof targetId == "undefined" || targetId == "") && targetTerm == "") { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Drop a concept..."); } else { $('#' + panel.divElement.id + '-addmsg').html(""); $('#' + panel.divElement.id + '-conceptField').removeClass("has-error"); var context2 = { modifier: modifier, criteria: criteria, typeId: typeId, typeTerm: typeTerm, targetId: targetId, targetTerm: targetTerm, form: form }; $('#' + panel.divElement.id + '-listGroup').append(JST["views/developmentQueryPlugin/relsCriteria.hbs"](context2)); panel.renumLines(); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); $('#' + panel.divElement.id + '-selectedConcept').val(""); $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedType').val(""); $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedTarget').val(""); $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-searchTerm').val(""); } } else { var conceptId = $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId"); var term = $('#' + panel.divElement.id + '-selectedConcept').val(); if (typeof conceptId == "undefined" || conceptId == "" || term == "") { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Drop a concept..."); } else { $('#' + panel.divElement.id + '-addmsg').html(""); $('#' + panel.divElement.id + '-conceptField').removeClass("has-error"); var criterias = [{ criteria: criteria, conceptId: conceptId, term: term }]; if ($(divElement).find(".addedCriteria").length) { var typeSelected = $(divElement).find(".addedCriteria").first().attr("data-typeSelected"); $(divElement).find(".addedCriteria").each(function(i) { var addedConceptId = $(this).find(".andCriteriaConcept").first().attr("data-conceptId"); var addedTerm = $(this).find(".andCriteriaConcept").first().val(); var addedCrit = $(this).find(".addSelectCriteria").first().html(); if (addedConceptId && addedTerm) { criterias.forEach(function(criteriaAdded) { if (criteriaAdded.criteria == addedCrit && criteriaAdded.conceptId == addedConceptId) { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Criteria already added..."); return false; } }); var crit = { criteria: addedCrit, conceptId: addedConceptId, term: addedTerm }; if (typeSelected == "Refinement") { if ($(this).find(".typeCritCombo").first().attr("data-type-concept-id") == "false") { $('#' + panel.divElement.id + '-addmsg').html("Select a type..."); return false; } else { crit.type = { conceptId: $(this).find(".typeCritCombo").first().attr("data-type-concept-id"), term: $(this).find(".typeCritCombo").first().attr("data-type-term") }; } } criterias.push(crit); } else { $('#' + panel.divElement.id + '-conceptField').addClass("has-error"); $('#' + panel.divElement.id + '-addmsg').html("Drop a concept..."); return false; } }); } if ($('#' + panel.divElement.id + '-addmsg').html() == "") { $(divElement).find(".addedCriteria").remove(); $("#" + panel.divElement.id + "-addCriteriaAnd").show(); var context2 = { modifier: modifier, criterias: criterias }; // Add Excludes always at the end, and includes before exclude var foundExclude = false; $('#' + panel.divElement.id + '-listGroup').find(".query-condition").each(function(index) { var modifier = $(this).data('modifier'); if (modifier == "Exclude") { $(this).before(JST["views/developmentQueryPlugin/criteria.hbs"](context2)); var critAdded = $('#' + panel.divElement.id + '-listGroup').find(".query-condition")[index]; $(critAdded).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critAdded), true, function(resultCount) { $(critAdded).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critAdded).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); foundExclude = true; return false; } }); if (!foundExclude) { $('#' + panel.divElement.id + '-listGroup').append(JST["views/developmentQueryPlugin/criteria.hbs"](context2)); var critAdded = $('#' + panel.divElement.id + '-listGroup').find(".query-condition")[$('#' + panel.divElement.id + '-listGroup').find(".query-condition").length - 1]; $(critAdded).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critAdded), true, function(resultCount) { $(critAdded).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critAdded).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); } $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").unbind(); $('#' + panel.divElement.id + '-listGroup').find(".criteriaDropdownOption").click(function(e) { var prevValue = $(e.target).closest(".constraint").attr('data-criteria'); var newValue = $(e.target).html(); if (prevValue != newValue) { $(e.target).closest(".constraint").attr('data-criteria', newValue); $(e.target).closest("div").find("button").first().html(newValue + "&nbsp;"); var critToUpdate = $(e.target).closest(".query-condition"); $(critToUpdate).find("small").remove(); $(critToUpdate).append('<small class="text-muted pull-right glyphicon glyphicon-refresh icon-spin" style="position: relative; top: 12px;"></small>'); panel.execute("inferred", panel.exportToConstraintGrammar(false, false, critToUpdate), true, function(resultCount) { $(critToUpdate).find("small").remove(); $(critToUpdate).find(".glyphicon-refresh").first().remove(); var cont = parseInt(resultCount); $(critToUpdate).append('<small class="text-muted pull-right" style="position: relative; top: 10px;" title="This instruction involves the selection of ' + cont + ' concepts">' + cont + ' cpts</small>'); }); } }); panel.renumLines(); $(divElement).find(".removeLi").unbind(); $(divElement).find(".removeLi").disableTextSelect(); $(divElement).find(".removeLi").click(function(e) { $(e.target).closest("li").remove(); panel.renumLines(); }); $('#' + panel.divElement.id + '-selectedConcept').val(""); $('#' + panel.divElement.id + '-selectedConcept').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedType').val(""); $('#' + panel.divElement.id + '-selectedType').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-selectedTarget').val(""); $('#' + panel.divElement.id + '-selectedTarget').attr("data-conceptId", ""); $('#' + panel.divElement.id + '-searchTerm').val(""); } } } }); $('#' + panel.divElement.id + '-computeInferredButton2').unbind(); $('#' + panel.divElement.id + '-computeInferredButton2').disableTextSelect(); $('#' + panel.divElement.id + '-computeInferredButton2').click(function(e) { var expression = $.trim($("#" + panel.divElement.id + "-ExpText").val()); $('#' + panel.divElement.id + '-computeInferredButton2').addClass("disabled"); /* $.post(options.serverUrl.replace("snomed", "expressions/") + "parse/brief", { expression: expression }).done(function(res) { //console.log(res); if (res.validation) { */ panel.execute("inferred", expression, true); /* } else { alertEvent("Invalid Expression", "error") } }).fail(function(err) { //console.log(err); }).always(function() { */ $('#' + panel.divElement.id + '-computeInferredButton2').removeClass("disabled"); // }); }); $('#' + panel.divElement.id + '-computeInferredButton').unbind(); $('#' + panel.divElement.id + '-computeInferredButton').disableTextSelect(); $('#' + panel.divElement.id + '-computeInferredButton').click(function(e) { var grammar = panel.exportToConstraintGrammar(false, false); if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-modifier="Include"]').length) { panel.execute("inferred", grammar, true); } else { //console.log("add at least one include"); //alertEvent("Add at least one include", "error"); $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-danger'>Add at least one include</span>"); $("#" + panel.divElement.id + "-footer").html(""); //$('#' + panel.divElement.id + '-resultInfo').html('ERROR'); } }); $('#' + panel.divElement.id + '-computeOntoserver').unbind(); $('#' + panel.divElement.id + '-computeOntoserver').click(function(e) { var grammar = panel.exportToConstraintGrammar(false, false); if ($('#' + panel.divElement.id + '-listGroup').find('.query-condition[data-modifier="Include"]').length) { var ontoserverUrl = "http://52.21.192.244:8080/ontoserver/resources/ontology/findConceptsByQuery?versionedId=http%3A%2F%2Fsnomed.info%2Fsct%2F32506021000036107%2Fversion%2F20151130&field=shortId&field=label&field=primitive&field=inferredAxioms&format=json&start=0&rows=100"; var ontoserverConstraintParam = "&query=Constraint("; var sampleEncodedConstraint = "%3C%2019829001%20%7Cdisorder%20of%20lung%7C%3A%20%0A116676008%20%7Cassociated%20morphology%7C%20%3D%20*"; var encodedGrammar = encodeURIComponent(grammar); var executeUrl = ontoserverUrl + ontoserverConstraintParam + encodedGrammar + ")"; panel.currentEx++; $('#' + panel.divElement.id + '-resultInfo').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $('#' + panel.divElement.id + '-footer').html('<div class="progress progress-striped active"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"><span>Searching</span></div></div><p id="' + panel.divElement.id + '-waitingSearch-text" class="lead animated"></p>'); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("OntoServer is processing your instructions..."); $.getJSON(executeUrl, function(result) { //$.getJSON(panel.url + "rest/browser/concepts/" + panel.conceptId + "/children", function(result) { }).done(function(result) { //console.log(result); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + result.totalResults + " concepts</span>"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); //TODO: implement pagination with Ontoserver if (result.totalResults > 100) { $('#' + panel.divElement.id + '-footer').html("Showing first 100 matches"); } else { $('#' + panel.divElement.id + '-footer').html("Showing all matches"); } $.each(result.data, function(i, row) { $('#' + panel.divElement.id + '-outputBody').append("<tr style='cursor: pointer;' class='conceptResult' data-module='' data-concept-id='" + row.shortId + "' data-term='" + row.label + "'><td>" + row.label + "</td><td>" + row.shortId + "</td></tr>"); $('#' + panel.divElement.id + '-outputBody2').append("<tr><td>" + row.label + "</td><td>" + row.shortId + "</td></tr>"); }); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").unbind(); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").click(function(event) { //console.log("clicked",$(event.target).closest("tr").attr('data-term')); channel.publish(panel.divElement.id, { term: $(event.target).closest("tr").attr('data-term'), module: $(event.target).closest("tr").attr("data-module"), conceptId: $(event.target).closest("tr").attr('data-concept-id'), source: panel.divElement.id }); }); }).fail(function(err) { //console.log("Error",err); }); } else { $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-danger'>Add at least one include</span>"); $("#" + panel.divElement.id + "-footer").html(""); } }); }; panel.updateGrammarModal = function(fullSyntax) { if (fullSyntax) { $('#home-' + panel.divElement.id + '-full-syntax-button').addClass("btn-primary"); $('#home-' + panel.divElement.id + '-full-syntax-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').removeClass("btn-primary"); } else { $('#home-' + panel.divElement.id + '-full-syntax-button').removeClass("btn-primary"); $('#home-' + panel.divElement.id + '-full-syntax-button').addClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').removeClass("btn-default"); $('#home-' + panel.divElement.id + '-brief-syntax-button').addClass("btn-primary"); } panel.grammarToCopy = panel.exportToConstraintGrammar(false, fullSyntax); $("#" + panel.divElement.id + "-constraintGrammar").html(panel.exportToConstraintGrammar(true, fullSyntax)); }; panel.setUpPanel(); this.renumLines = function() { $('#' + panel.divElement.id + '-listGroup').find(".query-condition").each(function(index) { $(this).find(".line-number").html(index + 1); }); }; this.getTotalResults = function(callback) { if (xhrTotal != null) { xhrTotal.abort(); } panel.lastRequest.skip = 0; panel.lastRequest.limit = panel.lastTotalValues + 1; $('#' + panel.divElement.id + '-exportXls').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); xhrTotal = $.ajax({ type: "POST", url: options.serverUrl.replace("snomed", "expressions/") + "/" + options.edition + "/" + options.release + "/execute/brief", data: panel.lastRequest, dataType: "json", success: function(result) { xhrTotal = null; panel.allResults = result.computeResponse.matches; var rowsHtml = ""; if (panel.allResults && panel.allResults.length) { $.each(panel.allResults, function(i, field) { rowsHtml += "<tr><td>" + field.defaultTerm + "</td><td>" + field.conceptId + "</td></tr>"; }); } $("#" + panel.divElement.id + "-outputBody2").html(rowsHtml); $('#' + panel.divElement.id + '-exportXls').html('Download XLS <img style="height: 23px;" src="img/excel.png">'); if (callback) callback(); } }).always(function(result) { xhrTotal = null; }).fail(function() { alertEvent("Failed!", "error"); }); //xhrTotal = $.post(panel.lastUrl, panel.lastRequest).done(function(data){ // xhrTotal = null; // panel.allResults = data.matches; // var rowsHtml = ""; // if (panel.allResults && panel.allResults.length){ // $.each(panel.allResults, function(i, field){ // rowsHtml+= "<tr><td>" + field.defaultTerm + "</td><td>" + field.conceptId + "</td></tr>"; // }); // } // $("#" + panel.divElement.id + "-outputBody2").html(rowsHtml); // $('#' + panel.divElement.id + '-exportXls').html('Download XLS <img style="height: 23px;" src="img/excel.png">'); // if (callback) // callback(); //}).fail(function(){ // alertEvent("Failed!", "error"); //}); }; this.getExpressionForCondition = function(condition, htmlFormat, fullSyntax) { var grammar = ""; var operator = ""; if (condition.criteria == "self") { if (fullSyntax) { operator = "self "; } else { operator = ""; } } else if (condition.criteria == "descendantOf") { if (fullSyntax) { operator = "descendantOf "; } else { operator = "< "; } } else if (condition.criteria == "descendantOrSelfOf") { if (fullSyntax) { operator = "descendantOrSelfOf "; } else { operator = "<< "; } } else if (condition.criteria == "childrenOf") { if (fullSyntax) { operator = "childrenOf "; } else { operator = "<1 "; } } else if (condition.criteria == "ancestorOf") { if (fullSyntax) { operator = "ancestorOf "; } else { operator = "> "; } } else if (condition.criteria == "ancestorOrSelfOf") { if (fullSyntax) { operator = "ancestorOrSelfOf "; } else { operator = ">> "; } } else if (condition.criteria == "parentsOf") { if (fullSyntax) { operator = "parentsOf "; } else { operator = ">1 "; } } else if (condition.criteria == "hasDescription") { if (fullSyntax) { operator = "hasDescription "; } else { operator = "desc "; } } else if (condition.criteria == "hasRelationship") { if (fullSyntax) { operator = "hasRelationship "; } else { operator = "rel "; } } else if (condition.criteria == "isMemberOf") { if (fullSyntax) { operator = "isMemberOf "; } else { operator = "^ "; } }; var term = "|" + condition.term + "|"; if (htmlFormat) { operator = "<span class='exp-operators'>" + operator + "</span>"; term = "<span class='exp-term'>" + term + "</span>"; } if (condition.typeId) { if (condition.typeId == "*") { grammar = " * = " + operator + condition.conceptId + term; } else { var typeTerm = "|" + condition.typeTerm + "|"; if (htmlFormat) { term = "<span class='exp-term'>" + typeTerm + "</span>"; } grammar = condition.typeId + typeTerm + " = " + operator + condition.conceptId + term; } } else { grammar = operator + condition.conceptId + term; } return grammar; }; this.exportToConstraintGrammar = function(htmlFormat, fullSyntax, htmlObj, fullObjHtml) { var breakLine = " "; if (htmlFormat) { breakLine = "<br>"; } var grammar = ""; if ($('#' + panel.divElement.id + '-listGroup').find(".query-condition").length == 0 && !htmlObj && !fullObjHtml) { //console.log("Add at least one instruction..."); } else { var includes = []; var excludes = []; if (htmlObj) { var conditions = []; $(htmlObj).find(".constraint").each(function(index2) { var condition = { "criteria": $(this).attr('data-criteria'), "typeId": $(this).attr('data-type-concept-id'), "typeTerm": $(this).attr('data-type-term'), "conceptId": $(this).attr('data-concept-id'), "term": $(this).attr('data-term') }; conditions.push(condition); }); includes.push(conditions); } else { var objTouse = '#' + panel.divElement.id + '-listGroup'; if (fullObjHtml) objTouse = fullObjHtml $(objTouse).find(".query-condition").each(function(index) { var conditions = []; $(this).find(".constraint").each(function(index2) { var condition = { "criteria": $(this).attr('data-criteria'), "typeId": $(this).attr('data-type-concept-id'), "typeTerm": $(this).attr('data-type-term'), "conceptId": $(this).attr('data-concept-id'), "term": $(this).attr('data-term') }; conditions.push(condition); }); if ($(this).data('modifier') == "Exclude") { excludes.push(conditions); } else { includes.push(conditions); } }); } var isRefined = function(conditions) { var refined = false; if (conditions.length > 1) { if (conditions[1].typeId) { refined = true; } } return refined; }; //if (includes.length > 1) grammar += "("; $.each(includes, function(index, conditions) { if (index > 0) grammar += " OR "; if (conditions.length > 1 || isRefined(conditions)) grammar += " ("; if (isRefined(conditions)) { $.each(conditions, function(index2, condition) { grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (index2 == 0) { grammar += " : "; } else if (index2 < conditions.length - 1) { grammar += " , "; } if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } else { $.each(conditions, function(index2, condition) { if (index2 > 0) grammar += " AND "; grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } if (conditions.length > 1 || isRefined(conditions)) grammar += ") "; if (htmlFormat && index < includes.length - 1) { grammar += "<br>"; } }); //if (includes.length > 1) grammar += ")"; if (excludes.length > 0 && includes.length > 1) { grammar = "(" + grammar; grammar += ") MINUS "; if (htmlFormat) { grammar += "<br>"; } } else if (excludes.length > 0) { grammar += " MINUS "; if (htmlFormat) { grammar += "<br>"; } } if (excludes.length > 1) grammar += "("; $.each(excludes, function(index, conditions) { if (index > 0) grammar += " OR "; if (conditions.length > 1 || isRefined(conditions)) grammar += " ("; if (isRefined(conditions)) { $.each(conditions, function(index2, condition) { grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (index2 == 0) { grammar += " : "; } else if (index2 < conditions.length - 1) { grammar += " , "; } if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } else { $.each(conditions, function(index2, condition) { if (index2 > 0) grammar += " AND "; grammar += panel.getExpressionForCondition(condition, htmlFormat, fullSyntax); if (htmlFormat && index2 < conditions.length - 1) { grammar += "<br>"; } }); } if (conditions.length > 1 || isRefined(conditions)) grammar += ") "; if (htmlFormat && index < excludes.length - 1) { grammar += "<br>"; } }); if (excludes.length > 1) grammar += ")"; } grammar = grammar.trim(); //console.log(grammar.charAt(0)); //console.log(grammar.charAt(grammar.length-1)); //if (grammar.charAt(0) == "(" && grammar.charAt(grammar.length-1) == ")") { // grammar = grammar.substr(1,grammar.length-2); //} return grammar; }; this.execute = function(form, expression, clean, onlyTotal) { panel.currentEx++; var currentEx = panel.currentEx; //$('#' + panel.divElement.id + '-footer').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); if (onlyTotal) { limit = 1; skip = 0; } else { $('#' + panel.divElement.id + '-footer').html('<div class="progress progress-striped active"> <div class="progress-bar" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%"><span>Searching</span></div></div><p id="' + panel.divElement.id + '-waitingSearch-text" class="lead animated"></p>'); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("The server is processing your instructions..."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); setTimeout(function() { //console.log(currentEx, panel.currentEx); if (xhrExecute != null && currentEx == panel.currentEx) { $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("The server is still processing your instructions..."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); }, 600); } }, 15000); setTimeout(function() { if (xhrExecute != null && currentEx == panel.currentEx) { $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("This seems to be a complex set of instructions, still processing..."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); }, 600); } }, 30000); setTimeout(function() { if (xhrExecute != null && currentEx == panel.currentEx) { $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); $("#" + panel.divElement.id + "-waitingSearch-text").html(""); $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); $("#" + panel.divElement.id + "-waitingSearch-text").html("The server is processing a complex set of instructions. This action might not be supported in a public server. Some times instructions can be simplified by specifying conditions using concepts closer in the hierarchy to the intended results, avoiding unnecessary selections of large portions of the terminology."); setTimeout(function() { $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); }, 600); }, 600); } }, 45000); //setTimeout(function(){ // $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeOutLeft"); // setTimeout(function(){ // $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeOutLeft"); // if (xhrExecute != null && currentEx == panel.currentEx){ // $("#" + panel.divElement.id + "-waitingSearch-text").html(""); // $("#" + panel.divElement.id + "-waitingSearch-text").addClass("fadeInRight"); // $("#" + panel.divElement.id + "-waitingSearch-text").html("Instruction set exceeds maximum allowed time for computation. Some times instructions can be simplified by specifying conditions using concepts closer in the hierarchy to the intended results, avoiding unnecessary selections of large portions of the terminology."); // setTimeout(function(){ // $("#" + panel.divElement.id + "-waitingSearch-text").removeClass("fadeInRight"); // }, 600); // } // }, 600); //}, 61000); $('#' + panel.divElement.id + '-resultInfo').html("<i class='glyphicon glyphicon-refresh icon-spin'></i>"); if (clean) { $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); limit = 100; skip = 0; } } var data = { expression: expression, limit: limit, skip: skip, form: form }; console.log("normal " + expression); var strippedExpression1 = expression.replace(/\|.*?\|/guim, ''); var strippedExpression = strippedExpression1.replace(/\n/guim, ''); console.log("stripped " + strippedExpression); panel.lastRequest = data; page = skip / limit; var expressionURL; if (options.queryBranch == 'MAIN') { expressionURL = options.queryServerUrl + "/" + options.queryBranch + "/concepts?module=900000000000207008&ecl=" + strippedExpression + "&offset=" + skip + "&limit=" + limit + "&expand=fsn()"; } else if (options.queryBranch.includes('SNOMEDCT-US')) { expressionURL = options.queryServerUrl + "/" + options.queryBranch + "/concepts?&ecl=" + strippedExpression + "&offset=" + skip + "&limit=" + limit + "&expand=fsn()"; } else { expressionURL = options.queryServerUrl + "/" + options.queryBranch + "/concepts?ecl=" + strippedExpression + "&page=" + page + "&size=" + limit; } console.log("queryURL " + expressionURL); if (xhrExecute != null && !onlyTotal) xhrExecute.abort(); var xhrExecute2 = $.ajax({ type: "GET", url: expressionURL, //timeout: 300000,lasturl success: function(result) { //if (result.paserResponse.validation) { data = result; //result.computeResponse.matches if (!onlyTotal) { $("#" + panel.divElement.id + "-exportResults").removeClass("disabled"); if (data.performanceCutOff) { if (!data.totalElements) { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.total + " concepts. <span class='text-danger'>This query cannot be completed in real-time, please schedule a Cloud executions. Results below are incomplete and some conditions were not tested. </span></span>"); } else { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.totalElements + " concepts. <span class='text-danger'>This query cannot be completed in real-time, please schedule a Cloud executions. Results below are incomplete and some conditions were not tested. </span></span>"); } } else { if (!data.totalElements) { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.total + " concepts</span>"); } else { $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-muted small'>Found " + data.totalElements + " concepts</span>"); } } $.each(data.items, function(i, row) { $('#' + panel.divElement.id + '-outputBody').append("<tr style='cursor: pointer;' class='conceptResult' data-module='" + row.moduleId + "' data-concept-id='" + row.id + "' data-term='" + row.fsn.term + "'><td>" + row.fsn.term + "</td><td>" + row.id + "</td></tr>"); $('#' + panel.divElement.id + '-outputBody2').append("<tr><td>" + row.fsn.term + "</td><td>" + row.id + "</td></tr>"); }); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").unbind(); $('#' + panel.divElement.id + '-outputBody').find(".conceptResult").click(function(event) { //console.log("clicked",$(event.target).closest("tr").attr('data-term')); channel.publish(panel.divElement.id, { term: $(event.target).closest("tr").attr('data-term'), module: $(event.target).closest("tr").attr("data-module"), conceptId: $(event.target).closest("tr").attr('data-concept-id'), source: panel.divElement.id, showConcept: true }); }); if (!data.totalElements) { panel.lastTotalValues = data.total; if (limit + skip < data.total) { $('#' + panel.divElement.id + '-footer').html("<span id='" + panel.divElement.id + "-more'>Show more (viewing " + (limit + skip) + " of " + data.total + " total)</span>"); } else { $('#' + panel.divElement.id + '-footer').html("Showing all " + data.total + " matches"); } } else { panel.lastTotalValues = data.totalElements; if (limit + skip < data.totalElements) { $('#' + panel.divElement.id + '-footer').html("<span id='" + panel.divElement.id + "-more'>Show more (viewing " + (limit + (page * limit)) + " of " + data.totalElements + " total)</span>"); } else { $('#' + panel.divElement.id + '-footer').html("Showing all " + data.totalElements + " matches"); } } $('#' + panel.divElement.id + '-more').unbind(); $('#' + panel.divElement.id + '-more').click(function(e) { skip = (page * limit) + 100; panel.execute(form, expression, false); }); } else { onlyTotal(data.total); } } }).done(function(result) { // done xhrExecute2 = null; }).fail(function(jqXHR) { //console.log(xhrExecute2); if (jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.computeResponse && jqXHR.responseJSON.computeResponse.message) { $('#' + panel.divElement.id + '-outputBody').html(""); $('#' + panel.divElement.id + '-outputBody2').html(""); $("#" + panel.divElement.id + "-footer").html(""); $('#' + panel.divElement.id + '-resultInfo').html("<span class='text-danger'>" + jqXHR.responseJSON.computeResponse.message + "</span>"); } else { var textStatus = xhrExecute2.statusText; if (textStatus != "abort") { if (xhrExecute2.status == 0) textStatus = "timeout"; xhrExecute2 = null; if (textStatus === 'timeout') { // $("#" + panel.divElement.id + "-syntax-result").html('<span class="label label-danger">ERROR</span>'); // $("#" + panel.divElement.id + "-results").html("Timeout..."); if (!onlyTotal) { $('#' + panel.divElement.id + '-footer').html("<p class='lead'>Instruction set exceeds maximum allowed time for computation. Some times instructions can be simplified by specifying conditions using concepts closer in the hierarchy to the intended results, avoiding unnecessary selections of large portions of the terminology.</p>"); $('#' + panel.divElement.id + '-resultInfo').html("This query cannot be completed in real-time."); //$('#' + panel.divElement.id + '-footer').html("Timeout Error"); } else { onlyTotal("Error"); } } else { if (!onlyTotal) { $("#" + panel.divElement.id + "-syntax-result").html('<span class="label label-danger">ERROR</span>'); $("#" + panel.divElement.id + "-results").html("Error..."); } else { onlyTotal("Error"); } } } } }); if (!onlyTotal) xhrExecute = xhrExecute2; } } /** * Created by alo on 7/18/14. */ icon = document.createElement("img"); channel = postal.channel("Selections"); Handlebars.registerHelper('i18n', function (i18n, defaultV){ if (typeof window[i18n] == "undefined"){ //console.log(i18n, "=", defaultV); return defaultV; }else{ return window[i18n]; } }); Handlebars.registerHelper('if_undefined', function (a, opts) { if (opts != "undefined") { if (typeof a == "undefined") return opts.fn(this); else return opts.inverse(this); } }); Handlebars.registerHelper("if_eqInd", function(a, b, opts){ if ((parseInt(a) + 1) == parseInt(b)) return opts.fn(this); else return opts.inverse(this); }); Handlebars.registerHelper("console", function(a){ console.log(a); }); $(document).on('dragend', function(){ removeHighlight(); }); function setDefaultTerm(concept) { if (concept) { if (concept.fsn) { if (typeof concept.fsn == "object") { concept.defaultTerm = concept.fsn.term; } else { concept.defaultTerm = concept.fsn; } } if (concept.relationships) { concept.statedRelationships = []; concept.relationships.forEach(function(r) { r.type.defaultTerm = r.type.fsn.term; r.target.defaultTerm = r.target.fsn.term; if (r.characteristicType == "STATED_RELATIONSHIP") { concept.statedRelationships.push(r); } }) // Remove statedRelationships from relationships array concept.statedRelationships.forEach(function(r) { concept.relationships.splice(concept.relationships.indexOf(r), 1); }) } if (concept.definitionStatus == "PRIMITIVE") { concept.definitionStatus = "PRIMITIVE"; } } } function removeHighlight(){ $(document).find('.drop-highlighted').removeClass('drop-highlighted'); } function allowDrop(ev) { ev.preventDefault(); var aux; if ($(ev.target).attr("data-droppable") == "true"){ aux = $(ev.target); }else{ aux = $(ev.target).closest("div"); } // while (typeof $(aux).closest('div').attr('ondrop') != "undefined"){ // aux = $(aux).closest('div'); // } $(aux).addClass("drop-highlighted"); } function dropField(ev){ var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } $(ev.target).val(term); $(ev.target).attr("data-conceptId", conceptId); } } function iconToDrag(text){ var CVS = document.createElement('canvas'), ctx = CVS.getContext('2d'); CVS.width = 300; CVS.height = 300; ctx.font = "15px sans-serif"; ctx.strokeText(text, 10, 20); var icon = document.createElement("img"); icon.src = CVS.toDataURL(); return icon; } function drag(ev, id) { var dataText = ""; var term = "", conceptId = ""; $.each(ev.target.attributes, function (){ if (this.name.substr(0, 4) == "data"){ ev.dataTransfer.setData(this.name.substr(5), this.value); if (this.name.substr(5) == "concept-id"){ conceptId = this.value; } if (this.name.substr(5) == "term"){ term = this.value; } } }); icon = iconToDrag(term); if (navigator.userAgent.indexOf("Chrome") > -1){ icon = iconToDrag(term); ev.dataTransfer.setDragImage(icon, 0, 0); }else{ // icon = iconToDrag(term); } ev.dataTransfer.setDragImage(icon, 0, 0); dataText = conceptId + "|" + term; ev.dataTransfer.setData("Text", dataText); ev.dataTransfer.setData("divElementId", id); } function dropS(ev){ $(document).find('.drop-highlighted').removeClass('drop-highlighted'); ev.preventDefault(); var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } $(ev.target).val(term); var id = $(ev.target).attr("id").replace("-searchBox", ""); $.each(componentsRegistry, function(i, field) { if (field.divElement.id == id) { field.search(term, 0, 100, false); } }); } } function dropC(ev, id) { $(document).find('.drop-highlighted').removeClass('drop-highlighted'); ev.preventDefault(); var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } var divElementID = id; var panelAct; $.each(componentsRegistry, function (i, field){ if (field.divElement.id == divElementID){ panelAct = field; } }); if (conceptId && panelAct.conceptId != conceptId) { panelAct.conceptId = conceptId; panelAct.updateCanvas(); channel.publish(panelAct.divElement.id, { term: term, conceptId: panelAct.conceptId, source: panelAct.divElement.id }); } } } function dropF(ev, id) { var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);"){ var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); var module = ev.dataTransfer.getData("module"); if (typeof term == "undefined"){ term = text.substr(i); } var favs = stringToArray(localStorage.getItem("favs")), found = false; $.each(favs, function(i,field){ if (field == conceptId){ found = true; } }); var concept = { defaultTerm: term, conceptId: conceptId, module: module }; if (!found){ // console.log(concept); favs.push(conceptId); localStorage.setItem("favs", favs); localStorage.setItem("conceptId:" + conceptId, JSON.stringify(concept)); } channel.publish("favsAction"); } } function dropT(ev, id) { $(document).find('.drop-highlighted').removeClass('drop-highlighted'); ev.preventDefault(); var text = ev.dataTransfer.getData("Text"); if (text != "javascript:void(0);") { var i = 0; while (text.charAt(i) != "|" && i < text.length){ i++; } var divElementId = id; var panel; var conceptId = ev.dataTransfer.getData("concept-id"); if (typeof conceptId == "undefined" && i < text.length){ conceptId = text.substr(0, i); } var term = ev.dataTransfer.getData("term"); if (typeof term == "undefined"){ term = text.substr(i); } var definitionStatus = ev.dataTransfer.getData("def-status"); var module = ev.dataTransfer.getData("module"); $.each(componentsRegistry, function (i, field){ if (field.divElement.id == divElementId){ panel = field; } }); if (conceptId) { if (panel.options.selectedView == "undefined") { panel.options.selectedView = "inferred"; } if (typeof conceptId != "undefined") { var d = new Date(); var time = d.getTime(); panel.history.push({term: term, conceptId: conceptId, time: time}); panel.setToConcept(conceptId, term, definitionStatus, module); channel.publish(panel.divElement.id, { term: term, conceptId: conceptId, source: panel.divElement.id }); } } } } function stringToArray (string){ if (typeof string == "string"){ var ind = 0, auxString, array = []; while (ind < string.length){ auxString = ""; while (string.substr(ind, 1) != "," && ind < string.length){ auxString = auxString + string.substr(ind,1); ind++; } array.push(auxString); ind++; } return(array); }else{ return false; } } var lastEventTime = (new Date()).getTime(); function alertEvent(message, type) { var t = (new Date()).getTime(); if (t-lastEventTime < 10 && message.toLowerCase().includes("copied")) { // Ignore notification } else { $.notify(message,type); } lastEventTime = t; } if (!String.prototype.endsWith) { String.prototype.endsWith = function(searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; }
OWLAP-147 - inferred attributes restored - stated attribute ordering asserted
snomed-interaction-components/js/snomed-interaction-components-2.1.js
OWLAP-147 - inferred attributes restored - stated attribute ordering asserted
<ide><path>nomed-interaction-components/js/snomed-interaction-components-2.1.js <ide> + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; <ide> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(5, program5, data),fn:self.program(2, program2, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), "undefined", options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(27, program27, data),fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), "undefined", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(34, program34, data),fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), "undefined", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(55, program55, data),fn:self.program(25, program25, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), "undefined", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), "undefined", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n </tbody>\n </table>\n"; <ide> return buffer; <ide> } <ide> <ide> var buffer = "", stack1; <ide> buffer += "\n\n "; <del> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), {hash:{},inverse:self.noop,fn:self.programWithDepth(6, program6, data, depth0),data:data}); <add> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.relationships), {hash:{},inverse:self.noop,fn:self.program(6, program6, data),data:data}); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <ide> return buffer; <ide> } <del>function program6(depth0,data,depth1) { <add>function program6(depth0,data) { <ide> <ide> var buffer = "", stack1; <ide> buffer += "\n "; <del> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(7, program7, data, depth1),data:data}); <add> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.programWithDepth(7, program7, data, depth0),data:data}); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <ide> return buffer; <ide> } <del>function program7(depth0,data,depth2) { <add>function program7(depth0,data,depth1) { <ide> <ide> var buffer = "", stack1, helper, options; <del> buffer += "\n <tr class='inferred-rel\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n '>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(12, program12, data),fn:self.program(10, program10, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n ham\n </td>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <add> buffer += "\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.programWithDepth(8, program8, data, depth1),data:data},helper ? helper.call(depth0, (depth0 && depth0.characteristicType), "INFERRED_RELATIONSHIP", options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.characteristicType), "INFERRED_RELATIONSHIP", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n "; <add> return buffer; <add> } <add>function program8(depth0,data,depth2) { <add> <add> var buffer = "", stack1, helper, options; <add> buffer += "\n <tr class='inferred-rel\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(9, program9, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth2 && depth2.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n '>\n <td>\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(13, program13, data),fn:self.program(11, program11, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n " <add> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\n </td>\n <td>\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(17, program17, data),fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n " <ide> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>"; <add> + "</td>\n <td>"; <ide> if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>TypeId</th><th style='padding: 3px;'>TargetId</th><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" <add> + "</td>\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(21, program21, data),fn:self.program(19, program19, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>TypeId</th><th style='padding: 3px;'>TargetId</th><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>" <ide> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <ide> + "</td><td style='padding: 3px;'>" <ide> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <ide> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <del> return buffer; <del> } <del>function program8(depth0,data) { <del> <del> <del> return "\n highlightEffectiveTime\n "; <del> } <del> <del>function program10(depth0,data) { <del> <del> var buffer = "", stack1, helper; <del> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <del> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "\" data-concept-id=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-term=\"" <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-def-status=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; <del> return buffer; <del> } <del> <del>function program12(depth0,data) { <del> <del> var buffer = "", stack1, helper; <del> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <del> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "\" data-concept-id=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-term=\"" <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-def-status=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; <del> return buffer; <del> } <del> <del>function program14(depth0,data) { <del> <del> var buffer = "", stack1, helper; <del> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <del> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "\" data-concept-id=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-term=\"" <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-def-status=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; <del> return buffer; <del> } <del> <del>function program16(depth0,data) { <del> <del> var buffer = "", stack1, helper; <del> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <del> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "\" data-concept-id=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-term=\"" <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-def-status=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; <del> return buffer; <del> } <del> <del>function program18(depth0,data) { <del> <del> var buffer = "", helper, options; <del> buffer += "\n <td><span class='i18n' data-i18n-id='i18n_stated'>" <del> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_stated", "Stated", options) : helperMissing.call(depth0, "i18n", "i18n_stated", "Stated", options))) <del> + "</span>\n "; <del> return buffer; <del> } <del> <del>function program20(depth0,data) { <del> <del> var buffer = "", stack1, helper, options; <del> buffer += "\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(23, program23, data),fn:self.program(21, program21, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program21(depth0,data) { <del> <del> var buffer = "", helper, options; <del> buffer += "\n <td><span class='i18n' data-i18n-id='i18n_inferred'>" <del> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_inferred", "Inferred", options) : helperMissing.call(depth0, "i18n", "i18n_inferred", "Inferred", options))) <del> + "</span>\n "; <del> return buffer; <del> } <del> <del>function program23(depth0,data) { <del> <del> var buffer = "", helper, options; <del> buffer += "\n <td><span class='i18n' data-i18n-id='i18n_other'>" <del> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_other", "Other", options) : helperMissing.call(depth0, "i18n", "i18n_other", "Other", options))) <del> + "</span>\n "; <del> return buffer; <del> } <del> <del>function program25(depth0,data) { <del> <del> <del> return "\n "; <del> } <del> <del>function program27(depth0,data) { <del> <del> var buffer = "", stack1; <del> buffer += "\n\n "; <del> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.statedRelationships), {hash:{},inverse:self.noop,fn:self.program(28, program28, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program28(depth0,data) { <del> <del> var buffer = "", stack1; <del> buffer += "\n "; <del> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(29, program29, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program29(depth0,data) { <del> <del> var buffer = "", stack1, helper, options; <del> buffer += "\n <tr class='stated-rel\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(8, program8, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n '>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(30, program30, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>"; <del> if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(20, program20, data),fn:self.program(18, program18, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; <del> if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td><td style='padding: 3px;'>"; <del> if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td><td style='padding: 3px;'>"; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <del> return buffer; <del> } <del>function program30(depth0,data) { <del> <del> var buffer = "", stack1, helper; <del> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <del> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "\" data-concept-id=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-term=\"" <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-def-status=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; <del> return buffer; <del> } <del> <del>function program32(depth0,data) { <del> <del> var buffer = "", stack1, helper; <del> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <del> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "\" data-concept-id=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-term=\"" <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\" data-def-status=\"" <del> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; <del> return buffer; <del> } <del> <del>function program34(depth0,data) { <del> <del> var buffer = "", stack1; <del> buffer += "\n "; <del> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(35, program35, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program35(depth0,data) { <del> <del> var buffer = "", stack1; <del> buffer += "\n "; <del> stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(36, program36, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program36(depth0,data) { <del> <del> var buffer = "", stack1; <del> buffer += "\n "; <del> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(37, program37, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program37(depth0,data) { <del> <del> var buffer = "", stack1, helper, options; <del> buffer += "\n <tr class='stated-rel\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(38, program38, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options) : helperMissing.call(depth0, "if_eq", (depth0 && depth0.effectiveTime), ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.highlightByEffectiveTime), options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n '>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(42, program42, data),fn:self.program(40, program40, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(46, program46, data),fn:self.program(44, program44, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <del> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>"; <del> if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(50, program50, data),fn:self.program(48, program48, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000010007", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; <del> if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td><td style='padding: 3px;'>"; <del> if (helper = helpers.effectiveTime) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.effectiveTime); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td><td style='padding: 3px;'>"; <del> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <del> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <del> buffer += escapeExpression(stack1) <del> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <del> return buffer; <del> } <del>function program38(depth0,data) { <add> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <add> return buffer; <add> } <add>function program9(depth0,data) { <ide> <ide> <ide> return "\n highlightEffectiveTime\n "; <ide> } <ide> <del>function program40(depth0,data) { <add>function program11(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <add> + "')\" data-module=\""; <ide> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <ide> return buffer; <ide> } <ide> <del>function program42(depth0,data) { <add>function program13(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "')\" data-module=\""; <add> + "')\" data-module=\""; <ide> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <ide> return buffer; <ide> } <ide> <del>function program44(depth0,data) { <add>function program15(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> return buffer; <ide> } <ide> <del>function program46(depth0,data) { <add>function program17(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> return buffer; <ide> } <ide> <del>function program48(depth0,data) { <add>function program19(depth0,data) { <ide> <ide> var buffer = "", helper, options; <ide> buffer += "\n <td><span class='i18n' data-i18n-id='i18n_stated'>" <ide> return buffer; <ide> } <ide> <del>function program50(depth0,data) { <add>function program21(depth0,data) { <ide> <ide> var buffer = "", stack1, helper, options; <ide> buffer += "\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(53, program53, data),fn:self.program(51, program51, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options)); <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(24, program24, data),fn:self.program(22, program22, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.charType)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId), "900000000000011006", options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <ide> return buffer; <ide> } <del>function program51(depth0,data) { <add>function program22(depth0,data) { <ide> <ide> var buffer = "", helper, options; <ide> buffer += "\n <td><span class='i18n' data-i18n-id='i18n_inferred'>" <ide> return buffer; <ide> } <ide> <del>function program53(depth0,data) { <add>function program24(depth0,data) { <ide> <ide> var buffer = "", helper, options; <ide> buffer += "\n <td><span class='i18n' data-i18n-id='i18n_other'>" <ide> return buffer; <ide> } <ide> <del>function program55(depth0,data) { <del> <del> var buffer = "", stack1; <del> buffer += "\n "; <del> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(35, program35, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del> <del>function program57(depth0,data) { <del> <del> var buffer = "", stack1, helper, options; <del> buffer += "\n "; <del> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.noop,fn:self.program(58, program58, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n"; <del> return buffer; <del> } <del>function program58(depth0,data) { <del> <del> <del> return "\n <p>No additional relationships</p>\n "; <del> } <del> <del>function program60(depth0,data) { <add>function program26(depth0,data) { <add> <add> <add> return "\n <p>No additional relationships</p>\n"; <add> } <add> <add>function program28(depth0,data) { <ide> <ide> var buffer = "", stack1, helper, options; <ide> buffer += "\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" <ide> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) <ide> + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; <del> stack1 = helpers.each.call(depth0, (depth0 && depth0.additionalRels), {hash:{},inverse:self.noop,fn:self.program(61, program61, data),data:data}); <add> stack1 = helpers.each.call(depth0, (depth0 && depth0.additionalRels), {hash:{},inverse:self.noop,fn:self.program(29, program29, data),data:data}); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n </tbody>\n </table>\n"; <ide> return buffer; <ide> } <del>function program61(depth0,data) { <add>function program29(depth0,data) { <ide> <ide> var buffer = "", stack1; <ide> buffer += "\n "; <del> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(62, program62, data),data:data}); <add> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(30, program30, data),data:data}); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <ide> return buffer; <ide> } <del>function program62(depth0,data) { <add>function program30(depth0,data) { <ide> <ide> var buffer = "", stack1, helper, options; <ide> buffer += "\n <tr>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(65, program65, data),fn:self.program(63, program63, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(33, program33, data),fn:self.program(31, program31, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n " <ide> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <ide> + "</td>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(69, program69, data),fn:self.program(67, program67, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(37, program37, data),fn:self.program(35, program35, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n " <ide> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <ide> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <ide> return buffer; <ide> } <del>function program63(depth0,data) { <add>function program31(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> return buffer; <ide> } <ide> <del>function program65(depth0,data) { <add>function program33(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> return buffer; <ide> } <ide> <del>function program67(depth0,data) { <add>function program35(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> return buffer; <ide> } <ide> <del>function program69(depth0,data) { <add>function program37(depth0,data) { <ide> <ide> var buffer = "", stack1, helper; <ide> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <ide> return buffer; <ide> } <ide> <del>function program71(depth0,data) { <add>function program39(depth0,data) { <ide> <ide> <ide> return "\n <p>No Axioms found</p>\n"; <ide> } <ide> <del>function program73(depth0,data) { <add>function program41(depth0,data) { <add> <add> var buffer = "", stack1, helper, options; <add> buffer += "\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(42, program42, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n"; <add> return buffer; <add> } <add>function program42(depth0,data) { <ide> <ide> var buffer = "", stack1; <add> buffer += "\n "; <add> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(43, program43, data),data:data}); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <del> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), {hash:{},inverse:self.noop,fn:self.program(74, program74, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n"; <del> return buffer; <del> } <del>function program74(depth0,data) { <add> return buffer; <add> } <add>function program43(depth0,data) { <ide> <ide> var buffer = "", stack1, helper, options; <del> buffer += "\n <p>Class Axiom - "; <add> buffer += "\n <p>Axiom - "; <ide> if (helper = helpers.axiomId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.axiomId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" <add> + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) <del> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" <add> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) <del> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" <add> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) <del> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" <add> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) <del> + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; <del> stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(75, program75, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; <del> return buffer; <del> } <del>function program75(depth0,data) { <add> + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; <add> stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(44, program44, data),data:data}); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; <add> return buffer; <add> } <add>function program44(depth0,data) { <ide> <ide> var buffer = "", stack1; <add> buffer += "\n "; <add> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(45, program45, data),data:data}); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <del> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(76, program76, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program76(depth0,data) { <add> return buffer; <add> } <add>function program45(depth0,data) { <ide> <ide> var buffer = "", stack1, helper, options; <del> buffer += "\n <tr>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(30, program30, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <add> buffer += "\n <tr>\n <td>\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(48, program48, data),fn:self.program(46, program46, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n " <ide> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <add> + "</td>\n <td>\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(17, program17, data),fn:self.program(15, program15, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n " <ide> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>"; <add> + "</td>\n <td>"; <ide> if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>Axiom </span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; <add> + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>Axiom </span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; <ide> if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <ide> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <del> return buffer; <del> } <del> <del>function program78(depth0,data) { <add> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <add> return buffer; <add> } <add>function program46(depth0,data) { <add> <add> var buffer = "", stack1, helper; <add> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <add> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "')\" data-module=\""; <add> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "\" data-concept-id=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-term=\"" <add> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-def-status=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; <add> return buffer; <add> } <add> <add>function program48(depth0,data) { <add> <add> var buffer = "", stack1, helper; <add> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <add> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "')\" data-module=\""; <add> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "\" data-concept-id=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-term=\"" <add> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-def-status=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; <add> return buffer; <add> } <add> <add>function program50(depth0,data) { <ide> <ide> <ide> return "\n <p>No GCI's found</p>\n"; <ide> } <ide> <del>function program80(depth0,data) { <add>function program52(depth0,data) { <add> <add> var buffer = "", stack1, helper, options; <add> buffer += "\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(53, program53, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "stated", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n"; <add> return buffer; <add> } <add>function program53(depth0,data) { <ide> <ide> var buffer = "", stack1; <add> buffer += "\n "; <add> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(54, program54, data),data:data}); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <del> stack1 = helpers.each.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), {hash:{},inverse:self.noop,fn:self.program(81, program81, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n"; <del> return buffer; <del> } <del>function program81(depth0,data) { <add> return buffer; <add> } <add>function program54(depth0,data) { <ide> <ide> var buffer = "", stack1, helper, options; <del> buffer += "\n <p>GCI Axiom - "; <add> buffer += "\n <p>GCI - "; <ide> if (helper = helpers.axiomId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.axiomId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" <add> + "</p>\n <table class='table table-bordered'>\n <thead>\n <tr>\n <th><span class='i18n' data-i18n-id='i18n_type'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_type", "Type", options) : helperMissing.call(depth0, "i18n", "i18n_type", "Type", options))) <del> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" <add> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_destination'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_destination", "Destination", options) : helperMissing.call(depth0, "i18n", "i18n_destination", "Destination", options))) <del> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" <add> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_group'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_group", "Group", options) : helperMissing.call(depth0, "i18n", "i18n_group", "Group", options))) <del> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" <add> + "</span></th>\n <th><span class='i18n' data-i18n-id='i18n_char_type'>" <ide> + escapeExpression((helper = helpers.i18n || (depth0 && depth0.i18n),options={hash:{},data:data},helper ? helper.call(depth0, "i18n_char_type", "CharType", options) : helperMissing.call(depth0, "i18n", "i18n_char_type", "CharType", options))) <del> + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; <del> stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(82, program82, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; <del> return buffer; <del> } <del>function program82(depth0,data) { <add> + "</span></th>\n </tr>\n </thead>\n <tbody>\n "; <add> stack1 = helpers.each.call(depth0, (depth0 && depth0.relationships), {hash:{},inverse:self.noop,fn:self.program(55, program55, data),data:data}); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n </tbody>\n </table>\n <br><br><br>\n "; <add> return buffer; <add> } <add>function program55(depth0,data) { <ide> <ide> var buffer = "", stack1; <add> buffer += "\n "; <add> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(56, program56, data),data:data}); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n "; <del> stack1 = helpers['if'].call(depth0, (depth0 && depth0.active), {hash:{},inverse:self.noop,fn:self.program(83, program83, data),data:data}); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n "; <del> return buffer; <del> } <del>function program83(depth0,data) { <add> return buffer; <add> } <add>function program56(depth0,data) { <ide> <ide> var buffer = "", stack1, helper, options; <del> buffer += "\n <tr>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(32, program32, data),fn:self.program(30, program30, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <add> buffer += "\n <tr>\n <td>\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(48, program48, data),fn:self.program(46, program46, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n " <ide> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.type)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>\n "; <del> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(16, program16, data),fn:self.program(14, program14, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <del> if(stack1 || stack1 === 0) { buffer += stack1; } <del> buffer += "\n " <add> + "</td>\n <td>\n "; <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.program(59, program59, data),fn:self.program(57, program57, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus), "PRIMITIVE", options)); <add> if(stack1 || stack1 === 0) { buffer += stack1; } <add> buffer += "\n " <ide> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <del> + "</td>\n <td>"; <add> + "</td>\n <td>"; <ide> if (helper = helpers.groupId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.groupId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>GCI Axiom</span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; <add> + "</td>\n <td><span class='i18n' data-i18n-id='i18n_additional'>GCI Axiom</span>\n <button type=\"button\" class=\"btn btn-link unobtrusive-icon more-fields-button pull-right\" data-container=\"body\" data-toggle=\"popover\" data-placement=\"left\" data-content=\"\n <table border='1'><tr><th style='padding: 3px;'>Modifier</th><th style='padding: 3px;'>Effective Time</th><th style='padding: 3px;'>ModuleId</th></tr>\n <tr><td style='padding: 3px;'>"; <ide> if (helper = helpers.modifier) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.modifier); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <ide> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <ide> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <ide> buffer += escapeExpression(stack1) <del> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <del> return buffer; <del> } <del> <del> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options)); <add> + "</td></tr>\n </table>\n \" data-html=\"true\"><i class=\"glyphicon glyphicon-info-sign\"></i></button>\n </td>\n </tr>\n "; <add> return buffer; <add> } <add>function program57(depth0,data) { <add> <add> var buffer = "", stack1, helper; <add> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <add> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "')\" data-module=\""; <add> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "\" data-concept-id=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-term=\"" <add> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-def-status=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\"><span class=\"badge alert-warning\">&nbsp;</span></a>&nbsp;&nbsp;\n "; <add> return buffer; <add> } <add> <add>function program59(depth0,data) { <add> <add> var buffer = "", stack1, helper; <add> buffer += "\n <a href=\"javascript:void(0);\" style=\"color: inherit;text-decoration: inherit;\" draggable = \"true\" ondragstart=\"drag(event, '"; <add> if (helper = helpers.divElementId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.divElementId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "')\" data-module=\""; <add> if (helper = helpers.moduleId) { stack1 = helper.call(depth0, {hash:{},data:data}); } <add> else { helper = (depth0 && depth0.moduleId); stack1 = typeof helper === functionType ? helper.call(depth0, {hash:{},data:data}) : helper; } <add> buffer += escapeExpression(stack1) <add> + "\" data-concept-id=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.conceptId)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-term=\"" <add> + escapeExpression(((stack1 = ((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.fsn)),stack1 == null || stack1 === false ? stack1 : stack1.term)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\" data-def-status=\"" <add> + escapeExpression(((stack1 = ((stack1 = (depth0 && depth0.target)),stack1 == null || stack1 === false ? stack1 : stack1.definitionStatus)),typeof stack1 === functionType ? stack1.apply(depth0) : stack1)) <add> + "\"><span class=\"badge alert-warning\">&equiv;</span></a>&nbsp;&nbsp;\n "; <add> return buffer; <add> } <add> <add> stack1 = (helper = helpers.if_eq || (depth0 && depth0.if_eq),options={hash:{},inverse:self.noop,fn:self.program(1, program1, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options) : helperMissing.call(depth0, "if_eq", ((stack1 = (depth0 && depth0.options)),stack1 == null || stack1 === false ? stack1 : stack1.selectedView), "inferred", options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n\n"; <del> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(60, program60, data),fn:self.program(57, program57, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.additionalRels), options) : helperMissing.call(depth0, "if_undefined", (depth0 && depth0.additionalRels), options)); <add> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(28, program28, data),fn:self.program(26, program26, data),data:data},helper ? helper.call(depth0, (depth0 && depth0.additionalRels), options) : helperMissing.call(depth0, "if_undefined", (depth0 && depth0.additionalRels), options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n\n"; <del> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(73, program73, data),fn:self.program(71, program71, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options)); <add> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(41, program41, data),fn:self.program(39, program39, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.classAxioms), options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n"; <del> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(80, program80, data),fn:self.program(78, program78, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options)); <add> stack1 = (helper = helpers.if_undefined || (depth0 && depth0.if_undefined),options={hash:{},inverse:self.program(52, program52, data),fn:self.program(50, program50, data),data:data},helper ? helper.call(depth0, ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options) : helperMissing.call(depth0, "if_undefined", ((stack1 = (depth0 && depth0.firstMatch)),stack1 == null || stack1 === false ? stack1 : stack1.gciAxioms), options)); <ide> if(stack1 || stack1 === 0) { buffer += stack1; } <ide> buffer += "\n"; <ide> return buffer; <ide> panel.statedRoles.push(loopRel); <ide> } <ide> }); <add> <add> function sortAxiomRelationships (relationships){ <add> relationships.sort(function(a, b) { <add> if (a.groupId < b.groupId) { <add> return -1; <add> } else if (a.groupId > b.groupId) { <add> return 1; <add> } else { <add> if (a.type.conceptId == 116680003) { <add> return -1; <add> } <add> if (b.type.conceptId == 116680003) { <add> return 1; <add> } <add> if (a.target.defaultTerm < b.target.defaultTerm) <add> return -1; <add> if (a.target.defaultTerm > b.target.defaultTerm) <add> return 1; <add> return 0; <add> } <add> }); <add> }; <add> <ide> firstMatch.classAxioms.forEach(function(axiom) { <ide> if(axiom.active){ <ide> axiom.relationships.forEach(function(rel) { <ide> } <ide> else{ <ide> rel.axiomId = axiom.axiomId; <del> rel.type = 'Axiom'; <ide> panel.attributesFromAxioms.push(rel); <ide> } <ide> }); <ide> } <add> sortAxiomRelationships(axiom.relationships); <ide> }); <ide> firstMatch.gciAxioms.forEach(function(axiom) { <ide> if(axiom.active){ <ide> axiom.relationships.forEach(function(rel) { <ide> if(rel.active && rel.type.conceptId !== "116680003"){ <ide> rel.axiomId = axiom.axiomId; <del> rel.type = 'GCI'; <ide> panel.attributesFromAxioms.push(rel); <ide> } <ide> }); <ide> } <add> sortAxiomRelationships(axiom.relationships); <ide> }); <ide> <ide> if (firstMatch.statedDescendants) { <ide> } <ide> }); <ide> } <add> <ide> if (firstMatch.statedRelationships) { <ide> firstMatch.statedRelationships.sort(function(a, b) { <ide> if (a.groupId < b.groupId) {
JavaScript
mit
738cbf51a3ecee92a31558cf8f67654e4613d123
0
usablica/persian.js
/** * PersianJs v0.3.0 * https://github.com/usablica/persian.js * MIT licensed * * Copyright (C) 2012 usabli.ca and other contributors */ (function(){var VERSION="0.4.0",hasModule=typeof module!=="undefined"&&module.exports;var arabicNumbers=["١","٢","٣","٤","٥","٦","٧","٨","٩","٠"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"],englishNumbers=["1","2","3","4","5","6","7","8","9","0"];function PersianJs(str){this._str=str}function _arabicChar(value){if(!value){return}var arabicChars=["ي","ك","‍","دِ","بِ","زِ","ذِ","ِشِ","ِسِ","‌","ى"],persianChars=["ی","ک","","د","ب","ز","ذ","ش","س","","ی"];for(var i=0,charsLen=arabicChars.length;i<charsLen;i++){value=value.replace(new RegExp(arabicChars[i],"g"),persianChars[i])}this._str=value;return this}function _persianNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _arabicNumber(value){if(!value){return}value=value.toString();for(var i=0,numbersLen=arabicNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(arabicNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _englishNumber(value){if(!value){return}value=value.toString();var englishNumbers=["1","2","3","4","5","6","7","8","9","0"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"];for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(englishNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _toEnglishNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i]).replace(new RegExp(arabicNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _decodeURL(value){if(!value){return}var old="";while(old!=value){old=value;value=value.replace(/(http\S+?)\%20/g,"$1‌‌‌_‌‌‌")}value=value.replace(/(http\S+)/g,function(s,p){return decodeURI(p)});value=value.replace(/\u200c\u200c\u200c_\u200c\u200c\u200c/g,"%20");this._str=value;return this}function _switchKey(value){if(!value){return}var persianChar=["ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ","ظ","ط","ز","ر","ذ","د","پ","و","؟"],englishChar=["q","w","e","r","t","y","u","i","o","p","[","]","a","s","d","f","g","h","j","k","l",";","'","z","x","c","v","b","n","m",",","?"];for(var i=0,charsLen=persianChar.length;i<charsLen;i++){value=value.replace(new RegExp(persianChar[i],"g"),englishChar[i])}this._str=value;return this}function _digitsToWords(value){var delimiter,digit,i,iThree,numbers,parts,result,resultThree,three;if(!isFinite(value)){return""}if(typeof value!=="string"){value=value.toString()}parts=["","هزار","میلیون","میلیارد","تریلیون","کوادریلیون","کویینتیلیون","سکستیلیون"];numbers={0:["","صد","دویست","سیصد","چهارصد","پانصد","ششصد","هفتصد","هشتصد","نهصد"],1:["","ده","بیست","سی","چهل","پنجاه","شصت","هفتاد","هشتاد","نود"],2:["","یک","دو","سه","چهار","پنج","شش","هفت","هشت","نه"],two:["ده","یازده","دوازده","سیزده","چهارده","پانزده","شانزده","هفده","هجده","نوزده"],zero:"صفر"};delimiter=" و ";valueParts=value.split("").reverse().join("").replace(/\d{3}(?=\d)/g,"$&,").split("").reverse().join("").split(",").map(function(str){return Array(4-str.length).join("0")+str});result=function(){var _results;_results=[];for(iThree in valueParts){three=valueParts[iThree];resultThree=function(){var _i,_len,_results1;_results1=[];for(i=_i=0,_len=three.length;_i<_len;i=++_i){digit=three[i];if(i===1&&digit==="1"){_results1.push(numbers.two[three[2]])}else if((i!==2||three[1]!=="1")&&numbers[i][digit]!==""){_results1.push(numbers[i][digit])}else{continue}}return _results1}();resultThree=resultThree.join(delimiter);_results.push(resultThree+" "+parts[valueParts.length-iThree-1])}return _results}();result=result.filter(function(x){return x.trim()!==""});result=result.join(delimiter).trim();if(result===""){result=numbers.zero}this._str=result;return this}function _halfSpace(value){if(!value){return}var pattern;pattern=/((\s\u0645\u06CC)+( )+([\u0600-\u06EF]{1,}){1,})/g;value=value.replace(new RegExp(pattern),"$2‌$4");pattern=/(([\u0600-\u06EF]{1,})+( )+(ای|ایی|اند|ایم|اید|ام){1})/g;value=value.replace(new RegExp(pattern),"$2‌$4");this._str=value;return this}var persianJs=function(inputStr){if(!inputStr||inputStr===""){throw new Error("Input is null or empty.")}return new PersianJs(inputStr)};persianJs.version=VERSION;persianJs.fn=PersianJs.prototype={clone:function(){return persianJs(this)},value:function(){return this._str},toString:function(){return this._str.toString()},set:function(value){this._str=String(value);return this},arabicChar:function(){return _arabicChar.call(this,this._str)},persianNumber:function(){return _persianNumber.call(this,this._str)},arabicNumber:function(){return _arabicNumber.call(this,this._str)},englishNumber:function(){return _englishNumber.call(this,this._str)},toEnglishNumber:function(){return _toEnglishNumber.call(this,this._str)},fixURL:function(){return _decodeURL.call(this,this._str)},decodeURL:function(){return _decodeURL.call(this,this._str)},switchKey:function(){return _switchKey.call(this,this._str)},digitsToWords:function(){return _digitsToWords.call(this,this._str)},halfSpace:function(){return _halfSpace.call(this,this._str)}};if(hasModule){module.exports=persianJs}if(typeof ender==="undefined"){this["persianJs"]=persianJs}if(typeof define==="function"&&define.amd){define("persianJs",[],function(){return persianJs})}})(); //# sourceMappingURL=./persian-min.map
persian.min.js
/** * PersianJs v0.3.0 * https://github.com/usablica/persian.js * MIT licensed * * Copyright (C) 2012 usabli.ca and other contributors */ (function(){var VERSION="0.4.0",hasModule=typeof module!=="undefined"&&module.exports;var arabicNumbers=["١","٢","٣","٤","٥","٦","٧","٨","٩","٠"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"],englishNumbers=["1","2","3","4","5","6","7","8","9","0"];function PersianJs(str){this._str=str}function _arabicChar(value){if(!value){return}var arabicChars=["ي","ك","‍","دِ","بِ","زِ","ذِ","ِشِ","ِسِ","‌","ى"],persianChars=["ی","ک","","د","ب","ز","ذ","ش","س","","ی"];for(var i=0,charsLen=arabicChars.length;i<charsLen;i++){value=value.replace(new RegExp(arabicChars[i],"g"),persianChars[i])}this._str=value;return this}function _persianNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _arabicNumber(value){if(!value){return}value=value.toString();for(var i=0,numbersLen=arabicNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(arabicNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _englishNumber(value){if(!value){return}value=value.toString();var englishNumbers=["1","2","3","4","5","6","7","8","9","0"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"];for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(englishNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _toEnglishNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i]).replace(new RegExp(arabicNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _decodeURL(value){if(!value){return}var old="";while(old!=value){old=value;value=value.replace(/(http\S+?)\%20/g,"$1‌‌‌_‌‌‌")}value=value.replace(/(http\S+)/g,function(s,p){return decodeURI(p)});value=value.replace(/\u200c\u200c\u200c_\u200c\u200c\u200c/g,"%20");this._str=value;return this}function _switchKey(value){if(!value){return}var persianChar=["ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ","ظ","ط","ز","ر","ذ","د","پ","و","؟"],englishChar=["q","w","e","r","t","y","u","i","o","p","[","]","a","s","d","f","g","h","j","k","l",";","'","z","x","c","v","b","n","m",",","?"];for(var i=0,charsLen=persianChar.length;i<charsLen;i++){value=value.replace(new RegExp(persianChar[i],"g"),englishChar[i])}this._str=value;return this}function _digitsToWords(value){var delimiter,digit,i,iThree,numbers,parts,result,resultThree,three;if(!isFinite(value)){return""}if(typeof value!=="string"){value=value.toString()}parts=["","هزار","میلیون","میلیارد","تریلیون","کوادریلیون","کویینتیلیون","سکستیلیون"];numbers={0:["","صد","دویصت","سیصد","چهارصد","پانصد","ششصد","هفتصد","هشتصد","نهصد"],1:["","ده","بیست","سی","چهل","پنجاه","شصت","هفتاد","هشتاد","نود"],2:["","یک","دو","سه","چهار","پنج","شش","هفت","هشت","نه"],two:["ده","یازده","دوازده","سیزده","چهارده","پانزده","شانزده","هفده","هجده","نوزده"],zero:"صفر"};delimiter=" و ";valueParts=value.split("").reverse().join("").replace(/\d{3}(?=\d)/g,"$&,").split("").reverse().join("").split(",").map(function(str){return Array(4-str.length).join("0")+str});result=function(){var _results;_results=[];for(iThree in valueParts){three=valueParts[iThree];resultThree=function(){var _i,_len,_results1;_results1=[];for(i=_i=0,_len=three.length;_i<_len;i=++_i){digit=three[i];if(i===1&&digit==="1"){_results1.push(numbers.two[three[2]])}else if((i!==2||three[1]!=="1")&&numbers[i][digit]!==""){_results1.push(numbers[i][digit])}else{continue}}return _results1}();resultThree=resultThree.join(delimiter);_results.push(resultThree+" "+parts[valueParts.length-iThree-1])}return _results}();result=result.filter(function(x){return x.trim()!==""});result=result.join(delimiter).trim();if(result===""){result=numbers.zero}this._str=result;return this}function _halfSpace(value){if(!value){return}var pattern;pattern=/((\s\u0645\u06CC)+( )+([\u0600-\u06EF]{1,}){1,})/g;value=value.replace(new RegExp(pattern),"$2‌$4");pattern=/(([\u0600-\u06EF]{1,})+( )+(ای|ایی|اند|ایم|اید|ام){1})/g;value=value.replace(new RegExp(pattern),"$2‌$4");this._str=value;return this}var persianJs=function(inputStr){if(!inputStr||inputStr===""){throw new Error("Input is null or empty.")}return new PersianJs(inputStr)};persianJs.version=VERSION;persianJs.fn=PersianJs.prototype={clone:function(){return persianJs(this)},value:function(){return this._str},toString:function(){return this._str.toString()},set:function(value){this._str=String(value);return this},arabicChar:function(){return _arabicChar.call(this,this._str)},persianNumber:function(){return _persianNumber.call(this,this._str)},arabicNumber:function(){return _arabicNumber.call(this,this._str)},englishNumber:function(){return _englishNumber.call(this,this._str)},toEnglishNumber:function(){return _toEnglishNumber.call(this,this._str)},fixURL:function(){return _decodeURL.call(this,this._str)},decodeURL:function(){return _decodeURL.call(this,this._str)},switchKey:function(){return _switchKey.call(this,this._str)},digitsToWords:function(){return _digitsToWords.call(this,this._str)},halfSpace:function(){return _halfSpace.call(this,this._str)}};if(hasModule){module.exports=persianJs}if(typeof ender==="undefined"){this["persianJs"]=persianJs}if(typeof define==="function"&&define.amd){define("persianJs",[],function(){return persianJs})}})(); //# sourceMappingURL=./persian-min.map
Fix typo in persian min js
persian.min.js
Fix typo in persian min js
<ide><path>ersian.min.js <ide> * <ide> * Copyright (C) 2012 usabli.ca and other contributors <ide> */ <del>(function(){var VERSION="0.4.0",hasModule=typeof module!=="undefined"&&module.exports;var arabicNumbers=["١","٢","٣","٤","٥","٦","٧","٨","٩","٠"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"],englishNumbers=["1","2","3","4","5","6","7","8","9","0"];function PersianJs(str){this._str=str}function _arabicChar(value){if(!value){return}var arabicChars=["ي","ك","‍","دِ","بِ","زِ","ذِ","ِشِ","ِسِ","‌","ى"],persianChars=["ی","ک","","د","ب","ز","ذ","ش","س","","ی"];for(var i=0,charsLen=arabicChars.length;i<charsLen;i++){value=value.replace(new RegExp(arabicChars[i],"g"),persianChars[i])}this._str=value;return this}function _persianNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _arabicNumber(value){if(!value){return}value=value.toString();for(var i=0,numbersLen=arabicNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(arabicNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _englishNumber(value){if(!value){return}value=value.toString();var englishNumbers=["1","2","3","4","5","6","7","8","9","0"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"];for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(englishNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _toEnglishNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i]).replace(new RegExp(arabicNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _decodeURL(value){if(!value){return}var old="";while(old!=value){old=value;value=value.replace(/(http\S+?)\%20/g,"$1‌‌‌_‌‌‌")}value=value.replace(/(http\S+)/g,function(s,p){return decodeURI(p)});value=value.replace(/\u200c\u200c\u200c_\u200c\u200c\u200c/g,"%20");this._str=value;return this}function _switchKey(value){if(!value){return}var persianChar=["ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ","ظ","ط","ز","ر","ذ","د","پ","و","؟"],englishChar=["q","w","e","r","t","y","u","i","o","p","[","]","a","s","d","f","g","h","j","k","l",";","'","z","x","c","v","b","n","m",",","?"];for(var i=0,charsLen=persianChar.length;i<charsLen;i++){value=value.replace(new RegExp(persianChar[i],"g"),englishChar[i])}this._str=value;return this}function _digitsToWords(value){var delimiter,digit,i,iThree,numbers,parts,result,resultThree,three;if(!isFinite(value)){return""}if(typeof value!=="string"){value=value.toString()}parts=["","هزار","میلیون","میلیارد","تریلیون","کوادریلیون","کویینتیلیون","سکستیلیون"];numbers={0:["","صد","دویصت","سیصد","چهارصد","پانصد","ششصد","هفتصد","هشتصد","نهصد"],1:["","ده","بیست","سی","چهل","پنجاه","شصت","هفتاد","هشتاد","نود"],2:["","یک","دو","سه","چهار","پنج","شش","هفت","هشت","نه"],two:["ده","یازده","دوازده","سیزده","چهارده","پانزده","شانزده","هفده","هجده","نوزده"],zero:"صفر"};delimiter=" و ";valueParts=value.split("").reverse().join("").replace(/\d{3}(?=\d)/g,"$&,").split("").reverse().join("").split(",").map(function(str){return Array(4-str.length).join("0")+str});result=function(){var _results;_results=[];for(iThree in valueParts){three=valueParts[iThree];resultThree=function(){var _i,_len,_results1;_results1=[];for(i=_i=0,_len=three.length;_i<_len;i=++_i){digit=three[i];if(i===1&&digit==="1"){_results1.push(numbers.two[three[2]])}else if((i!==2||three[1]!=="1")&&numbers[i][digit]!==""){_results1.push(numbers[i][digit])}else{continue}}return _results1}();resultThree=resultThree.join(delimiter);_results.push(resultThree+" "+parts[valueParts.length-iThree-1])}return _results}();result=result.filter(function(x){return x.trim()!==""});result=result.join(delimiter).trim();if(result===""){result=numbers.zero}this._str=result;return this}function _halfSpace(value){if(!value){return}var pattern;pattern=/((\s\u0645\u06CC)+( )+([\u0600-\u06EF]{1,}){1,})/g;value=value.replace(new RegExp(pattern),"$2‌$4");pattern=/(([\u0600-\u06EF]{1,})+( )+(ای|ایی|اند|ایم|اید|ام){1})/g;value=value.replace(new RegExp(pattern),"$2‌$4");this._str=value;return this}var persianJs=function(inputStr){if(!inputStr||inputStr===""){throw new Error("Input is null or empty.")}return new PersianJs(inputStr)};persianJs.version=VERSION;persianJs.fn=PersianJs.prototype={clone:function(){return persianJs(this)},value:function(){return this._str},toString:function(){return this._str.toString()},set:function(value){this._str=String(value);return this},arabicChar:function(){return _arabicChar.call(this,this._str)},persianNumber:function(){return _persianNumber.call(this,this._str)},arabicNumber:function(){return _arabicNumber.call(this,this._str)},englishNumber:function(){return _englishNumber.call(this,this._str)},toEnglishNumber:function(){return _toEnglishNumber.call(this,this._str)},fixURL:function(){return _decodeURL.call(this,this._str)},decodeURL:function(){return _decodeURL.call(this,this._str)},switchKey:function(){return _switchKey.call(this,this._str)},digitsToWords:function(){return _digitsToWords.call(this,this._str)},halfSpace:function(){return _halfSpace.call(this,this._str)}};if(hasModule){module.exports=persianJs}if(typeof ender==="undefined"){this["persianJs"]=persianJs}if(typeof define==="function"&&define.amd){define("persianJs",[],function(){return persianJs})}})(); <add>(function(){var VERSION="0.4.0",hasModule=typeof module!=="undefined"&&module.exports;var arabicNumbers=["١","٢","٣","٤","٥","٦","٧","٨","٩","٠"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"],englishNumbers=["1","2","3","4","5","6","7","8","9","0"];function PersianJs(str){this._str=str}function _arabicChar(value){if(!value){return}var arabicChars=["ي","ك","‍","دِ","بِ","زِ","ذِ","ِشِ","ِسِ","‌","ى"],persianChars=["ی","ک","","د","ب","ز","ذ","ش","س","","ی"];for(var i=0,charsLen=arabicChars.length;i<charsLen;i++){value=value.replace(new RegExp(arabicChars[i],"g"),persianChars[i])}this._str=value;return this}function _persianNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _arabicNumber(value){if(!value){return}value=value.toString();for(var i=0,numbersLen=arabicNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(arabicNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _englishNumber(value){if(!value){return}value=value.toString();var englishNumbers=["1","2","3","4","5","6","7","8","9","0"],persianNumbers=["۱","۲","۳","۴","۵","۶","۷","۸","۹","۰"];for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(englishNumbers[i],"g"),persianNumbers[i])}this._str=value;return this}function _toEnglishNumber(value){if(!value){return}for(var i=0,numbersLen=englishNumbers.length;i<numbersLen;i++){value=value.replace(new RegExp(persianNumbers[i],"g"),englishNumbers[i]).replace(new RegExp(arabicNumbers[i],"g"),englishNumbers[i])}this._str=value;return this}function _decodeURL(value){if(!value){return}var old="";while(old!=value){old=value;value=value.replace(/(http\S+?)\%20/g,"$1‌‌‌_‌‌‌")}value=value.replace(/(http\S+)/g,function(s,p){return decodeURI(p)});value=value.replace(/\u200c\u200c\u200c_\u200c\u200c\u200c/g,"%20");this._str=value;return this}function _switchKey(value){if(!value){return}var persianChar=["ض","ص","ث","ق","ف","غ","ع","ه","خ","ح","ج","چ","ش","س","ی","ب","ل","ا","ت","ن","م","ک","گ","ظ","ط","ز","ر","ذ","د","پ","و","؟"],englishChar=["q","w","e","r","t","y","u","i","o","p","[","]","a","s","d","f","g","h","j","k","l",";","'","z","x","c","v","b","n","m",",","?"];for(var i=0,charsLen=persianChar.length;i<charsLen;i++){value=value.replace(new RegExp(persianChar[i],"g"),englishChar[i])}this._str=value;return this}function _digitsToWords(value){var delimiter,digit,i,iThree,numbers,parts,result,resultThree,three;if(!isFinite(value)){return""}if(typeof value!=="string"){value=value.toString()}parts=["","هزار","میلیون","میلیارد","تریلیون","کوادریلیون","کویینتیلیون","سکستیلیون"];numbers={0:["","صد","دویست","سیصد","چهارصد","پانصد","ششصد","هفتصد","هشتصد","نهصد"],1:["","ده","بیست","سی","چهل","پنجاه","شصت","هفتاد","هشتاد","نود"],2:["","یک","دو","سه","چهار","پنج","شش","هفت","هشت","نه"],two:["ده","یازده","دوازده","سیزده","چهارده","پانزده","شانزده","هفده","هجده","نوزده"],zero:"صفر"};delimiter=" و ";valueParts=value.split("").reverse().join("").replace(/\d{3}(?=\d)/g,"$&,").split("").reverse().join("").split(",").map(function(str){return Array(4-str.length).join("0")+str});result=function(){var _results;_results=[];for(iThree in valueParts){three=valueParts[iThree];resultThree=function(){var _i,_len,_results1;_results1=[];for(i=_i=0,_len=three.length;_i<_len;i=++_i){digit=three[i];if(i===1&&digit==="1"){_results1.push(numbers.two[three[2]])}else if((i!==2||three[1]!=="1")&&numbers[i][digit]!==""){_results1.push(numbers[i][digit])}else{continue}}return _results1}();resultThree=resultThree.join(delimiter);_results.push(resultThree+" "+parts[valueParts.length-iThree-1])}return _results}();result=result.filter(function(x){return x.trim()!==""});result=result.join(delimiter).trim();if(result===""){result=numbers.zero}this._str=result;return this}function _halfSpace(value){if(!value){return}var pattern;pattern=/((\s\u0645\u06CC)+( )+([\u0600-\u06EF]{1,}){1,})/g;value=value.replace(new RegExp(pattern),"$2‌$4");pattern=/(([\u0600-\u06EF]{1,})+( )+(ای|ایی|اند|ایم|اید|ام){1})/g;value=value.replace(new RegExp(pattern),"$2‌$4");this._str=value;return this}var persianJs=function(inputStr){if(!inputStr||inputStr===""){throw new Error("Input is null or empty.")}return new PersianJs(inputStr)};persianJs.version=VERSION;persianJs.fn=PersianJs.prototype={clone:function(){return persianJs(this)},value:function(){return this._str},toString:function(){return this._str.toString()},set:function(value){this._str=String(value);return this},arabicChar:function(){return _arabicChar.call(this,this._str)},persianNumber:function(){return _persianNumber.call(this,this._str)},arabicNumber:function(){return _arabicNumber.call(this,this._str)},englishNumber:function(){return _englishNumber.call(this,this._str)},toEnglishNumber:function(){return _toEnglishNumber.call(this,this._str)},fixURL:function(){return _decodeURL.call(this,this._str)},decodeURL:function(){return _decodeURL.call(this,this._str)},switchKey:function(){return _switchKey.call(this,this._str)},digitsToWords:function(){return _digitsToWords.call(this,this._str)},halfSpace:function(){return _halfSpace.call(this,this._str)}};if(hasModule){module.exports=persianJs}if(typeof ender==="undefined"){this["persianJs"]=persianJs}if(typeof define==="function"&&define.amd){define("persianJs",[],function(){return persianJs})}})(); <ide> //# sourceMappingURL=./persian-min.map
Java
mit
5727f5a39e8ba2a450973769cd0ebf0828a8d3cf
0
SumanBoss/wifiplugin,SumanBoss/wifiplugin
package org.apache.cordova.plugin; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import java.util.List; import org.json.JSONObject; import android.widget.Toast; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; public class WifiInfoPlugin extends CordovaPlugin { public static final String ACTION_MANAGE_WIFI = "managewifi"; public static final String GET_DEVICE = "getdevice"; public static final String WIFI_INFO = "wifinfo"; public static final String CHANGE_WIFI = "changewifi"; public static String imei; public static String macadress; public static String provider; public static String phonenumber; public static int wifistatus; public WifiInfoPlugin() { } @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { Context context = cordova.getActivity().getApplicationContext(); try { if (ACTION_MANAGE_WIFI.equals(action)) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { wifi.setWifiEnabled(true); } List<ScanResult> mScanResults = wifi.getScanResults(); for (ScanResult result : mScanResults) { if ("mtoll".equals(result.SSID)) { WifiConfiguration wc = new WifiConfiguration(); wc.SSID = "\"mtoll\""; wc.hiddenSSID = true; wc.status = WifiConfiguration.Status.DISABLED; wc.priority = 40; wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wc.wepKeys[0] = "\"FFFFFFFFFF\""; wc.wepTxKeyIndex = 0; int res = wifi.addNetwork(wc); boolean es = wifi.saveConfiguration(); boolean b = wifi.enableNetwork(res, true); break; } } callbackContext.success(); return true; } else if (GET_DEVICE.equals(action)) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); imei = telephonyManager.getDeviceId(); phonenumber = telephonyManager.getLine1Number(); provider = telephonyManager.getNetworkOperatorName(); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { WifiInfo info = wifiManager.getConnectionInfo(); macadress = info.getMacAddress(); } else { wifiManager.setWifiEnabled(true); WifiInfo info = wifiManager.getConnectionInfo(); macadress = info.getMacAddress(); wifiManager.setWifiEnabled(false); } JSONObject jSONObject = new JSONObject(); jSONObject.put("imei", WifiInfoPlugin.imei); jSONObject.put("macadress", WifiInfoPlugin.macadress); jSONObject.put("phonenumber", WifiInfoPlugin.phonenumber); jSONObject.put("provider", WifiInfoPlugin.provider); callbackContext.success(jSONObject); return true; } else if (WIFI_INFO.equals(action)) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { wifistatus = 0; } else { wifistatus = 1; } JSONObject jSONObject = new JSONObject(); jSONObject.put("status", WifiInfoPlugin.wifistatus); callbackContext.success(jSONObject); return true; } else if (CHANGE_WIFI.equals(action)) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { wifi.setWifiEnabled(true); } else { wifi.setWifiEnabled(false); } callbackContext.success(); return true; } else { callbackContext.error("Invalid action"); Toast.makeText(context, "Invalid action", Toast.LENGTH_LONG).show(); return false; } } catch (JSONException e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); callbackContext.error(e.getMessage()); return false; } } }
src/android/WifiInfoPlugin.java
package org.apache.cordova.plugin; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import java.util.List; import org.json.JSONObject; import android.widget.Toast; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; public class WifiInfoPlugin extends CordovaPlugin { public static final String ACTION_MANAGE_WIFI = "managewifi"; public static final String GET_DEVICE = "getdevice"; public static final String WIFI_INFO = "wifinfo"; public static final String CHANGE_WIFI = "changewifi"; public static String imei; public static String macadress; public static String provider; public static String phonenumber; public static int wifistatus; public WifiInfoPlugin() { } @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { Context context = cordova.getActivity().getApplicationContext(); try { if (ACTION_MANAGE_WIFI.equals(action)) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { wifi.setWifiEnabled(true); } List<ScanResult> mScanResults = wifi.getScanResults(); for (ScanResult result : mScanResults) { if ("Cloudlabz".equals(result.SSID)) { WifiConfiguration wc = new WifiConfiguration(); wc.SSID = "\"Cloudlabz\""; wc.hiddenSSID = true; wc.status = WifiConfiguration.Status.DISABLED; wc.priority = 40; wc.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); wc.allowedProtocols.set(WifiConfiguration.Protocol.RSN); wc.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wc.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); wc.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); wc.wepKeys[0] = "\"c10ud1@6z\""; wc.wepTxKeyIndex = 0; int res = wifi.addNetwork(wc); boolean es = wifi.saveConfiguration(); boolean b = wifi.enableNetwork(res, true); break; } } callbackContext.success(); return true; } else if (GET_DEVICE.equals(action)) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); imei = telephonyManager.getDeviceId(); phonenumber = telephonyManager.getLine1Number(); provider = telephonyManager.getNetworkOperatorName(); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifiManager.isWifiEnabled()) { WifiInfo info = wifiManager.getConnectionInfo(); macadress = info.getMacAddress(); } else { wifiManager.setWifiEnabled(true); WifiInfo info = wifiManager.getConnectionInfo(); macadress = info.getMacAddress(); wifiManager.setWifiEnabled(false); } JSONObject jSONObject = new JSONObject(); jSONObject.put("imei", WifiInfoPlugin.imei); jSONObject.put("macadress", WifiInfoPlugin.macadress); jSONObject.put("phonenumber", WifiInfoPlugin.phonenumber); jSONObject.put("provider", WifiInfoPlugin.provider); callbackContext.success(jSONObject); return true; } else if (WIFI_INFO.equals(action)) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { wifistatus = 0; } else { wifistatus = 1; } JSONObject jSONObject = new JSONObject(); jSONObject.put("status", WifiInfoPlugin.wifistatus); callbackContext.success(jSONObject); return true; } else if (CHANGE_WIFI.equals(action)) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (wifi.isWifiEnabled() == false) { wifi.setWifiEnabled(true); } else { wifi.setWifiEnabled(false); } callbackContext.success(); return true; } else { callbackContext.error("Invalid action"); Toast.makeText(context, "Invalid action", Toast.LENGTH_LONG).show(); return false; } } catch (JSONException e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); callbackContext.error(e.getMessage()); return false; } } }
Update WifiInfoPlugin.java
src/android/WifiInfoPlugin.java
Update WifiInfoPlugin.java
<ide><path>rc/android/WifiInfoPlugin.java <ide> } <ide> List<ScanResult> mScanResults = wifi.getScanResults(); <ide> for (ScanResult result : mScanResults) { <del> if ("Cloudlabz".equals(result.SSID)) { <add> if ("mtoll".equals(result.SSID)) { <ide> WifiConfiguration wc = new WifiConfiguration(); <del> wc.SSID = "\"Cloudlabz\""; <add> wc.SSID = "\"mtoll\""; <ide> wc.hiddenSSID = true; <ide> wc.status = WifiConfiguration.Status.DISABLED; <ide> wc.priority = 40; <ide> wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); <ide> wc.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); <ide> <del> wc.wepKeys[0] = "\"c10ud1@6z\""; <add> wc.wepKeys[0] = "\"FFFFFFFFFF\""; <ide> wc.wepTxKeyIndex = 0; <ide> <ide> int res = wifi.addNetwork(wc);
Java
apache-2.0
b731427339d0318a76a0473b5b603fe82874bbef
0
OpenHFT/Chronicle-Core
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.core.io; import sun.misc.Cleaner; import sun.nio.ch.DirectBuffer; import sun.reflect.Reflection; import java.io.*; import java.nio.ByteBuffer; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Created by peter on 26/08/15. * A collection of IO utility tools */ public enum IOTools { ; public static boolean shallowDeleteDirWithFiles(String directory) { File dir = new File(directory); File[] entries = dir.listFiles(); Stream.of(entries).filter(File::isDirectory).forEach(f -> { throw new AssertionError("Contains directory " + f); }); Stream.of(entries).forEach(File::delete); return dir.delete(); } /** * This method first looks for the file in the classpath. If this is not found it * appends the suffix .gz and looks again in the classpath to see if it is present. * If it is still not found it looks for the file on the file system. If it not found * it appends the suffix .gz and looks again on the file system. * If it still not found a FileNotFoundException is thrown. * * @param name Name of the file * @return A byte[] containing the contents of the file * @throws IOException FileNotFoundException thrown if file is not found */ public static byte[] readFile(String name) throws IOException { ClassLoader classLoader; try { classLoader = Reflection.getCallerClass().getClassLoader(); } catch (Throwable e) { classLoader = Thread.currentThread().getContextClassLoader(); } InputStream is = classLoader.getResourceAsStream(name); if (is == null) is = classLoader.getResourceAsStream(name + ".gz"); if (is == null) try { is = new FileInputStream(name); } catch (FileNotFoundException e) { try { is = new GZIPInputStream(new FileInputStream(name + ".gz")); } catch (FileNotFoundException e1) { throw e; } } ByteArrayOutputStream out = new ByteArrayOutputStream(Math.min(512, is.available())); byte[] bytes = new byte[1024]; for (int len; (len = is.read(bytes)) > 0; ) out.write(bytes, 0, len); return out.toByteArray(); } public static void writeFile(String filename, byte[] bytes) throws IOException { OutputStream out = new FileOutputStream(filename); if (filename.endsWith(".gz")) out = new GZIPOutputStream(out); out.write(bytes); out.close(); } public static String tempName(String filename) { int ext = filename.lastIndexOf('.'); if (ext > 0 && ext > filename.length() - 5) { return filename.substring(0, ext) + System.nanoTime() + filename.substring(ext); } return filename + System.nanoTime(); } public static void clean(ByteBuffer bb) { if (bb instanceof DirectBuffer) { Cleaner cl = ((DirectBuffer) bb).cleaner(); if (cl != null) cl.clean(); } } }
src/main/java/net/openhft/chronicle/core/io/IOTools.java
/* * Copyright (C) 2015 higherfrequencytrading.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.openhft.chronicle.core.io; import sun.misc.Cleaner; import sun.nio.ch.DirectBuffer; import sun.reflect.Reflection; import java.io.*; import java.nio.ByteBuffer; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Created by peter on 26/08/15. * A collection of IO utility tools */ public enum IOTools { ; /** * This method first looks for the file in the classpath. If this is not found it * appends the suffix .gz and looks again in the classpath to see if it is present. * If it is still not found it looks for the file on the file system. If it not found * it appends the suffix .gz and looks again on the file system. * If it still not found a FileNotFoundException is thrown. * @param name Name of the file * @return A byte[] containing the contents of the file * @throws IOException FileNotFoundException thrown if file is not found */ public static byte[] readFile(String name) throws IOException { ClassLoader classLoader; try { classLoader = Reflection.getCallerClass().getClassLoader(); } catch (Throwable e) { classLoader = Thread.currentThread().getContextClassLoader(); } InputStream is = classLoader.getResourceAsStream(name); if (is == null) is = classLoader.getResourceAsStream(name + ".gz"); if (is == null) try { is = new FileInputStream(name); } catch (FileNotFoundException e) { try { is = new GZIPInputStream(new FileInputStream(name + ".gz")); } catch (FileNotFoundException e1) { throw e; } } ByteArrayOutputStream out = new ByteArrayOutputStream(Math.min(512, is.available())); byte[] bytes = new byte[1024]; for (int len; (len = is.read(bytes)) > 0; ) out.write(bytes, 0, len); return out.toByteArray(); } public static void writeFile(String filename, byte[] bytes) throws IOException { OutputStream out = new FileOutputStream(filename); if (filename.endsWith(".gz")) out = new GZIPOutputStream(out); out.write(bytes); out.close(); } public static String tempName(String filename) { int ext = filename.lastIndexOf('.'); if (ext > 0 && ext > filename.length() - 5) { return filename.substring(0, ext) + System.nanoTime() + filename.substring(ext); } return filename + System.nanoTime(); } public static void clean(ByteBuffer bb) { if (bb instanceof DirectBuffer) { Cleaner cl = ((DirectBuffer) bb).cleaner(); if (cl != null) cl.clean(); } } }
Tuning the FIX benchmarks and using a lock free writing strategy.
src/main/java/net/openhft/chronicle/core/io/IOTools.java
Tuning the FIX benchmarks and using a lock free writing strategy.
<ide><path>rc/main/java/net/openhft/chronicle/core/io/IOTools.java <ide> <ide> import java.io.*; <ide> import java.nio.ByteBuffer; <add>import java.util.stream.Stream; <ide> import java.util.zip.GZIPInputStream; <ide> import java.util.zip.GZIPOutputStream; <ide> <ide> public enum IOTools { <ide> ; <ide> <add> public static boolean shallowDeleteDirWithFiles(String directory) { <add> File dir = new File(directory); <add> File[] entries = dir.listFiles(); <add> Stream.of(entries).filter(File::isDirectory).forEach(f -> { <add> throw new AssertionError("Contains directory " + f); <add> }); <add> Stream.of(entries).forEach(File::delete); <add> return dir.delete(); <add> } <add> <ide> /** <ide> * This method first looks for the file in the classpath. If this is not found it <ide> * appends the suffix .gz and looks again in the classpath to see if it is present. <ide> * If it is still not found it looks for the file on the file system. If it not found <ide> * it appends the suffix .gz and looks again on the file system. <ide> * If it still not found a FileNotFoundException is thrown. <add> * <ide> * @param name Name of the file <ide> * @return A byte[] containing the contents of the file <ide> * @throws IOException FileNotFoundException thrown if file is not found
JavaScript
mit
70873f5a235f7389e0e7cee21714fd1c1fb01a39
0
atomicjolt/QbankAdmin,atomicjolt/QbankAdmin,atomicjolt/QbankAdmin
import request from "superagent"; import { Constants as AppConstants } from "../actions/app"; import { Constants as AssessmentConstants } from "../actions/assessment_offered"; import { Constants as BanksConstants } from "../actions/banks"; import { DONE } from "../constants/wrapper"; export default (store) => (next) => { function startApp(action) { if(action.type == AppConstants.APP_START) { request.get("https://4h8n6sg95j.execute-api.us-east-1.amazonaws.com/dev/proxy").then( function (response) { store.dispatch({ type: BanksConstants.GET_BANK_HIERARCHY, payload: response.body }); }, function (err) { console.log("error", err.url, err.message); } ); } if(action.type == AssessmentConstants.ASSESSMENT_OFFER) { store.dispatch({ type: AssessmentConstants.ASSESSMENT_CLEAR_SNIPPET }); var url = "https://4h8n6sg95j.execute-api.us-east-1.amazonaws.com/dev/offer"; var body = { bank_id: action.bankId, assessment_id: action.assessmentId }; request.post(url).send(body).then( function (response) { store.dispatch({ type: AssessmentConstants.ASSESSMENT_OFFER + DONE, payload: response.body }); }, function (err) { console.log("error", err.url, err.message); } ); } next(action); } return startApp; };
client/js/middleware/qbank.js
import request from "superagent"; import { Constants as AppConstants } from "../actions/app"; import { Constants as AssessmentConstants } from "../actions/assessment_offered"; import { Constants as BanksConstants } from "../actions/banks"; import { DONE } from "../constants/wrapper"; export default (store) => (next) => { function startApp(action) { if(action.type == AppConstants.APP_START) { request.get("https://4h8n6sg95j.execute-api.us-east-1.amazonaws.com/dev/proxy").then( function (response) { store.dispatch({ type: BanksConstants.GET_BANK_HIERARCHY, payload: response.body }); }, function (err) { console.log("error", err.url, err.message); } ); } if(action.type == AssessmentConstants.ASSESSMENT_OFFER) { store.dispatch({ type: AssessmentConstants.ASSESSMENT_CLEAR_SNIPPET }); var url = "https://4h8n6sg95j.execute-api.us-east-1.amazonaws.com/dev/offer"; var body = { bank_id: action.bankId, assessment_id: action.assessmentId }; request.post(url).send(body).then( function (response) { store.dispatch({ type: AssessmentConstants.ASSESSMENT_OFFER + DONE, payload: response.body }); }, function (err) { console.log("error", err.url, err.message); } ); } next(action); } return startApp; };
Alignment
client/js/middleware/qbank.js
Alignment
<ide><path>lient/js/middleware/qbank.js <ide> }); <ide> var url = "https://4h8n6sg95j.execute-api.us-east-1.amazonaws.com/dev/offer"; <ide> var body = { <del> bank_id: action.bankId, <add> bank_id: action.bankId, <ide> assessment_id: action.assessmentId <ide> }; <ide> request.post(url).send(body).then( <ide> function (response) { <ide> store.dispatch({ <ide> type: AssessmentConstants.ASSESSMENT_OFFER + DONE, <del> payload: response.body <add> payload: response.body <ide> }); <ide> }, <ide> function (err) {
Java
apache-2.0
error: pathspec 'src/algorithm/boj/Boj4344.java' did not match any file(s) known to git
06bfaffc3f0fb54c39e7e68135c4d55b3080ca2c
1
hagomy/algorithm
/* * Copyright 2017 haeun kim * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package algorithm.boj; import java.io.*; /** * Created by haeun on 2017-09-26 * Site : https://www.acmicpc.net/problem/4344 */ public class Boj4344 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int c = Integer.parseInt(br.readLine()); for (int i = 0; i < c; i++) { String[] inputs = br.readLine().split(" "); int size = Integer.parseInt(inputs[0]); int[] inputss = new int[size]; for (int j = 0; j < size; j++) { inputss[j] = Integer.parseInt(inputs[j + 1]); } float sum = 0; float avr[] = new float[c]; for (int k = 0; k < size; k++) { sum += inputss[k]; } avr[i] = sum / size; float count = 0; for (int k = 0; k < size; k++) { if (inputss[k] > avr[i]) { count++; } } System.out.println(String.format("%.3f", count / size * 100) + "%"); } } }
src/algorithm/boj/Boj4344.java
Solve No.4344 from Baekjoon Online Judge
src/algorithm/boj/Boj4344.java
Solve No.4344 from Baekjoon Online Judge
<ide><path>rc/algorithm/boj/Boj4344.java <add>/* <add> * Copyright 2017 haeun kim <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package algorithm.boj; <add> <add>import java.io.*; <add> <add>/** <add> * Created by haeun on 2017-09-26 <add> * Site : https://www.acmicpc.net/problem/4344 <add> */ <add> <add>public class Boj4344 { <add> <add> public static void main(String[] args) throws IOException { <add> <add> BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); <add> int c = Integer.parseInt(br.readLine()); <add> <add> for (int i = 0; i < c; i++) { <add> String[] inputs = br.readLine().split(" "); <add> int size = Integer.parseInt(inputs[0]); <add> int[] inputss = new int[size]; <add> for (int j = 0; j < size; j++) { <add> inputss[j] = Integer.parseInt(inputs[j + 1]); <add> } <add> <add> <add> float sum = 0; <add> float avr[] = new float[c]; <add> <add> for (int k = 0; k < size; k++) { <add> sum += inputss[k]; <add> } <add> <add> avr[i] = sum / size; <add> float count = 0; <add> for (int k = 0; k < size; k++) { <add> if (inputss[k] > avr[i]) { <add> count++; <add> } <add> } <add> System.out.println(String.format("%.3f", count / size * 100) + "%"); <add> } <add> <add> <add> } <add>}
Java
mit
7cff924b3e86bc13848cbdfc2fb87333c95e125e
0
raeleus/skin-composer
/** ***************************************************************************** * MIT License * * Copyright (c) 2018 Raymond Buckley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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.ray3k.skincomposer; import com.ray3k.skincomposer.data.CustomProperty; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.scenes.scene2d.EventListener; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.actions.AlphaAction; import com.badlogic.gdx.scenes.scene2d.actions.DelayAction; import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction; import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction; import com.badlogic.gdx.scenes.scene2d.actions.VisibleAction; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox; import com.badlogic.gdx.scenes.scene2d.ui.Container; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.HorizontalGroup; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.List; import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox; import com.badlogic.gdx.scenes.scene2d.ui.Slider; import com.badlogic.gdx.scenes.scene2d.ui.SplitPane; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextArea; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip; import com.badlogic.gdx.scenes.scene2d.ui.TooltipManager; import com.badlogic.gdx.scenes.scene2d.ui.Touchpad; import com.badlogic.gdx.scenes.scene2d.ui.Tree; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable; import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable; import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.OrderedMap; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Field; import com.ray3k.skincomposer.MenuButton.MenuButtonListener; import com.ray3k.skincomposer.data.ColorData; import com.ray3k.skincomposer.data.CustomProperty.PropertyType; import com.ray3k.skincomposer.data.CustomStyle; import com.ray3k.skincomposer.data.DrawableData; import com.ray3k.skincomposer.data.FontData; import com.ray3k.skincomposer.data.FreeTypeFontData; import com.ray3k.skincomposer.data.StyleData; import com.ray3k.skincomposer.data.StyleProperty; import com.ray3k.skincomposer.dialog.DialogColorPicker; import com.ray3k.skincomposer.utils.Utils; public class RootTable extends Table { private final Stage stage; private final Main main; private SelectBox classSelectBox; private SelectBox styleSelectBox; private Array<StyleProperty> styleProperties; private Array<CustomProperty> customProperties; private Table stylePropertiesTable; private Table previewPropertiesTable; private Table previewTable; private ScrollPane stylePropertiesScrollPane; private final ScrollPaneListener scrollPaneListener; private final ObjectMap<String, Object> previewProperties; private final Color previewBgColor; private SelectBox<String> previewSizeSelectBox; private static final String[] DEFAULT_SIZES = {"small", "default", "large", "growX", "growY", "grow", "custom"}; private static final String TEXT_SAMPLE = "Lorem ipsum dolor sit"; private static final String PARAGRAPH_SAMPLE = "Lorem ipsum dolor sit amet, consectetur\n" + "adipiscing elit, sed do eiusmod tempor\n" + "incididunt ut labore et dolore magna\n" + "aliqua. Ut enim ad minim veniam, quis\n" + "nostrud exercitation ullamco laboris\n" + "nisi ut aliquip ex ea commodo\n" + "consequat. Duis aute irure dolor in\n" + "reprehenderit in voluptate velit esse\n" + "cillum dolore eu fugiat nulla pariatur.\n" + "Excepteur sint occaecat cupidatat non\n" + "proident, sunt in culpa qui officia\n" + "deserunt mollit anim id est laborum.\n"; private static final String PARAGRAPH_SAMPLE_EXT = PARAGRAPH_SAMPLE + "\n\n\n" + PARAGRAPH_SAMPLE + "\n\n\n" + PARAGRAPH_SAMPLE + "\n\n\n" + PARAGRAPH_SAMPLE; private final Array<BitmapFont> previewFonts; private final ObjectMap<String, Drawable> drawablePairs; private TextureAtlas atlas; private MenuItem undoButton; private MenuItem redoButton; private MenuItem recentFilesButton; private MenuButton fileMenu; private MenuButton editMenu; private Label statusLabel; private Button classDuplicateButton; private Button classDeleteButton; private Button classRenameButton; private Button styleDeleteButton; private Button styleRenameButton; public RootTable(Main main) { super(main.getSkin()); this.stage = main.getStage(); this.main = main; previewProperties = new ObjectMap<>(); previewBgColor = new Color(Color.WHITE); scrollPaneListener = new ScrollPaneListener(); previewFonts = new Array<>(); drawablePairs = new ObjectMap<>(); produceAtlas(); main.getStage().addListener(new ShortcutListener(this)); } public void populate() { clearChildren(); addFileMenu(); row(); addClassBar(); row(); addStyleAndPreviewSplit(); row(); addStatusBar(); } private void addFileMenu() { Table table = new Table(); table.defaults().padRight(2.0f); add(table).growX().padTop(2.0f); MenuButtonGroup menuButtonGroup = new MenuButtonGroup(); fileMenu = new MenuButton("File", getSkin()); fileMenu.addListener(main.getHandListener()); fileMenu.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(fileMenu); table.add(fileMenu).padLeft(2.0f); recentFilesButton = new MenuItem("Recent Files...", RootTableEnum.RECENT_FILES); fileMenu.setItems(new MenuItem("New", RootTableEnum.NEW), new MenuItem("Open...", RootTableEnum.OPEN), recentFilesButton, new MenuItem("Save", RootTableEnum.SAVE), new MenuItem("Save As...", RootTableEnum.SAVE_AS), new MenuItem("Welcome Screen...", RootTableEnum.WELCOME), new MenuItem("Import...", RootTableEnum.IMPORT), new MenuItem("Export...", RootTableEnum.EXPORT), new MenuItem("Exit", RootTableEnum.EXIT)); if (Utils.isMac()) { fileMenu.setShortcuts("⌘+N", "⌘+O", null, "⌘+S", "Shift+⌘+S", null, null, "⌘+E"); } else { fileMenu.setShortcuts("Ctrl+N", "Ctrl+O", null, "Ctrl+S", "Shift+Ctrl+S", null, null, "Ctrl+E"); } fileMenu.addListener(new MenuBarListener(fileMenu)); editMenu = new MenuButton("Edit", getSkin()); editMenu.addListener(main.getHandListener()); editMenu.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(editMenu); table.add(editMenu); undoButton = new MenuItem("Undo", RootTableEnum.UNDO); redoButton = new MenuItem("Redo", RootTableEnum.REDO); editMenu.setItems(undoButton, redoButton); if (Utils.isMac()) { editMenu.setShortcuts("⌘+Z", "⌘+Y"); } else { editMenu.setShortcuts("Ctrl+Z", "Ctrl+Y"); } editMenu.setDisabled(undoButton, true); editMenu.setDisabled(redoButton, true); editMenu.addListener(new MenuBarListener(editMenu)); MenuButton<MenuItem> menuButton = new MenuButton("Project", getSkin()); menuButton.addListener(main.getHandListener()); menuButton.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(menuButton); table.add(menuButton); menuButton.setItems(new MenuItem("Settings...", RootTableEnum.SETTINGS), new MenuItem("Colors...", RootTableEnum.COLORS), new MenuItem("Fonts...", RootTableEnum.FONTS), new MenuItem("Drawables...", RootTableEnum.DRAWABLES), new MenuItem("Refresh Atlas", RootTableEnum.REFRESH_ATLAS)); menuButton.setShortcuts(null, null, null, null, "F5"); menuButton.addListener(new MenuBarListener(menuButton)); menuButton = new MenuButton("Help", getSkin()); menuButton.addListener(main.getHandListener()); menuButton.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(menuButton); table.add(menuButton); menuButton.setItems(new MenuItem("About...", RootTableEnum.ABOUT)); menuButton.addListener(new MenuBarListener(menuButton)); Button button = new Button(getSkin(), "download"); button.setName("downloadButton"); table.add(button).expandX().right(); button.addListener(new TextTooltip("Update Available", main.getTooltipManager(), getSkin())); button.addListener(main.getHandListener()); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DOWNLOAD_UPDATE)); } }); button.setVisible(false); } public void setRecentFilesDisabled(boolean disabled) { fileMenu.setDisabled(recentFilesButton, disabled); } public void setUndoDisabled(boolean disabled) { editMenu.setDisabled(undoButton, disabled); } public void setRedoDisabled(boolean disabled) { editMenu.setDisabled(redoButton, disabled); } public void setUndoText(String text) { undoButton.text = text; editMenu.updateContents(); } public void setRedoText(String text) { redoButton.text = text; editMenu.updateContents(); } private void addClassBar() { Table table = new Table(); table.setBackground(getSkin().getDrawable("class-bar")); add(table).expandX().left().growX(); Label label = new Label("Class:", getSkin()); table.add(label).padRight(10.0f).padLeft(10.0f); classSelectBox = new SelectBox(getSkin()); classSelectBox.addListener(main.getHandListener()); classSelectBox.getList().addListener(main.getHandListener()); table.add(classSelectBox).padRight(5.0f).minWidth(150.0f); classSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.CLASS_SELECTED)); fire(new LoadStylesEvent(classSelectBox, styleSelectBox)); } }); Button button = new Button(getSkin(), "new"); button.addListener(main.getHandListener()); table.add(button); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.NEW_CLASS)); } }); //Tooltip TextTooltip toolTip = new TextTooltip("New Class", main.getTooltipManager(), getSkin()); button.addListener(toolTip); classDuplicateButton = new Button(getSkin(), "duplicate"); classDuplicateButton.setDisabled(true); classDuplicateButton.addListener(main.getHandListener()); table.add(classDuplicateButton); classDuplicateButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DUPLICATE_CLASS)); } }); toolTip = new TextTooltip("Duplicate Class", main.getTooltipManager(), getSkin()); classDuplicateButton.addListener(toolTip); classDeleteButton = new Button(getSkin(), "delete"); classDeleteButton.setDisabled(true); table.add(classDeleteButton); classDeleteButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DELETE_CLASS)); } }); toolTip = new TextTooltip("Delete Class", main.getTooltipManager(), getSkin()); classDeleteButton.addListener(toolTip); classRenameButton = new Button(getSkin(), "settings"); classRenameButton.setDisabled(true); table.add(classRenameButton).padRight(30.0f); classRenameButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.RENAME_CLASS)); } }); toolTip = new TextTooltip("Rename Class", main.getTooltipManager(), getSkin()); classRenameButton.addListener(toolTip); label = new Label("Style:", getSkin()); table.add(label).padRight(10.0f); styleSelectBox = new SelectBox(getSkin()); table.add(styleSelectBox).padRight(5.0f).minWidth(150.0f); styleSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.STYLE_SELECTED)); } }); styleSelectBox.addListener(main.getHandListener()); styleSelectBox.getList().addListener(main.getHandListener()); button = new Button(getSkin(), "new"); button.addListener(main.getHandListener()); table.add(button); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.NEW_STYLE)); } }); toolTip = new TextTooltip("New Style", main.getTooltipManager(), getSkin()); button.addListener(toolTip); button = new Button(getSkin(), "duplicate"); button.addListener(main.getHandListener()); table.add(button); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DUPLICATE_STYLE)); } }); toolTip = new TextTooltip("Duplicate Style", main.getTooltipManager(), getSkin()); button.addListener(toolTip); styleDeleteButton = new Button(getSkin(), "delete"); styleDeleteButton.addListener(main.getHandListener()); table.add(styleDeleteButton); styleDeleteButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DELETE_STYLE)); } }); toolTip = new TextTooltip("Delete Style", main.getTooltipManager(), getSkin()); styleDeleteButton.addListener(toolTip); styleRenameButton = new Button(getSkin(), "settings"); table.add(styleRenameButton).expandX().left(); styleRenameButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.RENAME_STYLE)); } }); toolTip = new TextTooltip("Rename Style", main.getTooltipManager(), getSkin()); styleRenameButton.addListener(toolTip); fire(new LoadClassesEvent(classSelectBox)); fire(new LoadStylesEvent(classSelectBox, styleSelectBox)); } public void setClassDuplicateButtonDisabled(boolean disabled) { classDuplicateButton.setDisabled(disabled); if (disabled) { if (classDuplicateButton.getListeners().contains(main.getHandListener(), true)) { classDuplicateButton.removeListener(main.getHandListener()); } } else { if (!classDuplicateButton.getListeners().contains(main.getHandListener(), true)) { classDuplicateButton.addListener(main.getHandListener()); } } } public void setClassDeleteButtonDisabled(boolean disabled) { classDeleteButton.setDisabled(disabled); if (disabled) { if (classDeleteButton.getListeners().contains(main.getHandListener(), true)) { classDeleteButton.removeListener(main.getHandListener()); } } else { if (!classDeleteButton.getListeners().contains(main.getHandListener(), true)) { classDeleteButton.addListener(main.getHandListener()); } } } public void setClassRenameButtonDisabled(boolean disabled) { classRenameButton.setDisabled(disabled); if (disabled) { if (classRenameButton.getListeners().contains(main.getHandListener(), true)) { classRenameButton.removeListener(main.getHandListener()); } } else { if (!classRenameButton.getListeners().contains(main.getHandListener(), true)) { classRenameButton.addListener(main.getHandListener()); } } } public void setStyleDeleteButtonDisabled(boolean disabled) { styleDeleteButton.setDisabled(disabled); if (disabled) { if (styleDeleteButton.getListeners().contains(main.getHandListener(), true)) { styleDeleteButton.removeListener(main.getHandListener()); } } else { if (!styleDeleteButton.getListeners().contains(main.getHandListener(), true)) { styleDeleteButton.addListener(main.getHandListener()); } } } public void setStyleRenameButtonDisabled(boolean disabled) { styleRenameButton.setDisabled(disabled); if (disabled) { if (styleRenameButton.getListeners().contains(main.getHandListener(), true)) { styleRenameButton.removeListener(main.getHandListener()); } } else { if (!styleRenameButton.getListeners().contains(main.getHandListener(), true)) { styleRenameButton.addListener(main.getHandListener()); } } } private void addStyleAndPreviewSplit() { stylePropertiesTable = new Table(); stylePropertiesTable.setTouchable(Touchable.enabled); addStyleProperties(stylePropertiesTable); Table right = new Table(); right.setTouchable(Touchable.enabled); addPreviewPreviewPropertiesSplit(right, scrollPaneListener); SplitPane splitPane = new SplitPane(stylePropertiesTable, right, false, getSkin()); add(splitPane).grow(); splitPane.addListener(main.getHorizontalResizeArrowListener()); } public void refreshStyleProperties(boolean preserveScroll) { if (stylePropertiesTable != null && stylePropertiesScrollPane != null) { float scrollY; if (preserveScroll) { scrollY = stylePropertiesScrollPane.getScrollY(); } else { scrollY = 0; } stylePropertiesTable.clearChildren(); addStyleProperties(stylePropertiesTable); if (preserveScroll) { validate(); stylePropertiesScrollPane.setSmoothScrolling(false); stylePropertiesScrollPane.setScrollY(scrollY); stylePropertiesScrollPane.addAction(new SequenceAction(new DelayAction(.1f), new Action() { @Override public boolean act(float delta) { stylePropertiesScrollPane.setSmoothScrolling(true); return true; } })); } } } public void refreshClasses(boolean scrollToNewest) { int classSelectedIndex = classSelectBox.getSelectedIndex(); populate(); if (scrollToNewest) { classSelectBox.setSelectedIndex(classSelectBox.getItems().size - 1); } else { classSelectBox.setSelectedIndex(Math.min(classSelectedIndex, classSelectBox.getItems().size - 1)); } } public void refreshStyles(boolean scrollToNewest) { int classSelectedIndex = classSelectBox.getSelectedIndex(); populate(); classSelectBox.setSelectedIndex(classSelectedIndex); if (scrollToNewest) { styleSelectBox.setSelectedIndex(styleSelectBox.getItems().size - 1); } } private void addStyleProperties(final Table left) { Label label = new Label("Style Properties", getSkin(), "title"); left.add(label); left.row(); Table table = new Table(); table.defaults().padLeft(10.0f).padRight(10.0f).growX(); stylePropertiesScrollPane = new ScrollPane(table, getSkin()); stylePropertiesScrollPane.setFadeScrollBars(false); stylePropertiesScrollPane.setFlickScroll(false); stylePropertiesScrollPane.addListener(scrollPaneListener); stage.setScrollFocus(stylePropertiesScrollPane); left.add(stylePropertiesScrollPane).grow().padTop(10.0f).padBottom(10.0f); //gather all scrollPaneStyles Array<StyleData> scrollPaneStyles = main.getProjectData().getJsonData().getClassStyleMap().get(ScrollPane.class); //gather all listStyles Array<StyleData> listStyles = main.getProjectData().getJsonData().getClassStyleMap().get(List.class); //gather all labelStyles Array<StyleData> labelStyles = main.getProjectData().getJsonData().getClassStyleMap().get(Label.class); if (styleProperties != null) { for (StyleProperty styleProperty : styleProperties) { table.row(); if (styleProperty.type == Color.class) { BrowseField browseField; if (styleProperty.optional) { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "color"); } else { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "color-required"); } browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new StylePropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.type == BitmapFont.class) { BrowseField browseField; if (styleProperty.optional) { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "font"); } else { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "font-required"); } browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new StylePropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.type == Drawable.class) { BrowseField browseField; if (styleProperty.optional) { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "drawable"); } else { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "drawable-required"); } browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new StylePropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.type == Float.TYPE) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); Spinner spinner = new Spinner((Double) styleProperty.value, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); table.add(spinner); spinner.addListener(new StylePropertyChangeListener(styleProperty, spinner)); } else if (styleProperty.type == ScrollPaneStyle.class) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); SelectBox<StyleData> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(scrollPaneStyles); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); if (styleProperty.value != null) { String name = ((String) styleProperty.value); int index = 0; for (StyleData styleData : scrollPaneStyles) { if (styleData.name.equals(name)) { break; } else { index++; } } if (index < scrollPaneStyles.size) { selectBox.setSelectedIndex(index); } } table.add(selectBox); selectBox.addListener(new StylePropertyChangeListener(styleProperty, selectBox)); } else if (styleProperty.type == ListStyle.class) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); SelectBox<StyleData> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(listStyles); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); if (styleProperty.value != null) { String name = ((String) styleProperty.value); int index = 0; for (StyleData styleData : listStyles) { if (styleData.name.equals(name)) { break; } else { index++; } } if (index < listStyles.size) { selectBox.setSelectedIndex(index); } } table.add(selectBox); selectBox.addListener(new StylePropertyChangeListener(styleProperty, selectBox)); } else if (styleProperty.type == LabelStyle.class) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); SelectBox<StyleData> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(labelStyles); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); if (styleProperty.value != null) { String name = ((String) styleProperty.value); int index = 0; for (StyleData styleData : labelStyles) { if (styleData.name.equals(name)) { break; } else { index++; } } if (index < labelStyles.size) { selectBox.setSelectedIndex(index); } } table.add(selectBox); selectBox.addListener(new StylePropertyChangeListener(styleProperty, selectBox)); } table.row(); } } else if (customProperties != null) { for (CustomProperty styleProperty : customProperties) { if (styleProperty.getType() == PropertyType.COLOR) { String value = ""; if (styleProperty.getValue() instanceof String) { for (ColorData color : main.getJsonData().getColors()) { if (color.getName().equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); break; } } } BrowseField browseField = new BrowseField(value, styleProperty.getName(), getSkin(), "color"); browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new CustomPropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.getType() == PropertyType.FONT) { String value = ""; if (styleProperty.getValue() instanceof String) { for (FontData font : main.getJsonData().getFonts()) { if (font.getName().equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); break; } } for (FreeTypeFontData font : main.getJsonData().getFreeTypeFonts()) { if (font.name.equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); } } } BrowseField browseField = new BrowseField(value, styleProperty.getName(), getSkin(), "font"); browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new CustomPropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.getType() == PropertyType.DRAWABLE) { String value = ""; if (styleProperty.getValue() instanceof String) { for (DrawableData drawable : main.getAtlasData().getDrawables()) { if (drawable.name.equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); break; } } } BrowseField browseField = new BrowseField(value, styleProperty.getName(), getSkin(), "drawable"); browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new CustomPropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.getType() == PropertyType.NUMBER) { label = new Label(styleProperty.getName(), getSkin()); table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); if (styleProperty.getValue() instanceof Float) { styleProperty.setValue((double) (float) styleProperty.getValue()); } Double value = 0.0; if (styleProperty.getValue() instanceof Double) { value = (Double) styleProperty.getValue(); } Spinner spinner = new Spinner(value, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.setRound(false); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); table.add(spinner); spinner.addListener(new CustomPropertyChangeListener(styleProperty, spinner)); } else if (styleProperty.getType() == PropertyType.TEXT || styleProperty.getType() == PropertyType.RAW_TEXT) { label = new Label(styleProperty.getName(), getSkin()); table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); String value = ""; if (styleProperty.getValue() instanceof String) { value = (String) styleProperty.getValue(); } TextField textField = new TextField(value, getSkin()); textField.setAlignment(Align.center); textField.addListener(main.getIbeamListener()); table.add(textField); textField.addListener(new CustomPropertyChangeListener(styleProperty, textField)); } else if (styleProperty.getType() == PropertyType.BOOL) { label = new Label(styleProperty.getName(), getSkin()); table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); Button button = new Button(getSkin(), "switch"); boolean value = false; if (styleProperty.getValue() instanceof Boolean) { value = (boolean) styleProperty.getValue(); } button.setChecked(value); table.add(button).fill(false); button.addListener(new CustomPropertyChangeListener(styleProperty, button)); } Button duplicateButton = new Button(getSkin(), "duplicate"); table.add(duplicateButton).fill(false).expand(false, false).pad(0).bottom(); duplicateButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProperty, duplicateButton, CustomPropertyEnum.DUPLICATE)); } }); TextTooltip toolTip = new TextTooltip("Duplicate Style Property", main.getTooltipManager(), getSkin()); duplicateButton.addListener(toolTip); Button deleteButton = new Button(getSkin(), "delete"); table.add(deleteButton).fill(false).expand(false, false).pad(0).bottom(); deleteButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProperty, duplicateButton, CustomPropertyEnum.DELETE)); } }); toolTip = new TextTooltip("Delete Style Property", main.getTooltipManager(), getSkin()); deleteButton.addListener(toolTip); Button renameButton = new Button(getSkin(), "settings"); table.add(renameButton).fill(false).expand(false, false).pad(0).bottom(); renameButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProperty, duplicateButton, CustomPropertyEnum.RENAME)); } }); toolTip = new TextTooltip("Rename Style Property", main.getTooltipManager(), getSkin()); renameButton.addListener(toolTip); table.row(); } left.row(); table = new Table(); left.add(table).right().padBottom(10.0f); Button button = new Button(getSkin(), "new"); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(null, null, CustomPropertyEnum.NEW)); } }); table.add(button); TextTooltip toolTip = new TextTooltip("New Style Property", main.getTooltipManager(), getSkin()); button.addListener(toolTip); button.addListener(main.getHandListener()); } } private class StylePropertyChangeListener extends ChangeListener { private final StyleProperty styleProp; private final Actor styleActor; public StylePropertyChangeListener(StyleProperty styleProp, Actor styleActor) { this.styleProp = styleProp; this.styleActor = styleActor; } @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new StylePropertyEvent(styleProp, styleActor)); } } private class CustomPropertyChangeListener extends ChangeListener { private final CustomProperty styleProp; private final Actor styleActor; public CustomPropertyChangeListener(CustomProperty styleProp, Actor styleActor) { this.styleProp = styleProp; this.styleActor = styleActor; } @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProp, styleActor, CustomPropertyEnum.CHANGE_VALUE)); } } private void addPreviewPreviewPropertiesSplit(final Table right, InputListener scrollPaneListener) { Table bottom = new Table(); bottom.setTouchable(Touchable.enabled); addPreviewProperties(bottom, scrollPaneListener); Table top = new Table(); top.setTouchable(Touchable.enabled); addPreview(top, scrollPaneListener); SplitPane splitPane = new SplitPane(top, bottom, true, getSkin()); right.add(splitPane).grow(); splitPane.addListener(main.getVerticalResizeArrowListener()); } private void addPreview(Table top, InputListener scrollPaneListener) { Label label = new Label("Preview", getSkin(), "title"); top.add(label); top.row(); previewTable = new Table(getSkin()); previewTable.setBackground("white"); ScrollPane scrollPane = new ScrollPane(previewTable, getSkin()); scrollPane.setFadeScrollBars(false); scrollPane.setFlickScroll(false); scrollPane.addListener(scrollPaneListener); top.add(scrollPane).grow().padTop(10.0f).padBottom(10.0f); refreshPreview(); } private void addPreviewProperties(Table bottom, InputListener scrollPaneListener) { Label label = new Label("Preview Properties", getSkin(), "title"); bottom.add(label); bottom.row(); previewPropertiesTable = new Table(); previewPropertiesTable.defaults().pad(5.0f); ScrollPane scrollPane = new ScrollPane(previewPropertiesTable, getSkin()); scrollPane.setFadeScrollBars(false); scrollPane.setFlickScroll(false); scrollPane.addListener(scrollPaneListener); bottom.add(scrollPane).grow().padTop(10.0f).padBottom(10.0f); refreshPreviewProperties(); } public void refreshPreviewProperties() { if (previewPropertiesTable != null) { previewPropertiesTable.clear(); previewProperties.clear(); Table t = new Table(); previewPropertiesTable.add(t).grow(); t.defaults().pad(3.0f); if (previewBgColor == null) { previewBgColor.set(Color.WHITE); } previewProperties.put("bgcolor", previewBgColor); if (classSelectBox.getSelectedIndex() >= 0 && classSelectBox.getSelectedIndex() < Main.BASIC_CLASSES.length) { t.add(new Label("Stage Color: ", getSkin())).right(); BrowseField browseField = new BrowseField(null, null, getSkin(), "color"); browseField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { main.getDialogFactory().showDialogColorPicker((Color) previewProperties.get("bgcolor"), new DialogColorPicker.ColorListener() { @Override public void selected(Color color) { if (color != null) { browseField.getTextButton().setText((int) (color.r * 255) + "," + (int) (color.g * 255) + "," + (int) (color.b * 255) + "," + (int) (color.a * 255)); previewProperties.put("bgcolor", color); previewBgColor.set(color); refreshPreview(); } } }); } }); browseField.addListener(main.getHandListener()); t.add(browseField).growX(); browseField.getTextButton().setText((int) (previewBgColor.r * 255) + "," + (int) (previewBgColor.g * 255) + "," + (int) (previewBgColor.b * 255) + "," + (int) (previewBgColor.a * 255)); t.row(); t.add(new Label("Size: ", getSkin())).right(); previewSizeSelectBox = new SelectBox<>(getSkin()); previewSizeSelectBox.setItems(DEFAULT_SIZES); previewSizeSelectBox.setSelectedIndex(1); previewSizeSelectBox.addListener(main.getHandListener()); previewSizeSelectBox.getList().addListener(main.getHandListener()); t.add(previewSizeSelectBox).growX().minWidth(200.0f); Class clazz = Main.BASIC_CLASSES[classSelectBox.getSelectedIndex()]; if (clazz.equals(Button.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); } else if (clazz.equals(CheckBox.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(ImageButton.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); } else if (clazz.equals(ImageTextButton.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(Label.class)) { t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(List.class)) { t.row(); t.add(new Label("List Items: ", getSkin())).right(); TextArea listItemsTextArea = new TextArea("Lorem ipsum\ndolor sit\namet, consectetur", getSkin()); listItemsTextArea.setFocusTraversal(false); listItemsTextArea.setPrefRows(3); listItemsTextArea.addListener(main.getIbeamListener()); listItemsTextArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", listItemsTextArea.getText()); refreshPreview(); } }); previewProperties.put("text", listItemsTextArea.getText()); t.add(listItemsTextArea).growX(); } else if (clazz.equals(ProgressBar.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Value: ", getSkin())).right(); Spinner valueSpinner = new Spinner(0.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); valueSpinner.getTextField().setFocusTraversal(false); valueSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("value", valueSpinner.getValue()); refreshPreview(); } }); valueSpinner.getButtonMinus().addListener(main.getHandListener()); valueSpinner.getButtonPlus().addListener(main.getHandListener()); valueSpinner.getTextField().addListener(main.getIbeamListener()); previewProperties.put("value", valueSpinner.getValue()); t.add(valueSpinner).growX(); t.row(); t.add(new Label("Minimum: ", getSkin())).right(); Spinner minimumSpinner = new Spinner(0.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); minimumSpinner.getTextField().setFocusTraversal(false); minimumSpinner.getTextField().addListener(main.getIbeamListener()); minimumSpinner.getButtonMinus().addListener(main.getHandListener()); minimumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("minimum", minimumSpinner.getValue()); t.add(minimumSpinner).growX(); t.row(); t.add(new Label("Maximum: ", getSkin())).right(); Spinner maximumSpinner = new Spinner(100.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); maximumSpinner.getTextField().setFocusTraversal(false); maximumSpinner.getTextField().addListener(main.getIbeamListener()); maximumSpinner.getButtonMinus().addListener(main.getHandListener()); maximumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("maximum", maximumSpinner.getValue()); t.add(maximumSpinner).growX(); minimumSpinner.setMaximum(maximumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); minimumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("minimum", minimumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); refreshPreview(); } }); maximumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("maximum", maximumSpinner.getValue()); minimumSpinner.setMaximum(maximumSpinner.getValue()); refreshPreview(); } }); t.row(); t.add(new Label("Increment: ", getSkin())).right(); Spinner incrementSpinner = new Spinner(1.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); incrementSpinner.getTextField().setFocusTraversal(false); incrementSpinner.setMinimum(1); incrementSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("increment", incrementSpinner.getValue()); refreshPreview(); } }); incrementSpinner.getTextField().addListener(main.getIbeamListener()); incrementSpinner.getButtonMinus().addListener(main.getHandListener()); incrementSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("increment", incrementSpinner.getValue()); t.add(incrementSpinner).growX(); t.row(); t.add(new Label("Orientation: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Horizontal", "Vertical"}); if (getSelectedStyle().name.contains("vert")) { previewProperties.put("orientation", true); selectBox.setSelectedIndex(1); } else { previewProperties.put("orientation", false); } selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (selectBox.getSelectedIndex() == 0) { previewProperties.put("orientation", false); } else { previewProperties.put("orientation", true); } refreshPreview(); } }); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); t.add(selectBox).growX(); } else if (clazz.equals(ScrollPane.class)) { t.row(); t.add(new Label("Scrollbars On Top: ", getSkin())).right(); ImageTextButton onTopCheckBox = new ImageTextButton("", getSkin(), "switch"); onTopCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("scrollbarsOnTop", onTopCheckBox.isChecked()); refreshPreview(); } }); t.add(onTopCheckBox).left(); onTopCheckBox.addListener(main.getHandListener()); previewProperties.put("scrollbarsOnTop", onTopCheckBox.isChecked()); t.row(); t.add(new Label("H ScrollBar Position: ", getSkin())).right(); SelectBox<String> hScrollPosBox = new SelectBox<>(getSkin()); hScrollPosBox.setItems(new String[]{"Top", "Bottom"}); hScrollPosBox.setSelectedIndex(1); hScrollPosBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (hScrollPosBox.getSelectedIndex() == 0) { previewProperties.put("hScrollBarPosition", false); } else { previewProperties.put("hScrollBarPosition", true); } refreshPreview(); } }); t.add(hScrollPosBox).growX(); hScrollPosBox.addListener(main.getHandListener()); hScrollPosBox.getList().addListener(main.getHandListener()); previewProperties.put("hScrollBarPosition", true); t.row(); t.add(new Label("V ScrollBar Position: ", getSkin())).right(); SelectBox<String> vScrollPosBox = new SelectBox<>(getSkin()); vScrollPosBox.setItems(new String[]{"Left", "Right"}); vScrollPosBox.setSelectedIndex(1); vScrollPosBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (vScrollPosBox.getSelectedIndex() == 0) { previewProperties.put("vScrollBarPosition", false); } else { previewProperties.put("vScrollBarPosition", true); } refreshPreview(); } }); t.add(vScrollPosBox).growX(); vScrollPosBox.addListener(main.getHandListener()); vScrollPosBox.getList().addListener(main.getHandListener()); previewProperties.put("vScrollBarPosition", true); t.row(); t.add(new Label("H Scrolling Disabled: ", getSkin())).right(); ImageTextButton hScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); hScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("hScrollDisabled", hScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(hScrollCheckBox).left(); hScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("hScrollDisabled", hScrollCheckBox.isChecked()); t.row(); t.add(new Label("V Scrolling Disabled: ", getSkin())).right(); ImageTextButton vScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); vScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("vScrollDisabled", vScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(vScrollCheckBox).left(); vScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("vScrollDisabled", vScrollCheckBox.isChecked()); t.row(); t.add(new Label("Force H Scroll: ", getSkin())).right(); ImageTextButton forceHScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); forceHScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("forceHscroll", forceHScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(forceHScrollCheckBox).left(); forceHScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("forceHscroll", forceHScrollCheckBox.isChecked()); t.row(); t.add(new Label("Force V Scroll: ", getSkin())).right(); ImageTextButton forceVScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); forceVScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("forceVscroll", forceVScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(forceVScrollCheckBox).left(); forceVScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("forceVscroll", forceVScrollCheckBox.isChecked()); t.row(); t.add(new Label("Variable Size Knobs: ", getSkin())).right(); ImageTextButton variableSizeKnobsCheckBox = new ImageTextButton("", getSkin(), "switch"); variableSizeKnobsCheckBox.setChecked(true); variableSizeKnobsCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("variableSizeKnobs", variableSizeKnobsCheckBox.isChecked()); refreshPreview(); } }); t.add(variableSizeKnobsCheckBox).left(); variableSizeKnobsCheckBox.addListener(main.getHandListener()); previewProperties.put("variableSizeKnobs", variableSizeKnobsCheckBox.isChecked()); t.row(); t.add(new Label("H Overscroll: ", getSkin())).right(); ImageTextButton hOverscrollCheckBox = new ImageTextButton("", getSkin(), "switch"); hOverscrollCheckBox.setChecked(true); hOverscrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("hOverscroll", hOverscrollCheckBox.isChecked()); refreshPreview(); } }); t.add(hOverscrollCheckBox).left(); hOverscrollCheckBox.addListener(main.getHandListener()); previewProperties.put("hOverscroll", hOverscrollCheckBox.isChecked()); t.row(); t.add(new Label("V Overscroll: ", getSkin())).right(); ImageTextButton vOverscrollCheckBox = new ImageTextButton("", getSkin(), "switch"); vOverscrollCheckBox.setChecked(true); vOverscrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("vOverscroll", vOverscrollCheckBox.isChecked()); refreshPreview(); } }); t.add(vOverscrollCheckBox).left(); vOverscrollCheckBox.addListener(main.getHandListener()); previewProperties.put("vOverscroll", vOverscrollCheckBox.isChecked()); t.row(); t.add(new Label("Fade Scroll Bars: ", getSkin())).right(); ImageTextButton fadeScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); fadeScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("fadeScroll", fadeScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(fadeScrollCheckBox).left(); fadeScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("fadeScroll", fadeScrollCheckBox.isChecked()); t.row(); t.add(new Label("Smooth Scrolling: ", getSkin())).right(); ImageTextButton smoothScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); smoothScrollCheckBox.setChecked(true); smoothScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("smoothScroll", smoothScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(smoothScrollCheckBox).left(); smoothScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("smoothScroll", smoothScrollCheckBox.isChecked()); t.row(); t.add(new Label("Flick Scroll: ", getSkin())).right(); ImageTextButton flickScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); flickScrollCheckBox.setChecked(true); flickScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("flickScroll", flickScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(flickScrollCheckBox).left(); flickScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("flickScroll", flickScrollCheckBox.isChecked()); t.row(); t.add(new Label("Clamp: ", getSkin())).right(); ImageTextButton clampCheckBox = new ImageTextButton("", getSkin(), "switch"); clampCheckBox.setChecked(true); clampCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("clamp", clampCheckBox.isChecked()); refreshPreview(); } }); t.add(clampCheckBox).left(); clampCheckBox.addListener(main.getHandListener()); previewProperties.put("clamp", clampCheckBox.isChecked()); t.row(); t.add(new Label("Sample Text: ", getSkin())).right(); TextArea previewTextArea = new TextArea(PARAGRAPH_SAMPLE_EXT, getSkin()); previewTextArea.setFocusTraversal(false); previewTextArea.setPrefRows(5); previewTextArea.addListener(main.getIbeamListener()); previewTextArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextArea.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextArea.getText()); t.add(previewTextArea).growX(); previewSizeSelectBox.setSelectedIndex(2); } else if (clazz.equals(SelectBox.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Max List Count: ", getSkin())).right(); Spinner spinner = new Spinner(3, 1, true, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().setFocusTraversal(false); spinner.setMinimum(1); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); t.add(spinner).growX(); t.row(); t.add(new Label("List Items: ", getSkin())).right(); TextArea listItemsTextArea = new TextArea("Lorem ipsum\ndolor sit\namet, consectetur", getSkin()); listItemsTextArea.setFocusTraversal(false); listItemsTextArea.setPrefRows(3); listItemsTextArea.addListener(main.getIbeamListener()); listItemsTextArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", listItemsTextArea.getText()); refreshPreview(); } }); previewProperties.put("text", listItemsTextArea.getText()); t.add(listItemsTextArea).growX(); } else if (clazz.equals(Slider.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Minimum: ", getSkin())).right(); Spinner minimumSpinner = new Spinner(0.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); minimumSpinner.getTextField().setFocusTraversal(false); minimumSpinner.getTextField().addListener(main.getIbeamListener()); t.add(minimumSpinner).growX(); minimumSpinner.getButtonMinus().addListener(main.getHandListener()); minimumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("minimum", minimumSpinner.getValue()); t.row(); t.add(new Label("Maximum: ", getSkin())).right(); Spinner maximumSpinner = new Spinner(100.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); maximumSpinner.getTextField().setFocusTraversal(false); maximumSpinner.getTextField().addListener(main.getIbeamListener()); t.add(maximumSpinner).growX(); maximumSpinner.getButtonMinus().addListener(main.getHandListener()); maximumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("maximum", maximumSpinner.getValue()); minimumSpinner.setMaximum(maximumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); minimumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("minimum", minimumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); refreshPreview(); } }); maximumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("maximum", maximumSpinner.getValue()); minimumSpinner.setMaximum(maximumSpinner.getValue()); refreshPreview(); } }); t.row(); t.add(new Label("Increment: ", getSkin())).right(); Spinner incrementSpinner = new Spinner(1.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); incrementSpinner.getTextField().setFocusTraversal(false); incrementSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("increment", incrementSpinner.getValue()); refreshPreview(); } }); incrementSpinner.getTextField().addListener(main.getIbeamListener()); t.add(incrementSpinner).growX(); incrementSpinner.getButtonMinus().addListener(main.getHandListener()); incrementSpinner.getButtonPlus().addListener(main.getHandListener()); incrementSpinner.setMinimum(1.0f); previewProperties.put("increment", incrementSpinner.getValue()); t.row(); t.add(new Label("Orientation: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Horizontal", "Vertical"}); if (getSelectedStyle().name.contains("vert")) { previewProperties.put("orientation", true); selectBox.setSelectedIndex(1); } else { previewProperties.put("orientation", false); } selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (selectBox.getSelectedIndex() == 0) { previewProperties.put("orientation", false); } else { previewProperties.put("orientation", true); } refreshPreview(); } }); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); t.add(selectBox).growX(); } else if (clazz.equals(SplitPane.class)) { t.row(); t.add(new Label("Orientation: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Horizontal", "Vertical"}); if (getSelectedStyle().name.contains("vert")) { previewProperties.put("orientation", true); selectBox.setSelectedIndex(1); } else { previewProperties.put("orientation", false); } selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (selectBox.getSelectedIndex() == 0) { previewProperties.put("orientation", false); } else { previewProperties.put("orientation", true); } refreshPreview(); } }); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); t.add(selectBox).growX(); t.row(); t.add(new Label("Sample Text: ", getSkin())).right(); TextArea textArea = new TextArea(PARAGRAPH_SAMPLE, getSkin()); textArea.setFocusTraversal(false); textArea.setPrefRows(5); textArea.addListener(main.getIbeamListener()); textArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", textArea.getText()); refreshPreview(); } }); previewProperties.put("text", textArea.getText()); t.add(textArea).growX(); previewSizeSelectBox.setSelectedIndex(2); } else if (clazz.equals(TextButton.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(TextField.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Password Mode: ", getSkin())).right(); ImageTextButton checkBox = new ImageTextButton("", getSkin(), "switch"); checkBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("passwordMode", checkBox.isChecked()); refreshPreview(); } }); t.add(checkBox).left(); checkBox.addListener(main.getHandListener()); previewProperties.put("passwordMode", checkBox.isChecked()); t.row(); t.add(new Label("Password Character: ", getSkin())); TextField pcTextField = new TextField("*", getSkin()); pcTextField.setFocusTraversal(false); pcTextField.addListener(main.getIbeamListener()); pcTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("password", pcTextField.getText()); refreshPreview(); } }); previewProperties.put("password", pcTextField.getText()); t.add(pcTextField).growX(); t.row(); t.add(new Label("Text Alignment: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Left", "Center", "Right"}); selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { switch (selectBox.getSelectedIndex()) { case 0: previewProperties.put("alignment", Align.left); break; case 1: previewProperties.put("alignment", Align.center); break; case 2: previewProperties.put("alignment", Align.right); break; } refreshPreview(); } }); t.add(selectBox).growX(); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); previewProperties.put("alignment", Align.left); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); t.row(); t.add(new Label("Message Text: ", getSkin())).right(); TextField messageTextField = new TextField(TEXT_SAMPLE, getSkin()); messageTextField.setFocusTraversal(false); messageTextField.addListener(main.getIbeamListener()); messageTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("message", messageTextField.getText()); refreshPreview(); } }); previewProperties.put("message", messageTextField.getText()); t.add(messageTextField).growX(); } else if (clazz.equals(TextTooltip.class)) { t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(Touchpad.class)) { } else if (clazz.equals(Tree.class)) { t.row(); t.add(new Label("Icon Spacing: ", getSkin())).right(); Spinner spinner = new Spinner(0.0, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().setFocusTraversal(false); spinner.setMinimum(1); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); t.add(spinner).growX(); t.row(); t.add(new Label("Y Spacing: ", getSkin())).right(); spinner = new Spinner(0.0, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().setFocusTraversal(false); spinner.setMinimum(1); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); t.add(spinner).growX(); } else if (clazz.equals(Window.class)) { t.row(); t.add(new Label("Title Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("title", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("title", previewTextField.getText()); t.add(previewTextField).growX(); t.row(); t.add(new Label("Sample Text Color: ", getSkin())); BrowseField textColorField = new BrowseField(null, null, getSkin(), "color"); textColorField.addListener(main.getHandListener()); t.add(textColorField).growX(); t.row(); t.add(new Label("Sample Text: ", getSkin())).right(); TextArea textArea = new TextArea(PARAGRAPH_SAMPLE, getSkin()); textArea.setFocusTraversal(false); textArea.setPrefRows(5); textArea.addListener(main.getIbeamListener()); textArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", textArea.getText()); refreshPreview(); } }); previewProperties.put("text", textArea.getText()); t.add(textArea).growX(); } previewSizeSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("size", previewSizeSelectBox.getSelectedIndex()); if (previewSizeSelectBox.getSelectedIndex() != 7) { refreshPreview(); } } }); previewProperties.put("size", previewSizeSelectBox.getSelectedIndex()); refreshPreview(); } else { t.add(new Label("Stage Color: ", getSkin())).right(); BrowseField browseField = new BrowseField(null, null, getSkin(), "color"); browseField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { main.getDialogFactory().showDialogColorPicker((Color) previewProperties.get("bgcolor"), new DialogColorPicker.ColorListener() { @Override public void selected(Color color) { if (color != null) { browseField.getTextButton().setText((int) (color.r * 255) + "," + (int) (color.g * 255) + "," + (int) (color.b * 255) + "," + (int) (color.a * 255)); previewProperties.put("bgcolor", color); previewBgColor.set(color); refreshPreview(); } } }); } }); browseField.addListener(main.getHandListener()); t.add(browseField).growX(); browseField.getTextButton().setText((int) (previewBgColor.r * 255) + "," + (int) (previewBgColor.g * 255) + "," + (int) (previewBgColor.b * 255) + "," + (int) (previewBgColor.a * 255)); } } } public void refreshPreview() { if (previewTable != null) { previewTable.clear(); previewTable.setBackground("white"); previewTable.setColor((Color) previewProperties.get("bgcolor")); for (BitmapFont font : previewFonts) { font.dispose(); } if (classSelectBox.getSelectedIndex() >= 0 && classSelectBox.getSelectedIndex() < Main.BASIC_CLASSES.length) { StyleData styleData = getSelectedStyle(); Class clazz = Main.BASIC_CLASSES[classSelectBox.getSelectedIndex()]; if (!styleData.hasMandatoryFields()) { Label label; if (clazz.equals(SelectBox.class)) { label = new Label("Please fill all mandatory fields\n(Highlighted on the left)\n\nscrollStyle and listStyle\nmust already be defined", getSkin()); } else if (clazz.equals(TextTooltip.class)) { label = new Label("Please fill all mandatory fields\n(Highlighted on the left)\n\nlabel must already be defined", getSkin()); } else { label = new Label("Please fill all mandatory fields\n(Highlighted on the left)", getSkin()); } label.setAlignment(Align.center); previewTable.add(label); } else if (styleData.hasAllNullFields()) { Label label; label = new Label("All fields are empty!\nEmpty classes are not exported\nAdd style properties in the menu to the left", getSkin()); label.setAlignment(Align.center); previewTable.add(label); } else { Actor widget = null; if (clazz.equals(Button.class)) { Button.ButtonStyle style = createPreviewStyle(Button.ButtonStyle.class, styleData); widget = new Button(style); ((Button)widget).setDisabled((boolean) previewProperties.get("disabled")); widget.addListener(main.getHandListener()); } else if (clazz.equals(CheckBox.class)) { CheckBox.CheckBoxStyle style = createPreviewStyle(CheckBox.CheckBoxStyle.class, styleData); widget = new CheckBox("", style); ((CheckBox)widget).setDisabled((boolean) previewProperties.get("disabled")); ((CheckBox)widget).setText((String) previewProperties.get("text")); widget.addListener(main.getHandListener()); } else if (clazz.equals(ImageButton.class)) { ImageButtonStyle style = createPreviewStyle(ImageButtonStyle.class, styleData); widget = new ImageButton(style); ((ImageButton)widget).setDisabled((boolean) previewProperties.get("disabled")); widget.addListener(main.getHandListener()); } else if (clazz.equals(ImageTextButton.class)) { ImageTextButton.ImageTextButtonStyle style = createPreviewStyle(ImageTextButton.ImageTextButtonStyle.class, styleData); widget = new ImageTextButton("", style); ((ImageTextButton)widget).setDisabled((boolean) previewProperties.get("disabled")); ((ImageTextButton)widget).setText((String) previewProperties.get("text")); widget.addListener(main.getHandListener()); } else if (clazz.equals(Label.class)) { LabelStyle style = createPreviewStyle(LabelStyle.class, styleData); widget = new Label("", style); ((Label)widget).setText((String) previewProperties.get("text")); } else if (clazz.equals(List.class)) { ListStyle style = createPreviewStyle(ListStyle.class, styleData); widget = new List(style); Array<String> items = new Array<>(((String) previewProperties.get("text")).split("\\n")); ((List)widget).setItems(items); widget.addListener(main.getHandListener()); } else if (clazz.equals(ProgressBar.class)) { ProgressBar.ProgressBarStyle style = createPreviewStyle(ProgressBar.ProgressBarStyle.class, styleData); widget = new ProgressBar((float) (double) previewProperties.get("minimum"), (float) (double) previewProperties.get("maximum"), (float) (double) previewProperties.get("increment"), (boolean) previewProperties.get("orientation"), style); ((ProgressBar) widget).setValue((float) (double) previewProperties.get("value")); ((ProgressBar)widget).setDisabled((boolean) previewProperties.get("disabled")); } else if (clazz.equals(ScrollPane.class)) { ScrollPaneStyle style = createPreviewStyle(ScrollPaneStyle.class, styleData); Label label = new Label("", getSkin()); widget = new ScrollPane(label, style); ((ScrollPane) widget).setScrollbarsOnTop((boolean) previewProperties.get("scrollbarsOnTop")); ((ScrollPane) widget).setScrollBarPositions((boolean) previewProperties.get("hScrollBarPosition"), (boolean) previewProperties.get("vScrollBarPosition")); ((ScrollPane) widget).setScrollingDisabled((boolean) previewProperties.get("hScrollDisabled"), (boolean) previewProperties.get("vScrollDisabled")); ((ScrollPane) widget).setForceScroll((boolean) previewProperties.get("forceHscroll"), (boolean) previewProperties.get("forceVscroll")); ((ScrollPane) widget).setVariableSizeKnobs((boolean) previewProperties.get("variableSizeKnobs")); ((ScrollPane) widget).setOverscroll((boolean) previewProperties.get("hOverscroll"), (boolean) previewProperties.get("vOverscroll")); ((ScrollPane) widget).setFadeScrollBars((boolean) previewProperties.get("fadeScroll")); ((ScrollPane) widget).setSmoothScrolling((boolean) previewProperties.get("smoothScroll")); ((ScrollPane) widget).setFlickScroll((boolean) previewProperties.get("flickScroll")); ((ScrollPane) widget).setClamp((boolean) previewProperties.get("clamp")); label.setText((String) previewProperties.get("text")); } else if (clazz.equals(SelectBox.class)) { SelectBox.SelectBoxStyle style = createPreviewStyle(SelectBox.SelectBoxStyle.class, styleData); widget = new SelectBox(style); ((SelectBox)widget).setDisabled((boolean) previewProperties.get("disabled")); Array<String> items = new Array<>(((String) previewProperties.get("text")).split("\\n")); ((SelectBox)widget).setItems(items); widget.addListener(main.getHandListener()); ((SelectBox)widget).getList().addListener(main.getHandListener()); } else if (clazz.equals(Slider.class)) { Slider.SliderStyle style = createPreviewStyle(Slider.SliderStyle.class, styleData); widget = new Slider((float) (double) previewProperties.get("minimum"), (float) (double) previewProperties.get("maximum"), (float) (double) previewProperties.get("increment"), (boolean) previewProperties.get("orientation"), style); ((Slider)widget).setDisabled((boolean) previewProperties.get("disabled")); widget.addListener(main.getHandListener()); } else if (clazz.equals(SplitPane.class)) { SplitPane.SplitPaneStyle style = createPreviewStyle(SplitPane.SplitPaneStyle.class, styleData); Label label1 = new Label("", getSkin()); Label label2 = new Label("", getSkin()); widget = new SplitPane(label1, label2, (boolean) previewProperties.get("orientation"), style); label1.setText((String) previewProperties.get("text")); label2.setText((String) previewProperties.get("text")); if ((boolean) previewProperties.get("orientation")) { widget.addListener(main.getVerticalResizeArrowListener()); } else { widget.addListener(main.getHorizontalResizeArrowListener()); } } else if (clazz.equals(TextButton.class)) { TextButtonStyle style = createPreviewStyle(TextButtonStyle.class, styleData); widget = new TextButton("", style); ((TextButton)widget).setDisabled((boolean) previewProperties.get("disabled")); ((TextButton)widget).setText((String) previewProperties.get("text")); widget.addListener(main.getHandListener()); } else if (clazz.equals(TextField.class)) { TextFieldStyle style = createPreviewStyle(TextFieldStyle.class, styleData); widget = new TextField("", style); ((TextField)widget).setFocusTraversal(false); ((TextField)widget).setDisabled((boolean) previewProperties.get("disabled")); ((TextField)widget).setPasswordMode((boolean) previewProperties.get("passwordMode")); ((TextField)widget).setAlignment((int) previewProperties.get("alignment")); ((TextField)widget).setText((String) previewProperties.get("text")); ((TextField)widget).setMessageText((String) previewProperties.get("message")); String string = (String) previewProperties.get("password"); if (string.length() > 0) { ((TextField)widget).setPasswordCharacter(string.charAt(0)); } widget.addListener(main.getIbeamListener()); } else if (clazz.equals(TextTooltip.class)) { TextTooltip.TextTooltipStyle style = createPreviewStyle(TextTooltip.TextTooltipStyle.class, styleData); TooltipManager manager = new TooltipManager(); manager.animations = false; manager.initialTime = 0.0f; manager.resetTime = 0.0f; manager.subsequentTime = 0.0f; manager.hideAll(); manager.instant(); TextTooltip toolTip = new TextTooltip((String) previewProperties.get("text"), manager, style); widget = new Label("Hover over me", getSkin()); widget.addListener(toolTip); } else if (clazz.equals(Touchpad.class)) { Touchpad.TouchpadStyle style = createPreviewStyle(Touchpad.TouchpadStyle.class, styleData); widget = new Touchpad(0, style); widget.addListener(main.getHandListener()); } else if (clazz.equals(Tree.class)) { Tree.TreeStyle style = createPreviewStyle(Tree.TreeStyle.class, styleData); widget = new Tree(style); String[] lines = {"this", "is", "a", "test"}; Tree.Node parentNode = null; for (String line: lines) { Label label = new Label(line, getSkin()); Tree.Node node = new Tree.Node(label); if (parentNode == null) { ((Tree) widget).add(node); } else { parentNode.add(node); } parentNode = node; } widget.addListener(main.getHandListener()); } else if (clazz.equals(Window.class)) { Window.WindowStyle style = createPreviewStyle(Window.WindowStyle.class, styleData); if (style.stageBackground != null) { previewTable.setBackground(style.stageBackground); previewTable.setColor(Color.WHITE); style.stageBackground = null; } Label sampleText = new Label("", getSkin()); sampleText.setText((String) previewProperties.get("text")); widget = new Window((String) previewProperties.get("title"), style); ((Window)widget).add(sampleText); } if (widget != null) { switch ((int) previewProperties.get("size")) { case (0): previewTable.add(widget).size(10.0f); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (1): previewTable.add(widget); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (2): previewTable.add(widget).size(200.0f); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (3): previewTable.add(widget).growX(); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (4): previewTable.add(widget).growY(); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (5): previewTable.add(widget).grow(); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (6): Actor addWidget = widget; TraversalTextField widthField = new TraversalTextField("", getSkin()); TraversalTextField heightField = new TraversalTextField("", getSkin()); widthField.setNextFocus(heightField); heightField.setNextFocus(widthField); Dialog dialog = new Dialog("Enter dimensions...", getSkin()) { @Override protected void result(Object object) { if ((boolean)object) { previewTable.add(addWidget).size(Integer.parseInt(widthField.getText()), Integer.parseInt(heightField.getText())); Array<String> items = new Array<>(DEFAULT_SIZES); items.add(widthField.getText() + "x" + heightField.getText()); previewProperties.put("sizeX", Integer.parseInt(widthField.getText())); previewProperties.put("sizeY", Integer.parseInt(heightField.getText())); previewSizeSelectBox.setItems(items); previewSizeSelectBox.setSelectedIndex(7); } else { previewSizeSelectBox.setSelectedIndex(1); } } }; dialog.getTitleTable().getCells().first().padLeft(5.0f); dialog.text("Enter the preview dimensions: "); dialog.getContentTable().getCells().first().pad(10.0f); dialog.getContentTable().row(); Table sizeTable = new Table(); sizeTable.add(widthField).padLeft(10.0f); sizeTable.add(new Label(" x ", getSkin())); sizeTable.add(heightField).padRight(10.0f); dialog.getContentTable().add(sizeTable); dialog.getButtonTable().defaults().padBottom(10.0f).minWidth(50.0f); dialog.button("OK", true); dialog.button("Cancel", false); TextButton okButton = (TextButton) dialog.getButtonTable().getCells().first().getActor(); okButton.setDisabled(true); okButton.addListener(main.getHandListener()); widthField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { okButton.setDisabled(!widthField.getText().matches("^\\d+$") || !heightField.getText().matches("^\\d+$")); } }); heightField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { okButton.setDisabled(!widthField.getText().matches("^\\d+$") || !heightField.getText().matches("^\\d+$")); } }); dialog.getButtonTable().getCells().get(1).getActor().addListener(main.getHandListener()); dialog.key(Input.Keys.ESCAPE, false); dialog.show(stage); stage.setKeyboardFocus(widthField); break; case (7): previewTable.add(widget).size((int) previewProperties.get("sizeX"), (int) previewProperties.get("sizeY")); break; } } } } else { CustomStyle customStyle = (CustomStyle) styleSelectBox.getSelected(); boolean showMessage = true; if (customStyle.getProperties().size == 0) { Label label = new Label("No style properties!\nEmpty classes are not exported\nAdd style properties in the menu to the left", getSkin()); label.setAlignment(0); previewTable.add(label); } else { for (CustomProperty customProperty : customStyle.getProperties()) { if (customProperty.getValue() != null && !(customProperty.getValue() instanceof String) || customProperty.getValue() != null && !((String)customProperty.getValue()).equals("")) { showMessage = false; break; } } if (showMessage) { Label label = new Label("All properties are empty!\nEmpty classes are not exported\nAdd style properties in the menu to the left", getSkin()); label.setAlignment(0); previewTable.add(label); } } if (!showMessage) { HorizontalGroup horizontalGroup = new HorizontalGroup(); horizontalGroup.wrap(); //the following causes a crash. LibGDX bug. // horizontalGroup.space(10.0f); horizontalGroup.wrapSpace(10.0f); horizontalGroup.setTouchable(Touchable.disabled); previewTable.add(horizontalGroup).grow().pad(10.0f); for (CustomProperty customProperty : customStyle.getProperties()) { if (customProperty.getValue() != null) { Container container = new Container(); container.pad(5.0f); horizontalGroup.addActor(container); switch (customProperty.getType()) { case TEXT: case RAW_TEXT: Label labelText = new Label((String) customProperty.getValue(), getSkin()); container.setActor(labelText); break; case NUMBER: Label labelNumber = new Label(Double.toString((double) customProperty.getValue()), getSkin()); container.setActor(labelNumber); break; case BOOL: Label labelBoolean = new Label(Boolean.toString((boolean) customProperty.getValue()), getSkin()); container.setActor(labelBoolean); break; case COLOR: ColorData colorData = null; String colorName = (String) customProperty.getValue(); for (ColorData cd : main.getJsonData().getColors()) { if (cd.getName().equals(colorName)) { colorData = cd; break; } } if (colorData != null) { Table colorTable = new Table(getSkin()); colorTable.setBackground("white"); colorTable.setColor(colorData.color); colorTable.add().size(25.0f); container.setActor(colorTable); } break; case FONT: BitmapFont font = null; FontData fontData = null; String fontName = (String) customProperty.getValue(); for (FontData fd : main.getJsonData().getFonts()) { if (fd.getName().equals(fontName)) { fontData = fd; font = new BitmapFont(fd.file); previewFonts.add(font); break; } } if (font != null) { Label labelFont = new Label(fontData.getName(), new LabelStyle(font, Color.WHITE)); container.setActor(labelFont); } FreeTypeFontData freeTypeFontData = null; for (FreeTypeFontData fd : main.getJsonData().getFreeTypeFonts()) { if (fd.name.equals(fontName)) { freeTypeFontData = fd; break; } } if (freeTypeFontData != null && freeTypeFontData.bitmapFont != null) { Label labelFont = new Label(freeTypeFontData.name, new LabelStyle(freeTypeFontData.bitmapFont, Color.WHITE)); container.setActor(labelFont); } break; case DRAWABLE: DrawableData drawable = null; String drawableName = (String) customProperty.getValue(); for (DrawableData dd : main.getAtlasData().getDrawables()) { if (dd.name.equals(drawableName)) { drawable = dd; break; } } if (drawable != null) { Image image = new Image(drawablePairs.get(drawable.name)); container.setActor(image); } break; } } } } } } } private <T> T createPreviewStyle(Class<T> clazz, StyleData styleData) { T returnValue = null; try { returnValue = ClassReflection.newInstance(clazz); Field[] fields = ClassReflection.getFields(clazz); for (Field field : fields) { Object value = styleData.properties.get(field.getName()).value; if (value != null) { if (field.getType().equals(Drawable.class)) { field.set(returnValue, drawablePairs.get((String) value)); } else if (field.getType().equals(Color.class)) { for (ColorData data : main.getProjectData().getJsonData().getColors()) { if (value.equals(data.getName())) { field.set(returnValue, data.color); break; } } } else if (field.getType().equals(BitmapFont.class)) { for (FontData data : main.getProjectData().getJsonData().getFonts()) { if (value.equals(data.getName())) { BitmapFont font = new BitmapFont(data.file); previewFonts.add(font); field.set(returnValue, font); } } for (FreeTypeFontData data : main.getJsonData().getFreeTypeFonts()) { if (value.equals(data.name)) { field.set(returnValue, data.bitmapFont); } } } else if (field.getType().equals(Float.TYPE)) { field.set(returnValue, (float) value); } else if (field.getType().equals(ListStyle.class)) { Array<StyleData> datas = main.getProjectData().getJsonData().getClassStyleMap().get(List.class); for (StyleData data : datas) { if (value.equals(data.name)) { ListStyle style = createPreviewStyle(ListStyle.class, data); field.set(returnValue, style); break; } } } else if (field.getType().equals(ScrollPaneStyle.class)) { Array<StyleData> datas = main.getProjectData().getJsonData().getClassStyleMap().get(ScrollPane.class); for (StyleData data : datas) { if (value.equals(data.name)) { ScrollPaneStyle style = createPreviewStyle(ScrollPaneStyle.class, data); field.set(returnValue, style); break; } } } else if (field.getType().equals(LabelStyle.class)) { Array<StyleData> datas = main.getProjectData().getJsonData().getClassStyleMap().get(Label.class); for (StyleData data : datas) { if (value.equals(data.name)) { LabelStyle style = createPreviewStyle(LabelStyle.class, data); field.set(returnValue, style); break; } } } } } } finally { return returnValue; } } /** * Writes a TextureAtlas based on drawables list. Creates drawables to be * displayed on screen * @return */ public boolean produceAtlas() { try { if (atlas != null) { atlas.dispose(); atlas = null; } if (!main.getProjectData().getAtlasData().atlasCurrent) { main.getProjectData().getAtlasData().writeAtlas(); main.getProjectData().getAtlasData().atlasCurrent = true; } atlas = main.getProjectData().getAtlasData().getAtlas(); for (DrawableData data : main.getProjectData().getAtlasData().getDrawables()) { Drawable drawable; if (data.customized) { drawable = getSkin().getDrawable("custom-drawable-skincomposer-image"); } else if (data.tiled) { String name = data.file.name(); name = DrawableData.proper(name); drawable = new TiledDrawable(atlas.findRegion(name)); drawable.setMinWidth(data.minWidth); drawable.setMinHeight(data.minHeight); ((TiledDrawable) drawable).getColor().set(main.getJsonData().getColorByName(data.tintName).color); } else if (data.file.name().matches(".*\\.9\\.[a-zA-Z0-9]*$")) { String name = data.file.name(); name = DrawableData.proper(name); drawable = new NinePatchDrawable(atlas.createPatch(name)); if (data.tint != null) { drawable = ((NinePatchDrawable) drawable).tint(data.tint); } else if (data.tintName != null) { drawable = ((NinePatchDrawable) drawable).tint(main.getProjectData().getJsonData().getColorByName(data.tintName).color); } } else { String name = data.file.name(); name = DrawableData.proper(name); drawable = new SpriteDrawable(atlas.createSprite(name)); if (data.tint != null) { drawable = ((SpriteDrawable) drawable).tint(data.tint); } else if (data.tintName != null) { drawable = ((SpriteDrawable) drawable).tint(main.getProjectData().getJsonData().getColorByName(data.tintName).color); } } drawablePairs.put(data.name, drawable); } return true; } catch (Exception e) { Gdx.app.error(getClass().getName(), "Error while attempting to generate drawables.", e); main.getDialogFactory().showDialogError("Atlas Error...", "Error while attempting to generate drawables.\n\nOpen log?"); return false; } } private void addStatusBar() { Table table = new Table(); table.setBackground(getSkin().getDrawable("status-bar")); add(table).growX(); statusLabel = new Label("", getSkin()); statusLabel.setColor(1.0f, 1.0f, 1.0f, 0.0f); table.add(statusLabel).padLeft(10.0f); Label label = new Label("ver. " + Main.VERSION + " RAY3K.WORDPRESS.COM © 2018 Raymond \"Raeleus\" Buckley", getSkin()); table.add(label).expandX().right().padRight(25.0f); } private void display(final String text) { SequenceAction sequenceAction = new SequenceAction(); if (statusLabel.isVisible()) { statusLabel.clearActions(); AlphaAction alphaAction = new AlphaAction(); alphaAction.setAlpha(0.0f); alphaAction.setDuration(.25f); sequenceAction.addAction(alphaAction); RunnableAction runnableAction = new RunnableAction(); runnableAction.setRunnable(() -> { statusLabel.setText(text); }); sequenceAction.addAction(runnableAction); alphaAction = new AlphaAction(); alphaAction.setAlpha(1.0f); alphaAction.setDuration(.25f); sequenceAction.addAction(alphaAction); DelayAction delayAction = new DelayAction(); delayAction.setDuration(3.0f); sequenceAction.addAction(delayAction); alphaAction = new AlphaAction(); alphaAction.setAlpha(0.0f); alphaAction.setDuration(1.5f); sequenceAction.addAction(alphaAction); VisibleAction visibleAction = new VisibleAction(); visibleAction.setVisible(false); sequenceAction.addAction(visibleAction); } else { statusLabel.setText(text); statusLabel.clearActions(); statusLabel.setVisible(true); AlphaAction alphaAction = new AlphaAction(); alphaAction.setAlpha(1.0f); alphaAction.setDuration(.5f); sequenceAction.addAction(alphaAction); DelayAction delayAction = new DelayAction(); delayAction.setDuration(3.0f); sequenceAction.addAction(delayAction); alphaAction = new AlphaAction(); alphaAction.setAlpha(0.0f); alphaAction.setDuration(1.5f); sequenceAction.addAction(alphaAction); VisibleAction visibleAction = new VisibleAction(); visibleAction.setVisible(false); sequenceAction.addAction(visibleAction); } statusLabel.addAction(sequenceAction); } public void setStatusBarMessage(String text) { statusLabel.setColor(new Color(1.0f, 1.0f, 1.0f, statusLabel.getColor().a)); display(text); } public void setStatusBarError(String text) { statusLabel.setColor(new Color(1.0f, 0.0f, 0.0f, statusLabel.getColor().a)); display(text); } public SelectBox getClassSelectBox() { return classSelectBox; } public SelectBox getStyleSelectBox() { return styleSelectBox; } public Class getSelectedClass() { return Main.BASIC_CLASSES[classSelectBox.getSelectedIndex()]; } public StyleData getSelectedStyle() { OrderedMap<Class, Array<StyleData>> classStyleMap = main.getProjectData().getJsonData().getClassStyleMap(); return classStyleMap.get(getSelectedClass()).get(styleSelectBox.getSelectedIndex()); } public void setStyleProperties(Array<StyleProperty> styleProperties) { this.styleProperties = styleProperties; customProperties = null; } public void setCustomStyleProperties(Array<CustomProperty> styleProperties) { this.styleProperties = null; customProperties = styleProperties; } private class ScrollPaneListener extends InputListener { @Override public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) { if (event.getTarget() instanceof ScrollPane) { ScrollPane scrollPane = (ScrollPane) event.getTarget(); //if the scroll pane is scrollable if (!Float.isNaN(scrollPane.getScrollPercentY())) { stage.setScrollFocus(scrollPane); } } } } private class MenuBarListener extends MenuButtonListener { private final MenuButton<MenuItem> menuButton; public MenuBarListener(MenuButton<MenuItem> menuButton) { this.menuButton = menuButton; } @Override public void menuClicked() { fire(new RootTableEvent(menuButton.getSelectedItem().event)); } } private static class MenuItem { String text; RootTableEnum event; public MenuItem(String text, RootTableEnum enumeration) { this.text = text; this.event = enumeration; } @Override public String toString() { return text; } } public static enum RootTableEnum { NEW, OPEN, RECENT_FILES, SAVE, SAVE_AS, IMPORT, EXPORT, EXIT, UNDO, REDO, SETTINGS, COLORS, FONTS, DRAWABLES, ABOUT, CLASS_SELECTED, NEW_CLASS, DUPLICATE_CLASS, DELETE_CLASS, RENAME_CLASS, STYLE_SELECTED, NEW_STYLE, DUPLICATE_STYLE, DELETE_STYLE, RENAME_STYLE, PREVIEW_PROPERTY, WELCOME, REFRESH_ATLAS, DOWNLOAD_UPDATE, CHECK_FOR_UPDATES_COMPLETE; } public static class RootTableEvent extends Event { public RootTableEnum rootTableEnum; public RootTableEvent(RootTableEnum rootTableEnum) { this.rootTableEnum = rootTableEnum; } } private static class LoadClassesEvent extends Event { SelectBox classSelectBox; public LoadClassesEvent(SelectBox classSelectBox) { this.classSelectBox = classSelectBox; } } private static class LoadStylesEvent extends Event { SelectBox classSelectBox; SelectBox styleSelectBox; public LoadStylesEvent(SelectBox classSelectBox, SelectBox styleSelectBox) { this.classSelectBox = classSelectBox; this.styleSelectBox = styleSelectBox; } } private static class StylePropertyEvent extends Event { StyleProperty styleProperty; Actor styleActor; public StylePropertyEvent(StyleProperty styleProperty, Actor styleActor) { this.styleProperty = styleProperty; this.styleActor = styleActor; } } private static enum CustomPropertyEnum { NEW, DUPLICATE, DELETE, RENAME, CHANGE_VALUE; } private static class CustomPropertyEvent extends Event { private CustomProperty customProperty; private CustomPropertyEnum customPropertyEnum; private Actor styleActor; public CustomPropertyEvent(CustomProperty customProperty, Actor styleActor, CustomPropertyEnum customPropertyEnum) { this.customProperty = customProperty; this.customPropertyEnum = customPropertyEnum; this.styleActor = styleActor; } } public static abstract class RootTableListener implements EventListener { @Override public boolean handle(Event event) { if (event instanceof RootTableEvent) { rootEvent((RootTableEvent) event); } else if (event instanceof LoadClassesEvent) { loadClasses(((LoadClassesEvent) event).classSelectBox); } else if (event instanceof LoadStylesEvent) { loadStyles(((LoadStylesEvent) event).classSelectBox, ((LoadStylesEvent) event).styleSelectBox); } else if (event instanceof StylePropertyEvent) { stylePropertyChanged(((StylePropertyEvent) event).styleProperty, ((StylePropertyEvent) event).styleActor); } else if (event instanceof CustomPropertyEvent) { CustomPropertyEvent propertyEvent = (CustomPropertyEvent) event; if (null != propertyEvent.customPropertyEnum) switch (propertyEvent.customPropertyEnum) { case NEW: newCustomProperty(); break; case DELETE: deleteCustomProperty(propertyEvent.customProperty); break; case RENAME: renameCustomProperty(propertyEvent.customProperty); break; case DUPLICATE: duplicateCustomProperty(propertyEvent.customProperty); break; case CHANGE_VALUE: customPropertyValueChanged(propertyEvent.customProperty, propertyEvent.styleActor); break; default: break; } } return false; } public abstract void rootEvent(RootTableEvent event); public abstract void stylePropertyChanged(StyleProperty styleProperty, Actor styleActor); public abstract void loadClasses(SelectBox classSelectBox); public abstract void loadStyles(SelectBox classSelectBox, SelectBox styleSelectBox); public abstract void newCustomProperty(); public abstract void duplicateCustomProperty(CustomProperty customProperty); public abstract void deleteCustomProperty(CustomProperty customProperty); public abstract void customPropertyValueChanged(CustomProperty customProperty, Actor styleActor); public abstract void renameCustomProperty(CustomProperty customProperty); } public static class ShortcutListener extends InputListener { private final RootTable rootTable; public ShortcutListener(RootTable rootTable) { this.rootTable = rootTable; } @Override public boolean keyDown(InputEvent event, int keycode) { boolean listenForShortcuts = true; for (Actor actor : rootTable.getStage().getActors()) { if (actor instanceof Dialog) { listenForShortcuts = false; break; } } //trigger shortcuts only if no dialogs are open. if (listenForShortcuts) { if (Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Input.Keys.CONTROL_RIGHT)) { char character = rootTable.main.getDesktopWorker().getKeyName(keycode); switch (character) { case 'z': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.UNDO)); break; case 'y': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.REDO)); break; case 'n': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.NEW)); break; case 'o': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.OPEN)); break; case 's': if (Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Input.Keys.SHIFT_RIGHT)) { rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.SAVE_AS)); } else { rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.SAVE)); } break; case 'e': rootTable.fire(new RootTable.RootTableEvent(RootTableEnum.EXPORT)); break; default: break; } } switch (keycode) { case Input.Keys.F5: rootTable.fire(new RootTable.RootTableEvent(RootTableEnum.REFRESH_ATLAS)); break; } } return false; } } public ObjectMap<String, Drawable> getDrawablePairs() { return drawablePairs; } }
core/src/com/ray3k/skincomposer/RootTable.java
/** ***************************************************************************** * MIT License * * Copyright (c) 2018 Raymond Buckley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * 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.ray3k.skincomposer; import com.ray3k.skincomposer.data.CustomProperty; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.Action; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Event; import com.badlogic.gdx.scenes.scene2d.EventListener; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.InputListener; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.badlogic.gdx.scenes.scene2d.actions.AlphaAction; import com.badlogic.gdx.scenes.scene2d.actions.DelayAction; import com.badlogic.gdx.scenes.scene2d.actions.RunnableAction; import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction; import com.badlogic.gdx.scenes.scene2d.actions.VisibleAction; import com.badlogic.gdx.scenes.scene2d.ui.Button; import com.badlogic.gdx.scenes.scene2d.ui.CheckBox; import com.badlogic.gdx.scenes.scene2d.ui.Container; import com.badlogic.gdx.scenes.scene2d.ui.Dialog; import com.badlogic.gdx.scenes.scene2d.ui.HorizontalGroup; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton; import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.badlogic.gdx.scenes.scene2d.ui.List; import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle; import com.badlogic.gdx.scenes.scene2d.ui.ProgressBar; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane; import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle; import com.badlogic.gdx.scenes.scene2d.ui.SelectBox; import com.badlogic.gdx.scenes.scene2d.ui.Slider; import com.badlogic.gdx.scenes.scene2d.ui.SplitPane; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextArea; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextField; import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle; import com.badlogic.gdx.scenes.scene2d.ui.TextTooltip; import com.badlogic.gdx.scenes.scene2d.ui.TooltipManager; import com.badlogic.gdx.scenes.scene2d.ui.Touchpad; import com.badlogic.gdx.scenes.scene2d.ui.Tree; import com.badlogic.gdx.scenes.scene2d.ui.Window; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.DragListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.NinePatchDrawable; import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable; import com.badlogic.gdx.scenes.scene2d.utils.TiledDrawable; import com.badlogic.gdx.utils.Align; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.ObjectMap; import com.badlogic.gdx.utils.OrderedMap; import com.badlogic.gdx.utils.reflect.ClassReflection; import com.badlogic.gdx.utils.reflect.Field; import com.ray3k.skincomposer.MenuButton.MenuButtonListener; import com.ray3k.skincomposer.data.ColorData; import com.ray3k.skincomposer.data.CustomProperty.PropertyType; import com.ray3k.skincomposer.data.CustomStyle; import com.ray3k.skincomposer.data.DrawableData; import com.ray3k.skincomposer.data.FontData; import com.ray3k.skincomposer.data.FreeTypeFontData; import com.ray3k.skincomposer.data.StyleData; import com.ray3k.skincomposer.data.StyleProperty; import com.ray3k.skincomposer.dialog.DialogColorPicker; import com.ray3k.skincomposer.utils.Utils; public class RootTable extends Table { private final Stage stage; private final Main main; private SelectBox classSelectBox; private SelectBox styleSelectBox; private Array<StyleProperty> styleProperties; private Array<CustomProperty> customProperties; private Table stylePropertiesTable; private Table previewPropertiesTable; private Table previewTable; private ScrollPane stylePropertiesScrollPane; private final ScrollPaneListener scrollPaneListener; private final ObjectMap<String, Object> previewProperties; private final Color previewBgColor; private SelectBox<String> previewSizeSelectBox; private static final String[] DEFAULT_SIZES = {"small", "default", "large", "growX", "growY", "grow", "custom"}; private static final String TEXT_SAMPLE = "Lorem ipsum dolor sit"; private static final String PARAGRAPH_SAMPLE = "Lorem ipsum dolor sit amet, consectetur\n" + "adipiscing elit, sed do eiusmod tempor\n" + "incididunt ut labore et dolore magna\n" + "aliqua. Ut enim ad minim veniam, quis\n" + "nostrud exercitation ullamco laboris\n" + "nisi ut aliquip ex ea commodo\n" + "consequat. Duis aute irure dolor in\n" + "reprehenderit in voluptate velit esse\n" + "cillum dolore eu fugiat nulla pariatur.\n" + "Excepteur sint occaecat cupidatat non\n" + "proident, sunt in culpa qui officia\n" + "deserunt mollit anim id est laborum.\n"; private static final String PARAGRAPH_SAMPLE_EXT = PARAGRAPH_SAMPLE + "\n\n\n" + PARAGRAPH_SAMPLE + "\n\n\n" + PARAGRAPH_SAMPLE + "\n\n\n" + PARAGRAPH_SAMPLE; private final Array<BitmapFont> previewFonts; private final ObjectMap<String, Drawable> drawablePairs; private TextureAtlas atlas; private MenuItem undoButton; private MenuItem redoButton; private MenuItem recentFilesButton; private MenuButton fileMenu; private MenuButton editMenu; private Label statusLabel; private Button classDuplicateButton; private Button classDeleteButton; private Button classRenameButton; private Button styleDeleteButton; private Button styleRenameButton; public RootTable(Main main) { super(main.getSkin()); this.stage = main.getStage(); this.main = main; previewProperties = new ObjectMap<>(); previewBgColor = new Color(Color.WHITE); scrollPaneListener = new ScrollPaneListener(); previewFonts = new Array<>(); drawablePairs = new ObjectMap<>(); produceAtlas(); main.getStage().addListener(new ShortcutListener(this)); } public void populate() { clearChildren(); addFileMenu(); row(); addClassBar(); row(); addStyleAndPreviewSplit(); row(); addStatusBar(); } private void addFileMenu() { Table table = new Table(); table.defaults().padRight(2.0f); add(table).growX().padTop(2.0f); MenuButtonGroup menuButtonGroup = new MenuButtonGroup(); fileMenu = new MenuButton("File", getSkin()); fileMenu.addListener(main.getHandListener()); fileMenu.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(fileMenu); table.add(fileMenu).padLeft(2.0f); recentFilesButton = new MenuItem("Recent Files...", RootTableEnum.RECENT_FILES); fileMenu.setItems(new MenuItem("New", RootTableEnum.NEW), new MenuItem("Open...", RootTableEnum.OPEN), recentFilesButton, new MenuItem("Save", RootTableEnum.SAVE), new MenuItem("Save As...", RootTableEnum.SAVE_AS), new MenuItem("Welcome Screen...", RootTableEnum.WELCOME), new MenuItem("Import...", RootTableEnum.IMPORT), new MenuItem("Export...", RootTableEnum.EXPORT), new MenuItem("Exit", RootTableEnum.EXIT)); if (Utils.isMac()) { fileMenu.setShortcuts("⌘+N", "⌘+O", null, "⌘+S", "Shift+⌘+S", null, null, "⌘+E"); } else { fileMenu.setShortcuts("Ctrl+N", "Ctrl+O", null, "Ctrl+S", "Shift+Ctrl+S", null, null, "Ctrl+E"); } fileMenu.addListener(new MenuBarListener(fileMenu)); editMenu = new MenuButton("Edit", getSkin()); editMenu.addListener(main.getHandListener()); editMenu.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(editMenu); table.add(editMenu); undoButton = new MenuItem("Undo", RootTableEnum.UNDO); redoButton = new MenuItem("Redo", RootTableEnum.REDO); editMenu.setItems(undoButton, redoButton); if (Utils.isMac()) { editMenu.setShortcuts("⌘+Z", "⌘+Y"); } else { editMenu.setShortcuts("Ctrl+Z", "Ctrl+Y"); } editMenu.setDisabled(undoButton, true); editMenu.setDisabled(redoButton, true); editMenu.addListener(new MenuBarListener(editMenu)); MenuButton<MenuItem> menuButton = new MenuButton("Project", getSkin()); menuButton.addListener(main.getHandListener()); menuButton.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(menuButton); table.add(menuButton); menuButton.setItems(new MenuItem("Settings...", RootTableEnum.SETTINGS), new MenuItem("Colors...", RootTableEnum.COLORS), new MenuItem("Fonts...", RootTableEnum.FONTS), new MenuItem("Drawables...", RootTableEnum.DRAWABLES), new MenuItem("Refresh Atlas", RootTableEnum.REFRESH_ATLAS)); menuButton.setShortcuts(null, null, null, null, "F5"); menuButton.addListener(new MenuBarListener(menuButton)); menuButton = new MenuButton("Help", getSkin()); menuButton.addListener(main.getHandListener()); menuButton.getMenuList().addListener(main.getHandListener()); menuButtonGroup.add(menuButton); table.add(menuButton); menuButton.setItems(new MenuItem("About...", RootTableEnum.ABOUT)); menuButton.addListener(new MenuBarListener(menuButton)); Button button = new Button(getSkin(), "download"); button.setName("downloadButton"); table.add(button).expandX().right(); button.addListener(new TextTooltip("Update Available", main.getTooltipManager(), getSkin())); button.addListener(main.getHandListener()); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DOWNLOAD_UPDATE)); } }); button.setVisible(false); } public void setRecentFilesDisabled(boolean disabled) { fileMenu.setDisabled(recentFilesButton, disabled); } public void setUndoDisabled(boolean disabled) { editMenu.setDisabled(undoButton, disabled); } public void setRedoDisabled(boolean disabled) { editMenu.setDisabled(redoButton, disabled); } public void setUndoText(String text) { undoButton.text = text; editMenu.updateContents(); } public void setRedoText(String text) { redoButton.text = text; editMenu.updateContents(); } private void addClassBar() { Table table = new Table(); table.setBackground(getSkin().getDrawable("class-bar")); add(table).expandX().left().growX(); Label label = new Label("Class:", getSkin()); table.add(label).padRight(10.0f).padLeft(10.0f); classSelectBox = new SelectBox(getSkin()); classSelectBox.addListener(main.getHandListener()); classSelectBox.getList().addListener(main.getHandListener()); table.add(classSelectBox).padRight(5.0f).minWidth(150.0f); classSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.CLASS_SELECTED)); fire(new LoadStylesEvent(classSelectBox, styleSelectBox)); } }); Button button = new Button(getSkin(), "new"); button.addListener(main.getHandListener()); table.add(button); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.NEW_CLASS)); } }); //Tooltip TextTooltip toolTip = new TextTooltip("New Class", main.getTooltipManager(), getSkin()); button.addListener(toolTip); classDuplicateButton = new Button(getSkin(), "duplicate"); classDuplicateButton.setDisabled(true); classDuplicateButton.addListener(main.getHandListener()); table.add(classDuplicateButton); classDuplicateButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DUPLICATE_CLASS)); } }); toolTip = new TextTooltip("Duplicate Class", main.getTooltipManager(), getSkin()); classDuplicateButton.addListener(toolTip); classDeleteButton = new Button(getSkin(), "delete"); classDeleteButton.setDisabled(true); table.add(classDeleteButton); classDeleteButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DELETE_CLASS)); } }); toolTip = new TextTooltip("Delete Class", main.getTooltipManager(), getSkin()); classDeleteButton.addListener(toolTip); classRenameButton = new Button(getSkin(), "settings"); classRenameButton.setDisabled(true); table.add(classRenameButton).padRight(30.0f); classRenameButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.RENAME_CLASS)); } }); toolTip = new TextTooltip("Rename Class", main.getTooltipManager(), getSkin()); classRenameButton.addListener(toolTip); label = new Label("Style:", getSkin()); table.add(label).padRight(10.0f); styleSelectBox = new SelectBox(getSkin()); table.add(styleSelectBox).padRight(5.0f).minWidth(150.0f); styleSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.STYLE_SELECTED)); } }); styleSelectBox.addListener(main.getHandListener()); styleSelectBox.getList().addListener(main.getHandListener()); button = new Button(getSkin(), "new"); button.addListener(main.getHandListener()); table.add(button); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.NEW_STYLE)); } }); toolTip = new TextTooltip("New Style", main.getTooltipManager(), getSkin()); button.addListener(toolTip); button = new Button(getSkin(), "duplicate"); button.addListener(main.getHandListener()); table.add(button); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DUPLICATE_STYLE)); } }); toolTip = new TextTooltip("Duplicate Style", main.getTooltipManager(), getSkin()); button.addListener(toolTip); styleDeleteButton = new Button(getSkin(), "delete"); styleDeleteButton.addListener(main.getHandListener()); table.add(styleDeleteButton); styleDeleteButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.DELETE_STYLE)); } }); toolTip = new TextTooltip("Delete Style", main.getTooltipManager(), getSkin()); styleDeleteButton.addListener(toolTip); styleRenameButton = new Button(getSkin(), "settings"); table.add(styleRenameButton).expandX().left(); styleRenameButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new RootTableEvent(RootTableEnum.RENAME_STYLE)); } }); toolTip = new TextTooltip("Rename Style", main.getTooltipManager(), getSkin()); styleRenameButton.addListener(toolTip); fire(new LoadClassesEvent(classSelectBox)); fire(new LoadStylesEvent(classSelectBox, styleSelectBox)); } public void setClassDuplicateButtonDisabled(boolean disabled) { classDuplicateButton.setDisabled(disabled); if (disabled) { if (classDuplicateButton.getListeners().contains(main.getHandListener(), true)) { classDuplicateButton.removeListener(main.getHandListener()); } } else { if (!classDuplicateButton.getListeners().contains(main.getHandListener(), true)) { classDuplicateButton.addListener(main.getHandListener()); } } } public void setClassDeleteButtonDisabled(boolean disabled) { classDeleteButton.setDisabled(disabled); if (disabled) { if (classDeleteButton.getListeners().contains(main.getHandListener(), true)) { classDeleteButton.removeListener(main.getHandListener()); } } else { if (!classDeleteButton.getListeners().contains(main.getHandListener(), true)) { classDeleteButton.addListener(main.getHandListener()); } } } public void setClassRenameButtonDisabled(boolean disabled) { classRenameButton.setDisabled(disabled); if (disabled) { if (classRenameButton.getListeners().contains(main.getHandListener(), true)) { classRenameButton.removeListener(main.getHandListener()); } } else { if (!classRenameButton.getListeners().contains(main.getHandListener(), true)) { classRenameButton.addListener(main.getHandListener()); } } } public void setStyleDeleteButtonDisabled(boolean disabled) { styleDeleteButton.setDisabled(disabled); if (disabled) { if (styleDeleteButton.getListeners().contains(main.getHandListener(), true)) { styleDeleteButton.removeListener(main.getHandListener()); } } else { if (!styleDeleteButton.getListeners().contains(main.getHandListener(), true)) { styleDeleteButton.addListener(main.getHandListener()); } } } public void setStyleRenameButtonDisabled(boolean disabled) { styleRenameButton.setDisabled(disabled); if (disabled) { if (styleRenameButton.getListeners().contains(main.getHandListener(), true)) { styleRenameButton.removeListener(main.getHandListener()); } } else { if (!styleRenameButton.getListeners().contains(main.getHandListener(), true)) { styleRenameButton.addListener(main.getHandListener()); } } } private void addStyleAndPreviewSplit() { stylePropertiesTable = new Table(); stylePropertiesTable.setTouchable(Touchable.enabled); addStyleProperties(stylePropertiesTable); Table right = new Table(); right.setTouchable(Touchable.enabled); addPreviewPreviewPropertiesSplit(right, scrollPaneListener); SplitPane splitPane = new SplitPane(stylePropertiesTable, right, false, getSkin()); add(splitPane).grow(); splitPane.addListener(main.getHorizontalResizeArrowListener()); } public void refreshStyleProperties(boolean preserveScroll) { if (stylePropertiesTable != null && stylePropertiesScrollPane != null) { float scrollY; if (preserveScroll) { scrollY = stylePropertiesScrollPane.getScrollY(); } else { scrollY = 0; } stylePropertiesTable.clearChildren(); addStyleProperties(stylePropertiesTable); if (preserveScroll) { validate(); stylePropertiesScrollPane.setSmoothScrolling(false); stylePropertiesScrollPane.setScrollY(scrollY); stylePropertiesScrollPane.addAction(new SequenceAction(new DelayAction(.1f), new Action() { @Override public boolean act(float delta) { stylePropertiesScrollPane.setSmoothScrolling(true); return true; } })); } } } public void refreshClasses(boolean scrollToNewest) { int classSelectedIndex = classSelectBox.getSelectedIndex(); populate(); if (scrollToNewest) { classSelectBox.setSelectedIndex(classSelectBox.getItems().size - 1); } else { classSelectBox.setSelectedIndex(Math.min(classSelectedIndex, classSelectBox.getItems().size - 1)); } } public void refreshStyles(boolean scrollToNewest) { int classSelectedIndex = classSelectBox.getSelectedIndex(); populate(); classSelectBox.setSelectedIndex(classSelectedIndex); if (scrollToNewest) { styleSelectBox.setSelectedIndex(styleSelectBox.getItems().size - 1); } } private void addStyleProperties(final Table left) { Label label = new Label("Style Properties", getSkin(), "title"); left.add(label); left.row(); Table table = new Table(); table.defaults().padLeft(10.0f).padRight(10.0f).growX(); stylePropertiesScrollPane = new ScrollPane(table, getSkin()); stylePropertiesScrollPane.setFadeScrollBars(false); stylePropertiesScrollPane.setFlickScroll(false); stylePropertiesScrollPane.addListener(scrollPaneListener); stage.setScrollFocus(stylePropertiesScrollPane); left.add(stylePropertiesScrollPane).grow().padTop(10.0f).padBottom(10.0f); //gather all scrollPaneStyles Array<StyleData> scrollPaneStyles = main.getProjectData().getJsonData().getClassStyleMap().get(ScrollPane.class); //gather all listStyles Array<StyleData> listStyles = main.getProjectData().getJsonData().getClassStyleMap().get(List.class); //gather all labelStyles Array<StyleData> labelStyles = main.getProjectData().getJsonData().getClassStyleMap().get(Label.class); if (styleProperties != null) { for (StyleProperty styleProperty : styleProperties) { table.row(); if (styleProperty.type == Color.class) { BrowseField browseField; if (styleProperty.optional) { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "color"); } else { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "color-required"); } browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new StylePropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.type == BitmapFont.class) { BrowseField browseField; if (styleProperty.optional) { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "font"); } else { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "font-required"); } browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new StylePropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.type == Drawable.class) { BrowseField browseField; if (styleProperty.optional) { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "drawable"); } else { browseField = new BrowseField((String) styleProperty.value, styleProperty.name, getSkin(), "drawable-required"); } browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new StylePropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.type == Float.TYPE) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); Spinner spinner = new Spinner((Double) styleProperty.value, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); table.add(spinner); spinner.addListener(new StylePropertyChangeListener(styleProperty, spinner)); } else if (styleProperty.type == ScrollPaneStyle.class) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); SelectBox<StyleData> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(scrollPaneStyles); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); if (styleProperty.value != null) { String name = ((String) styleProperty.value); int index = 0; for (StyleData styleData : scrollPaneStyles) { if (styleData.name.equals(name)) { break; } else { index++; } } if (index < scrollPaneStyles.size) { selectBox.setSelectedIndex(index); } } table.add(selectBox); selectBox.addListener(new StylePropertyChangeListener(styleProperty, selectBox)); } else if (styleProperty.type == ListStyle.class) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); SelectBox<StyleData> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(listStyles); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); if (styleProperty.value != null) { String name = ((String) styleProperty.value); int index = 0; for (StyleData styleData : listStyles) { if (styleData.name.equals(name)) { break; } else { index++; } } if (index < listStyles.size) { selectBox.setSelectedIndex(index); } } table.add(selectBox); selectBox.addListener(new StylePropertyChangeListener(styleProperty, selectBox)); } else if (styleProperty.type == LabelStyle.class) { if (styleProperty.optional) { label = new Label(styleProperty.name, getSkin()); } else { label = new Label(styleProperty.name, getSkin(), "required"); } table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); SelectBox<StyleData> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(labelStyles); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); if (styleProperty.value != null) { String name = ((String) styleProperty.value); int index = 0; for (StyleData styleData : labelStyles) { if (styleData.name.equals(name)) { break; } else { index++; } } if (index < labelStyles.size) { selectBox.setSelectedIndex(index); } } table.add(selectBox); selectBox.addListener(new StylePropertyChangeListener(styleProperty, selectBox)); } table.row(); } } else if (customProperties != null) { for (CustomProperty styleProperty : customProperties) { if (styleProperty.getType() == PropertyType.COLOR) { String value = ""; if (styleProperty.getValue() instanceof String) { for (ColorData color : main.getJsonData().getColors()) { if (color.getName().equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); break; } } } BrowseField browseField = new BrowseField(value, styleProperty.getName(), getSkin(), "color"); browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new CustomPropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.getType() == PropertyType.FONT) { String value = ""; if (styleProperty.getValue() instanceof String) { for (FontData font : main.getJsonData().getFonts()) { if (font.getName().equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); break; } } for (FreeTypeFontData font : main.getJsonData().getFreeTypeFonts()) { if (font.name.equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); } } } BrowseField browseField = new BrowseField(value, styleProperty.getName(), getSkin(), "font"); browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new CustomPropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.getType() == PropertyType.DRAWABLE) { String value = ""; if (styleProperty.getValue() instanceof String) { for (DrawableData drawable : main.getAtlasData().getDrawables()) { if (drawable.name.equals(styleProperty.getValue())) { value = (String) styleProperty.getValue(); break; } } } BrowseField browseField = new BrowseField(value, styleProperty.getName(), getSkin(), "drawable"); browseField.addListener(main.getHandListener()); table.add(browseField).padTop(20.0f); browseField.addListener(new CustomPropertyChangeListener(styleProperty, browseField)); } else if (styleProperty.getType() == PropertyType.NUMBER) { label = new Label(styleProperty.getName(), getSkin()); table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); if (styleProperty.getValue() instanceof Float) { styleProperty.setValue((double) (float) styleProperty.getValue()); } Double value = 0.0; if (styleProperty.getValue() instanceof Double) { value = (Double) styleProperty.getValue(); } Spinner spinner = new Spinner(value, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.setRound(false); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); table.add(spinner); spinner.addListener(new CustomPropertyChangeListener(styleProperty, spinner)); } else if (styleProperty.getType() == PropertyType.TEXT || styleProperty.getType() == PropertyType.RAW_TEXT) { label = new Label(styleProperty.getName(), getSkin()); table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); String value = ""; if (styleProperty.getValue() instanceof String) { value = (String) styleProperty.getValue(); } TextField textField = new TextField(value, getSkin()); textField.setAlignment(Align.center); textField.addListener(main.getIbeamListener()); table.add(textField); textField.addListener(new CustomPropertyChangeListener(styleProperty, textField)); } else if (styleProperty.getType() == PropertyType.BOOL) { label = new Label(styleProperty.getName(), getSkin()); table.add(label).padTop(20.0f).fill(false).expand(false, false); table.row(); Button button = new Button(getSkin(), "switch"); boolean value = false; if (styleProperty.getValue() instanceof Boolean) { value = (boolean) styleProperty.getValue(); } button.setChecked(value); table.add(button).fill(false); button.addListener(new CustomPropertyChangeListener(styleProperty, button)); } Button duplicateButton = new Button(getSkin(), "duplicate"); table.add(duplicateButton).fill(false).expand(false, false).pad(0).bottom(); duplicateButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProperty, duplicateButton, CustomPropertyEnum.DUPLICATE)); } }); TextTooltip toolTip = new TextTooltip("Duplicate Style Property", main.getTooltipManager(), getSkin()); duplicateButton.addListener(toolTip); Button deleteButton = new Button(getSkin(), "delete"); table.add(deleteButton).fill(false).expand(false, false).pad(0).bottom(); deleteButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProperty, duplicateButton, CustomPropertyEnum.DELETE)); } }); toolTip = new TextTooltip("Delete Style Property", main.getTooltipManager(), getSkin()); deleteButton.addListener(toolTip); Button renameButton = new Button(getSkin(), "settings"); table.add(renameButton).fill(false).expand(false, false).pad(0).bottom(); renameButton.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProperty, duplicateButton, CustomPropertyEnum.RENAME)); } }); toolTip = new TextTooltip("Rename Style Property", main.getTooltipManager(), getSkin()); renameButton.addListener(toolTip); table.row(); } left.row(); table = new Table(); left.add(table).right().padBottom(10.0f); Button button = new Button(getSkin(), "new"); button.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(null, null, CustomPropertyEnum.NEW)); } }); table.add(button); TextTooltip toolTip = new TextTooltip("New Style Property", main.getTooltipManager(), getSkin()); button.addListener(toolTip); } } private class StylePropertyChangeListener extends ChangeListener { private final StyleProperty styleProp; private final Actor styleActor; public StylePropertyChangeListener(StyleProperty styleProp, Actor styleActor) { this.styleProp = styleProp; this.styleActor = styleActor; } @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new StylePropertyEvent(styleProp, styleActor)); } } private class CustomPropertyChangeListener extends ChangeListener { private final CustomProperty styleProp; private final Actor styleActor; public CustomPropertyChangeListener(CustomProperty styleProp, Actor styleActor) { this.styleProp = styleProp; this.styleActor = styleActor; } @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { fire(new CustomPropertyEvent(styleProp, styleActor, CustomPropertyEnum.CHANGE_VALUE)); } } private void addPreviewPreviewPropertiesSplit(final Table right, InputListener scrollPaneListener) { Table bottom = new Table(); bottom.setTouchable(Touchable.enabled); addPreviewProperties(bottom, scrollPaneListener); Table top = new Table(); top.setTouchable(Touchable.enabled); addPreview(top, scrollPaneListener); SplitPane splitPane = new SplitPane(top, bottom, true, getSkin()); right.add(splitPane).grow(); splitPane.addListener(main.getVerticalResizeArrowListener()); } private void addPreview(Table top, InputListener scrollPaneListener) { Label label = new Label("Preview", getSkin(), "title"); top.add(label); top.row(); previewTable = new Table(getSkin()); previewTable.setBackground("white"); ScrollPane scrollPane = new ScrollPane(previewTable, getSkin()); scrollPane.setFadeScrollBars(false); scrollPane.setFlickScroll(false); scrollPane.addListener(scrollPaneListener); top.add(scrollPane).grow().padTop(10.0f).padBottom(10.0f); refreshPreview(); } private void addPreviewProperties(Table bottom, InputListener scrollPaneListener) { Label label = new Label("Preview Properties", getSkin(), "title"); bottom.add(label); bottom.row(); previewPropertiesTable = new Table(); previewPropertiesTable.defaults().pad(5.0f); ScrollPane scrollPane = new ScrollPane(previewPropertiesTable, getSkin()); scrollPane.setFadeScrollBars(false); scrollPane.setFlickScroll(false); scrollPane.addListener(scrollPaneListener); bottom.add(scrollPane).grow().padTop(10.0f).padBottom(10.0f); refreshPreviewProperties(); } public void refreshPreviewProperties() { if (previewPropertiesTable != null) { previewPropertiesTable.clear(); previewProperties.clear(); Table t = new Table(); previewPropertiesTable.add(t).grow(); t.defaults().pad(3.0f); if (previewBgColor == null) { previewBgColor.set(Color.WHITE); } previewProperties.put("bgcolor", previewBgColor); if (classSelectBox.getSelectedIndex() >= 0 && classSelectBox.getSelectedIndex() < Main.BASIC_CLASSES.length) { t.add(new Label("Stage Color: ", getSkin())).right(); BrowseField browseField = new BrowseField(null, null, getSkin(), "color"); browseField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { main.getDialogFactory().showDialogColorPicker((Color) previewProperties.get("bgcolor"), new DialogColorPicker.ColorListener() { @Override public void selected(Color color) { if (color != null) { browseField.getTextButton().setText((int) (color.r * 255) + "," + (int) (color.g * 255) + "," + (int) (color.b * 255) + "," + (int) (color.a * 255)); previewProperties.put("bgcolor", color); previewBgColor.set(color); refreshPreview(); } } }); } }); browseField.addListener(main.getHandListener()); t.add(browseField).growX(); browseField.getTextButton().setText((int) (previewBgColor.r * 255) + "," + (int) (previewBgColor.g * 255) + "," + (int) (previewBgColor.b * 255) + "," + (int) (previewBgColor.a * 255)); t.row(); t.add(new Label("Size: ", getSkin())).right(); previewSizeSelectBox = new SelectBox<>(getSkin()); previewSizeSelectBox.setItems(DEFAULT_SIZES); previewSizeSelectBox.setSelectedIndex(1); previewSizeSelectBox.addListener(main.getHandListener()); previewSizeSelectBox.getList().addListener(main.getHandListener()); t.add(previewSizeSelectBox).growX().minWidth(200.0f); Class clazz = Main.BASIC_CLASSES[classSelectBox.getSelectedIndex()]; if (clazz.equals(Button.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); } else if (clazz.equals(CheckBox.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(ImageButton.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); } else if (clazz.equals(ImageTextButton.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(Label.class)) { t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(List.class)) { t.row(); t.add(new Label("List Items: ", getSkin())).right(); TextArea listItemsTextArea = new TextArea("Lorem ipsum\ndolor sit\namet, consectetur", getSkin()); listItemsTextArea.setFocusTraversal(false); listItemsTextArea.setPrefRows(3); listItemsTextArea.addListener(main.getIbeamListener()); listItemsTextArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", listItemsTextArea.getText()); refreshPreview(); } }); previewProperties.put("text", listItemsTextArea.getText()); t.add(listItemsTextArea).growX(); } else if (clazz.equals(ProgressBar.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); disabledCheckBox.addListener(main.getHandListener()); previewProperties.put("disabled", disabledCheckBox.isChecked()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Value: ", getSkin())).right(); Spinner valueSpinner = new Spinner(0.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); valueSpinner.getTextField().setFocusTraversal(false); valueSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("value", valueSpinner.getValue()); refreshPreview(); } }); valueSpinner.getButtonMinus().addListener(main.getHandListener()); valueSpinner.getButtonPlus().addListener(main.getHandListener()); valueSpinner.getTextField().addListener(main.getIbeamListener()); previewProperties.put("value", valueSpinner.getValue()); t.add(valueSpinner).growX(); t.row(); t.add(new Label("Minimum: ", getSkin())).right(); Spinner minimumSpinner = new Spinner(0.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); minimumSpinner.getTextField().setFocusTraversal(false); minimumSpinner.getTextField().addListener(main.getIbeamListener()); minimumSpinner.getButtonMinus().addListener(main.getHandListener()); minimumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("minimum", minimumSpinner.getValue()); t.add(minimumSpinner).growX(); t.row(); t.add(new Label("Maximum: ", getSkin())).right(); Spinner maximumSpinner = new Spinner(100.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); maximumSpinner.getTextField().setFocusTraversal(false); maximumSpinner.getTextField().addListener(main.getIbeamListener()); maximumSpinner.getButtonMinus().addListener(main.getHandListener()); maximumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("maximum", maximumSpinner.getValue()); t.add(maximumSpinner).growX(); minimumSpinner.setMaximum(maximumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); minimumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("minimum", minimumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); refreshPreview(); } }); maximumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("maximum", maximumSpinner.getValue()); minimumSpinner.setMaximum(maximumSpinner.getValue()); refreshPreview(); } }); t.row(); t.add(new Label("Increment: ", getSkin())).right(); Spinner incrementSpinner = new Spinner(1.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); incrementSpinner.getTextField().setFocusTraversal(false); incrementSpinner.setMinimum(1); incrementSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("increment", incrementSpinner.getValue()); refreshPreview(); } }); incrementSpinner.getTextField().addListener(main.getIbeamListener()); incrementSpinner.getButtonMinus().addListener(main.getHandListener()); incrementSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("increment", incrementSpinner.getValue()); t.add(incrementSpinner).growX(); t.row(); t.add(new Label("Orientation: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Horizontal", "Vertical"}); if (getSelectedStyle().name.contains("vert")) { previewProperties.put("orientation", true); selectBox.setSelectedIndex(1); } else { previewProperties.put("orientation", false); } selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (selectBox.getSelectedIndex() == 0) { previewProperties.put("orientation", false); } else { previewProperties.put("orientation", true); } refreshPreview(); } }); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); t.add(selectBox).growX(); } else if (clazz.equals(ScrollPane.class)) { t.row(); t.add(new Label("Scrollbars On Top: ", getSkin())).right(); ImageTextButton onTopCheckBox = new ImageTextButton("", getSkin(), "switch"); onTopCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("scrollbarsOnTop", onTopCheckBox.isChecked()); refreshPreview(); } }); t.add(onTopCheckBox).left(); onTopCheckBox.addListener(main.getHandListener()); previewProperties.put("scrollbarsOnTop", onTopCheckBox.isChecked()); t.row(); t.add(new Label("H ScrollBar Position: ", getSkin())).right(); SelectBox<String> hScrollPosBox = new SelectBox<>(getSkin()); hScrollPosBox.setItems(new String[]{"Top", "Bottom"}); hScrollPosBox.setSelectedIndex(1); hScrollPosBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (hScrollPosBox.getSelectedIndex() == 0) { previewProperties.put("hScrollBarPosition", false); } else { previewProperties.put("hScrollBarPosition", true); } refreshPreview(); } }); t.add(hScrollPosBox).growX(); hScrollPosBox.addListener(main.getHandListener()); hScrollPosBox.getList().addListener(main.getHandListener()); previewProperties.put("hScrollBarPosition", true); t.row(); t.add(new Label("V ScrollBar Position: ", getSkin())).right(); SelectBox<String> vScrollPosBox = new SelectBox<>(getSkin()); vScrollPosBox.setItems(new String[]{"Left", "Right"}); vScrollPosBox.setSelectedIndex(1); vScrollPosBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (vScrollPosBox.getSelectedIndex() == 0) { previewProperties.put("vScrollBarPosition", false); } else { previewProperties.put("vScrollBarPosition", true); } refreshPreview(); } }); t.add(vScrollPosBox).growX(); vScrollPosBox.addListener(main.getHandListener()); vScrollPosBox.getList().addListener(main.getHandListener()); previewProperties.put("vScrollBarPosition", true); t.row(); t.add(new Label("H Scrolling Disabled: ", getSkin())).right(); ImageTextButton hScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); hScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("hScrollDisabled", hScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(hScrollCheckBox).left(); hScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("hScrollDisabled", hScrollCheckBox.isChecked()); t.row(); t.add(new Label("V Scrolling Disabled: ", getSkin())).right(); ImageTextButton vScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); vScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("vScrollDisabled", vScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(vScrollCheckBox).left(); vScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("vScrollDisabled", vScrollCheckBox.isChecked()); t.row(); t.add(new Label("Force H Scroll: ", getSkin())).right(); ImageTextButton forceHScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); forceHScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("forceHscroll", forceHScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(forceHScrollCheckBox).left(); forceHScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("forceHscroll", forceHScrollCheckBox.isChecked()); t.row(); t.add(new Label("Force V Scroll: ", getSkin())).right(); ImageTextButton forceVScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); forceVScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("forceVscroll", forceVScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(forceVScrollCheckBox).left(); forceVScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("forceVscroll", forceVScrollCheckBox.isChecked()); t.row(); t.add(new Label("Variable Size Knobs: ", getSkin())).right(); ImageTextButton variableSizeKnobsCheckBox = new ImageTextButton("", getSkin(), "switch"); variableSizeKnobsCheckBox.setChecked(true); variableSizeKnobsCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("variableSizeKnobs", variableSizeKnobsCheckBox.isChecked()); refreshPreview(); } }); t.add(variableSizeKnobsCheckBox).left(); variableSizeKnobsCheckBox.addListener(main.getHandListener()); previewProperties.put("variableSizeKnobs", variableSizeKnobsCheckBox.isChecked()); t.row(); t.add(new Label("H Overscroll: ", getSkin())).right(); ImageTextButton hOverscrollCheckBox = new ImageTextButton("", getSkin(), "switch"); hOverscrollCheckBox.setChecked(true); hOverscrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("hOverscroll", hOverscrollCheckBox.isChecked()); refreshPreview(); } }); t.add(hOverscrollCheckBox).left(); hOverscrollCheckBox.addListener(main.getHandListener()); previewProperties.put("hOverscroll", hOverscrollCheckBox.isChecked()); t.row(); t.add(new Label("V Overscroll: ", getSkin())).right(); ImageTextButton vOverscrollCheckBox = new ImageTextButton("", getSkin(), "switch"); vOverscrollCheckBox.setChecked(true); vOverscrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("vOverscroll", vOverscrollCheckBox.isChecked()); refreshPreview(); } }); t.add(vOverscrollCheckBox).left(); vOverscrollCheckBox.addListener(main.getHandListener()); previewProperties.put("vOverscroll", vOverscrollCheckBox.isChecked()); t.row(); t.add(new Label("Fade Scroll Bars: ", getSkin())).right(); ImageTextButton fadeScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); fadeScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("fadeScroll", fadeScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(fadeScrollCheckBox).left(); fadeScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("fadeScroll", fadeScrollCheckBox.isChecked()); t.row(); t.add(new Label("Smooth Scrolling: ", getSkin())).right(); ImageTextButton smoothScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); smoothScrollCheckBox.setChecked(true); smoothScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("smoothScroll", smoothScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(smoothScrollCheckBox).left(); smoothScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("smoothScroll", smoothScrollCheckBox.isChecked()); t.row(); t.add(new Label("Flick Scroll: ", getSkin())).right(); ImageTextButton flickScrollCheckBox = new ImageTextButton("", getSkin(), "switch"); flickScrollCheckBox.setChecked(true); flickScrollCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("flickScroll", flickScrollCheckBox.isChecked()); refreshPreview(); } }); t.add(flickScrollCheckBox).left(); flickScrollCheckBox.addListener(main.getHandListener()); previewProperties.put("flickScroll", flickScrollCheckBox.isChecked()); t.row(); t.add(new Label("Clamp: ", getSkin())).right(); ImageTextButton clampCheckBox = new ImageTextButton("", getSkin(), "switch"); clampCheckBox.setChecked(true); clampCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("clamp", clampCheckBox.isChecked()); refreshPreview(); } }); t.add(clampCheckBox).left(); clampCheckBox.addListener(main.getHandListener()); previewProperties.put("clamp", clampCheckBox.isChecked()); t.row(); t.add(new Label("Sample Text: ", getSkin())).right(); TextArea previewTextArea = new TextArea(PARAGRAPH_SAMPLE_EXT, getSkin()); previewTextArea.setFocusTraversal(false); previewTextArea.setPrefRows(5); previewTextArea.addListener(main.getIbeamListener()); previewTextArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextArea.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextArea.getText()); t.add(previewTextArea).growX(); previewSizeSelectBox.setSelectedIndex(2); } else if (clazz.equals(SelectBox.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Max List Count: ", getSkin())).right(); Spinner spinner = new Spinner(3, 1, true, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().setFocusTraversal(false); spinner.setMinimum(1); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); t.add(spinner).growX(); t.row(); t.add(new Label("List Items: ", getSkin())).right(); TextArea listItemsTextArea = new TextArea("Lorem ipsum\ndolor sit\namet, consectetur", getSkin()); listItemsTextArea.setFocusTraversal(false); listItemsTextArea.setPrefRows(3); listItemsTextArea.addListener(main.getIbeamListener()); listItemsTextArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", listItemsTextArea.getText()); refreshPreview(); } }); previewProperties.put("text", listItemsTextArea.getText()); t.add(listItemsTextArea).growX(); } else if (clazz.equals(Slider.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Minimum: ", getSkin())).right(); Spinner minimumSpinner = new Spinner(0.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); minimumSpinner.getTextField().setFocusTraversal(false); minimumSpinner.getTextField().addListener(main.getIbeamListener()); t.add(minimumSpinner).growX(); minimumSpinner.getButtonMinus().addListener(main.getHandListener()); minimumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("minimum", minimumSpinner.getValue()); t.row(); t.add(new Label("Maximum: ", getSkin())).right(); Spinner maximumSpinner = new Spinner(100.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); maximumSpinner.getTextField().setFocusTraversal(false); maximumSpinner.getTextField().addListener(main.getIbeamListener()); t.add(maximumSpinner).growX(); maximumSpinner.getButtonMinus().addListener(main.getHandListener()); maximumSpinner.getButtonPlus().addListener(main.getHandListener()); previewProperties.put("maximum", maximumSpinner.getValue()); minimumSpinner.setMaximum(maximumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); minimumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("minimum", minimumSpinner.getValue()); maximumSpinner.setMinimum(minimumSpinner.getValue()); refreshPreview(); } }); maximumSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("maximum", maximumSpinner.getValue()); minimumSpinner.setMaximum(maximumSpinner.getValue()); refreshPreview(); } }); t.row(); t.add(new Label("Increment: ", getSkin())).right(); Spinner incrementSpinner = new Spinner(1.0f, 1.0f, false, Spinner.Orientation.HORIZONTAL, getSkin()); incrementSpinner.getTextField().setFocusTraversal(false); incrementSpinner.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("increment", incrementSpinner.getValue()); refreshPreview(); } }); incrementSpinner.getTextField().addListener(main.getIbeamListener()); t.add(incrementSpinner).growX(); incrementSpinner.getButtonMinus().addListener(main.getHandListener()); incrementSpinner.getButtonPlus().addListener(main.getHandListener()); incrementSpinner.setMinimum(1.0f); previewProperties.put("increment", incrementSpinner.getValue()); t.row(); t.add(new Label("Orientation: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Horizontal", "Vertical"}); if (getSelectedStyle().name.contains("vert")) { previewProperties.put("orientation", true); selectBox.setSelectedIndex(1); } else { previewProperties.put("orientation", false); } selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (selectBox.getSelectedIndex() == 0) { previewProperties.put("orientation", false); } else { previewProperties.put("orientation", true); } refreshPreview(); } }); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); t.add(selectBox).growX(); } else if (clazz.equals(SplitPane.class)) { t.row(); t.add(new Label("Orientation: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Horizontal", "Vertical"}); if (getSelectedStyle().name.contains("vert")) { previewProperties.put("orientation", true); selectBox.setSelectedIndex(1); } else { previewProperties.put("orientation", false); } selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { if (selectBox.getSelectedIndex() == 0) { previewProperties.put("orientation", false); } else { previewProperties.put("orientation", true); } refreshPreview(); } }); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); t.add(selectBox).growX(); t.row(); t.add(new Label("Sample Text: ", getSkin())).right(); TextArea textArea = new TextArea(PARAGRAPH_SAMPLE, getSkin()); textArea.setFocusTraversal(false); textArea.setPrefRows(5); textArea.addListener(main.getIbeamListener()); textArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", textArea.getText()); refreshPreview(); } }); previewProperties.put("text", textArea.getText()); t.add(textArea).growX(); previewSizeSelectBox.setSelectedIndex(2); } else if (clazz.equals(TextButton.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(TextField.class)) { t.row(); t.add(new Label("Disabled: ", getSkin())).right(); ImageTextButton disabledCheckBox = new ImageTextButton("", getSkin(), "switch"); disabledCheckBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("disabled", disabledCheckBox.isChecked()); refreshPreview(); } }); previewProperties.put("disabled", disabledCheckBox.isChecked()); disabledCheckBox.addListener(main.getHandListener()); t.add(disabledCheckBox).left(); t.row(); t.add(new Label("Password Mode: ", getSkin())).right(); ImageTextButton checkBox = new ImageTextButton("", getSkin(), "switch"); checkBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("passwordMode", checkBox.isChecked()); refreshPreview(); } }); t.add(checkBox).left(); checkBox.addListener(main.getHandListener()); previewProperties.put("passwordMode", checkBox.isChecked()); t.row(); t.add(new Label("Password Character: ", getSkin())); TextField pcTextField = new TextField("*", getSkin()); pcTextField.setFocusTraversal(false); pcTextField.addListener(main.getIbeamListener()); pcTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("password", pcTextField.getText()); refreshPreview(); } }); previewProperties.put("password", pcTextField.getText()); t.add(pcTextField).growX(); t.row(); t.add(new Label("Text Alignment: ", getSkin())).right(); SelectBox<String> selectBox = new SelectBox<>(getSkin()); selectBox.setItems(new String[]{"Left", "Center", "Right"}); selectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { switch (selectBox.getSelectedIndex()) { case 0: previewProperties.put("alignment", Align.left); break; case 1: previewProperties.put("alignment", Align.center); break; case 2: previewProperties.put("alignment", Align.right); break; } refreshPreview(); } }); t.add(selectBox).growX(); selectBox.addListener(main.getHandListener()); selectBox.getList().addListener(main.getHandListener()); previewProperties.put("alignment", Align.left); t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); t.row(); t.add(new Label("Message Text: ", getSkin())).right(); TextField messageTextField = new TextField(TEXT_SAMPLE, getSkin()); messageTextField.setFocusTraversal(false); messageTextField.addListener(main.getIbeamListener()); messageTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("message", messageTextField.getText()); refreshPreview(); } }); previewProperties.put("message", messageTextField.getText()); t.add(messageTextField).growX(); } else if (clazz.equals(TextTooltip.class)) { t.row(); t.add(new Label("Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("text", previewTextField.getText()); t.add(previewTextField).growX(); } else if (clazz.equals(Touchpad.class)) { } else if (clazz.equals(Tree.class)) { t.row(); t.add(new Label("Icon Spacing: ", getSkin())).right(); Spinner spinner = new Spinner(0.0, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().setFocusTraversal(false); spinner.setMinimum(1); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); t.add(spinner).growX(); t.row(); t.add(new Label("Y Spacing: ", getSkin())).right(); spinner = new Spinner(0.0, 1.0, false, Spinner.Orientation.HORIZONTAL, getSkin()); spinner.getTextField().setFocusTraversal(false); spinner.setMinimum(1); spinner.getTextField().addListener(main.getIbeamListener()); spinner.getButtonMinus().addListener(main.getHandListener()); spinner.getButtonPlus().addListener(main.getHandListener()); t.add(spinner).growX(); } else if (clazz.equals(Window.class)) { t.row(); t.add(new Label("Title Text: ", getSkin())).right(); TextField previewTextField = new TextField(TEXT_SAMPLE, getSkin()); previewTextField.setFocusTraversal(false); previewTextField.addListener(main.getIbeamListener()); previewTextField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("title", previewTextField.getText()); refreshPreview(); } }); previewProperties.put("title", previewTextField.getText()); t.add(previewTextField).growX(); t.row(); t.add(new Label("Sample Text Color: ", getSkin())); BrowseField textColorField = new BrowseField(null, null, getSkin(), "color"); textColorField.addListener(main.getHandListener()); t.add(textColorField).growX(); t.row(); t.add(new Label("Sample Text: ", getSkin())).right(); TextArea textArea = new TextArea(PARAGRAPH_SAMPLE, getSkin()); textArea.setFocusTraversal(false); textArea.setPrefRows(5); textArea.addListener(main.getIbeamListener()); textArea.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("text", textArea.getText()); refreshPreview(); } }); previewProperties.put("text", textArea.getText()); t.add(textArea).growX(); } previewSizeSelectBox.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { previewProperties.put("size", previewSizeSelectBox.getSelectedIndex()); if (previewSizeSelectBox.getSelectedIndex() != 7) { refreshPreview(); } } }); previewProperties.put("size", previewSizeSelectBox.getSelectedIndex()); refreshPreview(); } else { t.add(new Label("Stage Color: ", getSkin())).right(); BrowseField browseField = new BrowseField(null, null, getSkin(), "color"); browseField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { main.getDialogFactory().showDialogColorPicker((Color) previewProperties.get("bgcolor"), new DialogColorPicker.ColorListener() { @Override public void selected(Color color) { if (color != null) { browseField.getTextButton().setText((int) (color.r * 255) + "," + (int) (color.g * 255) + "," + (int) (color.b * 255) + "," + (int) (color.a * 255)); previewProperties.put("bgcolor", color); previewBgColor.set(color); refreshPreview(); } } }); } }); browseField.addListener(main.getHandListener()); t.add(browseField).growX(); browseField.getTextButton().setText((int) (previewBgColor.r * 255) + "," + (int) (previewBgColor.g * 255) + "," + (int) (previewBgColor.b * 255) + "," + (int) (previewBgColor.a * 255)); } } } public void refreshPreview() { if (previewTable != null) { previewTable.clear(); previewTable.setBackground("white"); previewTable.setColor((Color) previewProperties.get("bgcolor")); for (BitmapFont font : previewFonts) { font.dispose(); } if (classSelectBox.getSelectedIndex() >= 0 && classSelectBox.getSelectedIndex() < Main.BASIC_CLASSES.length) { StyleData styleData = getSelectedStyle(); Class clazz = Main.BASIC_CLASSES[classSelectBox.getSelectedIndex()]; if (!styleData.hasMandatoryFields()) { Label label; if (clazz.equals(SelectBox.class)) { label = new Label("Please fill all mandatory fields\n(Highlighted on the left)\n\nscrollStyle and listStyle\nmust already be defined", getSkin()); } else if (clazz.equals(TextTooltip.class)) { label = new Label("Please fill all mandatory fields\n(Highlighted on the left)\n\nlabel must already be defined", getSkin()); } else { label = new Label("Please fill all mandatory fields\n(Highlighted on the left)", getSkin()); } label.setAlignment(Align.center); previewTable.add(label); } else if (styleData.hasAllNullFields()) { Label label; label = new Label("All fields are empty!\nEmpty classes are not exported\nAdd style properties in the menu to the left", getSkin()); label.setAlignment(Align.center); previewTable.add(label); } else { Actor widget = null; if (clazz.equals(Button.class)) { Button.ButtonStyle style = createPreviewStyle(Button.ButtonStyle.class, styleData); widget = new Button(style); ((Button)widget).setDisabled((boolean) previewProperties.get("disabled")); widget.addListener(main.getHandListener()); } else if (clazz.equals(CheckBox.class)) { CheckBox.CheckBoxStyle style = createPreviewStyle(CheckBox.CheckBoxStyle.class, styleData); widget = new CheckBox("", style); ((CheckBox)widget).setDisabled((boolean) previewProperties.get("disabled")); ((CheckBox)widget).setText((String) previewProperties.get("text")); widget.addListener(main.getHandListener()); } else if (clazz.equals(ImageButton.class)) { ImageButtonStyle style = createPreviewStyle(ImageButtonStyle.class, styleData); widget = new ImageButton(style); ((ImageButton)widget).setDisabled((boolean) previewProperties.get("disabled")); widget.addListener(main.getHandListener()); } else if (clazz.equals(ImageTextButton.class)) { ImageTextButton.ImageTextButtonStyle style = createPreviewStyle(ImageTextButton.ImageTextButtonStyle.class, styleData); widget = new ImageTextButton("", style); ((ImageTextButton)widget).setDisabled((boolean) previewProperties.get("disabled")); ((ImageTextButton)widget).setText((String) previewProperties.get("text")); widget.addListener(main.getHandListener()); } else if (clazz.equals(Label.class)) { LabelStyle style = createPreviewStyle(LabelStyle.class, styleData); widget = new Label("", style); ((Label)widget).setText((String) previewProperties.get("text")); } else if (clazz.equals(List.class)) { ListStyle style = createPreviewStyle(ListStyle.class, styleData); widget = new List(style); Array<String> items = new Array<>(((String) previewProperties.get("text")).split("\\n")); ((List)widget).setItems(items); widget.addListener(main.getHandListener()); } else if (clazz.equals(ProgressBar.class)) { ProgressBar.ProgressBarStyle style = createPreviewStyle(ProgressBar.ProgressBarStyle.class, styleData); widget = new ProgressBar((float) (double) previewProperties.get("minimum"), (float) (double) previewProperties.get("maximum"), (float) (double) previewProperties.get("increment"), (boolean) previewProperties.get("orientation"), style); ((ProgressBar) widget).setValue((float) (double) previewProperties.get("value")); ((ProgressBar)widget).setDisabled((boolean) previewProperties.get("disabled")); } else if (clazz.equals(ScrollPane.class)) { ScrollPaneStyle style = createPreviewStyle(ScrollPaneStyle.class, styleData); Label label = new Label("", getSkin()); widget = new ScrollPane(label, style); ((ScrollPane) widget).setScrollbarsOnTop((boolean) previewProperties.get("scrollbarsOnTop")); ((ScrollPane) widget).setScrollBarPositions((boolean) previewProperties.get("hScrollBarPosition"), (boolean) previewProperties.get("vScrollBarPosition")); ((ScrollPane) widget).setScrollingDisabled((boolean) previewProperties.get("hScrollDisabled"), (boolean) previewProperties.get("vScrollDisabled")); ((ScrollPane) widget).setForceScroll((boolean) previewProperties.get("forceHscroll"), (boolean) previewProperties.get("forceVscroll")); ((ScrollPane) widget).setVariableSizeKnobs((boolean) previewProperties.get("variableSizeKnobs")); ((ScrollPane) widget).setOverscroll((boolean) previewProperties.get("hOverscroll"), (boolean) previewProperties.get("vOverscroll")); ((ScrollPane) widget).setFadeScrollBars((boolean) previewProperties.get("fadeScroll")); ((ScrollPane) widget).setSmoothScrolling((boolean) previewProperties.get("smoothScroll")); ((ScrollPane) widget).setFlickScroll((boolean) previewProperties.get("flickScroll")); ((ScrollPane) widget).setClamp((boolean) previewProperties.get("clamp")); label.setText((String) previewProperties.get("text")); } else if (clazz.equals(SelectBox.class)) { SelectBox.SelectBoxStyle style = createPreviewStyle(SelectBox.SelectBoxStyle.class, styleData); widget = new SelectBox(style); ((SelectBox)widget).setDisabled((boolean) previewProperties.get("disabled")); Array<String> items = new Array<>(((String) previewProperties.get("text")).split("\\n")); ((SelectBox)widget).setItems(items); widget.addListener(main.getHandListener()); ((SelectBox)widget).getList().addListener(main.getHandListener()); } else if (clazz.equals(Slider.class)) { Slider.SliderStyle style = createPreviewStyle(Slider.SliderStyle.class, styleData); widget = new Slider((float) (double) previewProperties.get("minimum"), (float) (double) previewProperties.get("maximum"), (float) (double) previewProperties.get("increment"), (boolean) previewProperties.get("orientation"), style); ((Slider)widget).setDisabled((boolean) previewProperties.get("disabled")); widget.addListener(main.getHandListener()); } else if (clazz.equals(SplitPane.class)) { SplitPane.SplitPaneStyle style = createPreviewStyle(SplitPane.SplitPaneStyle.class, styleData); Label label1 = new Label("", getSkin()); Label label2 = new Label("", getSkin()); widget = new SplitPane(label1, label2, (boolean) previewProperties.get("orientation"), style); label1.setText((String) previewProperties.get("text")); label2.setText((String) previewProperties.get("text")); if ((boolean) previewProperties.get("orientation")) { widget.addListener(main.getVerticalResizeArrowListener()); } else { widget.addListener(main.getHorizontalResizeArrowListener()); } } else if (clazz.equals(TextButton.class)) { TextButtonStyle style = createPreviewStyle(TextButtonStyle.class, styleData); widget = new TextButton("", style); ((TextButton)widget).setDisabled((boolean) previewProperties.get("disabled")); ((TextButton)widget).setText((String) previewProperties.get("text")); widget.addListener(main.getHandListener()); } else if (clazz.equals(TextField.class)) { TextFieldStyle style = createPreviewStyle(TextFieldStyle.class, styleData); widget = new TextField("", style); ((TextField)widget).setFocusTraversal(false); ((TextField)widget).setDisabled((boolean) previewProperties.get("disabled")); ((TextField)widget).setPasswordMode((boolean) previewProperties.get("passwordMode")); ((TextField)widget).setAlignment((int) previewProperties.get("alignment")); ((TextField)widget).setText((String) previewProperties.get("text")); ((TextField)widget).setMessageText((String) previewProperties.get("message")); String string = (String) previewProperties.get("password"); if (string.length() > 0) { ((TextField)widget).setPasswordCharacter(string.charAt(0)); } widget.addListener(main.getIbeamListener()); } else if (clazz.equals(TextTooltip.class)) { TextTooltip.TextTooltipStyle style = createPreviewStyle(TextTooltip.TextTooltipStyle.class, styleData); TooltipManager manager = new TooltipManager(); manager.animations = false; manager.initialTime = 0.0f; manager.resetTime = 0.0f; manager.subsequentTime = 0.0f; manager.hideAll(); manager.instant(); TextTooltip toolTip = new TextTooltip((String) previewProperties.get("text"), manager, style); widget = new Label("Hover over me", getSkin()); widget.addListener(toolTip); } else if (clazz.equals(Touchpad.class)) { Touchpad.TouchpadStyle style = createPreviewStyle(Touchpad.TouchpadStyle.class, styleData); widget = new Touchpad(0, style); widget.addListener(main.getHandListener()); } else if (clazz.equals(Tree.class)) { Tree.TreeStyle style = createPreviewStyle(Tree.TreeStyle.class, styleData); widget = new Tree(style); String[] lines = {"this", "is", "a", "test"}; Tree.Node parentNode = null; for (String line: lines) { Label label = new Label(line, getSkin()); Tree.Node node = new Tree.Node(label); if (parentNode == null) { ((Tree) widget).add(node); } else { parentNode.add(node); } parentNode = node; } widget.addListener(main.getHandListener()); } else if (clazz.equals(Window.class)) { Window.WindowStyle style = createPreviewStyle(Window.WindowStyle.class, styleData); if (style.stageBackground != null) { previewTable.setBackground(style.stageBackground); previewTable.setColor(Color.WHITE); style.stageBackground = null; } Label sampleText = new Label("", getSkin()); sampleText.setText((String) previewProperties.get("text")); widget = new Window((String) previewProperties.get("title"), style); ((Window)widget).add(sampleText); } if (widget != null) { switch ((int) previewProperties.get("size")) { case (0): previewTable.add(widget).size(10.0f); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (1): previewTable.add(widget); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (2): previewTable.add(widget).size(200.0f); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (3): previewTable.add(widget).growX(); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (4): previewTable.add(widget).growY(); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (5): previewTable.add(widget).grow(); previewSizeSelectBox.setItems(DEFAULT_SIZES); break; case (6): Actor addWidget = widget; TraversalTextField widthField = new TraversalTextField("", getSkin()); TraversalTextField heightField = new TraversalTextField("", getSkin()); widthField.setNextFocus(heightField); heightField.setNextFocus(widthField); Dialog dialog = new Dialog("Enter dimensions...", getSkin()) { @Override protected void result(Object object) { if ((boolean)object) { previewTable.add(addWidget).size(Integer.parseInt(widthField.getText()), Integer.parseInt(heightField.getText())); Array<String> items = new Array<>(DEFAULT_SIZES); items.add(widthField.getText() + "x" + heightField.getText()); previewProperties.put("sizeX", Integer.parseInt(widthField.getText())); previewProperties.put("sizeY", Integer.parseInt(heightField.getText())); previewSizeSelectBox.setItems(items); previewSizeSelectBox.setSelectedIndex(7); } else { previewSizeSelectBox.setSelectedIndex(1); } } }; dialog.getTitleTable().getCells().first().padLeft(5.0f); dialog.text("Enter the preview dimensions: "); dialog.getContentTable().getCells().first().pad(10.0f); dialog.getContentTable().row(); Table sizeTable = new Table(); sizeTable.add(widthField).padLeft(10.0f); sizeTable.add(new Label(" x ", getSkin())); sizeTable.add(heightField).padRight(10.0f); dialog.getContentTable().add(sizeTable); dialog.getButtonTable().defaults().padBottom(10.0f).minWidth(50.0f); dialog.button("OK", true); dialog.button("Cancel", false); TextButton okButton = (TextButton) dialog.getButtonTable().getCells().first().getActor(); okButton.setDisabled(true); okButton.addListener(main.getHandListener()); widthField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { okButton.setDisabled(!widthField.getText().matches("^\\d+$") || !heightField.getText().matches("^\\d+$")); } }); heightField.addListener(new ChangeListener() { @Override public void changed(ChangeListener.ChangeEvent event, Actor actor) { okButton.setDisabled(!widthField.getText().matches("^\\d+$") || !heightField.getText().matches("^\\d+$")); } }); dialog.getButtonTable().getCells().get(1).getActor().addListener(main.getHandListener()); dialog.key(Input.Keys.ESCAPE, false); dialog.show(stage); stage.setKeyboardFocus(widthField); break; case (7): previewTable.add(widget).size((int) previewProperties.get("sizeX"), (int) previewProperties.get("sizeY")); break; } } } } else { CustomStyle customStyle = (CustomStyle) styleSelectBox.getSelected(); boolean showMessage = true; if (customStyle.getProperties().size == 0) { Label label = new Label("No style properties!\nEmpty classes are not exported\nAdd style properties in the menu to the left", getSkin()); label.setAlignment(0); previewTable.add(label); } else { for (CustomProperty customProperty : customStyle.getProperties()) { if (customProperty.getValue() != null && !(customProperty.getValue() instanceof String) || customProperty.getValue() != null && !((String)customProperty.getValue()).equals("")) { showMessage = false; break; } } if (showMessage) { Label label = new Label("All properties are empty!\nEmpty classes are not exported\nAdd style properties in the menu to the left", getSkin()); label.setAlignment(0); previewTable.add(label); } } if (!showMessage) { HorizontalGroup horizontalGroup = new HorizontalGroup(); horizontalGroup.wrap(); //the following causes a crash. LibGDX bug. // horizontalGroup.space(10.0f); horizontalGroup.wrapSpace(10.0f); horizontalGroup.setTouchable(Touchable.disabled); previewTable.add(horizontalGroup).grow().pad(10.0f); for (CustomProperty customProperty : customStyle.getProperties()) { if (customProperty.getValue() != null) { Container container = new Container(); container.pad(5.0f); horizontalGroup.addActor(container); switch (customProperty.getType()) { case TEXT: case RAW_TEXT: Label labelText = new Label((String) customProperty.getValue(), getSkin()); container.setActor(labelText); break; case NUMBER: Label labelNumber = new Label(Double.toString((double) customProperty.getValue()), getSkin()); container.setActor(labelNumber); break; case BOOL: Label labelBoolean = new Label(Boolean.toString((boolean) customProperty.getValue()), getSkin()); container.setActor(labelBoolean); break; case COLOR: ColorData colorData = null; String colorName = (String) customProperty.getValue(); for (ColorData cd : main.getJsonData().getColors()) { if (cd.getName().equals(colorName)) { colorData = cd; break; } } if (colorData != null) { Table colorTable = new Table(getSkin()); colorTable.setBackground("white"); colorTable.setColor(colorData.color); colorTable.add().size(25.0f); container.setActor(colorTable); } break; case FONT: BitmapFont font = null; FontData fontData = null; String fontName = (String) customProperty.getValue(); for (FontData fd : main.getJsonData().getFonts()) { if (fd.getName().equals(fontName)) { fontData = fd; font = new BitmapFont(fd.file); previewFonts.add(font); break; } } if (font != null) { Label labelFont = new Label(fontData.getName(), new LabelStyle(font, Color.WHITE)); container.setActor(labelFont); } FreeTypeFontData freeTypeFontData = null; for (FreeTypeFontData fd : main.getJsonData().getFreeTypeFonts()) { if (fd.name.equals(fontName)) { freeTypeFontData = fd; break; } } if (freeTypeFontData != null && freeTypeFontData.bitmapFont != null) { Label labelFont = new Label(freeTypeFontData.name, new LabelStyle(freeTypeFontData.bitmapFont, Color.WHITE)); container.setActor(labelFont); } break; case DRAWABLE: DrawableData drawable = null; String drawableName = (String) customProperty.getValue(); for (DrawableData dd : main.getAtlasData().getDrawables()) { if (dd.name.equals(drawableName)) { drawable = dd; break; } } if (drawable != null) { Image image = new Image(drawablePairs.get(drawable.name)); container.setActor(image); } break; } } } } } } } private <T> T createPreviewStyle(Class<T> clazz, StyleData styleData) { T returnValue = null; try { returnValue = ClassReflection.newInstance(clazz); Field[] fields = ClassReflection.getFields(clazz); for (Field field : fields) { Object value = styleData.properties.get(field.getName()).value; if (value != null) { if (field.getType().equals(Drawable.class)) { field.set(returnValue, drawablePairs.get((String) value)); } else if (field.getType().equals(Color.class)) { for (ColorData data : main.getProjectData().getJsonData().getColors()) { if (value.equals(data.getName())) { field.set(returnValue, data.color); break; } } } else if (field.getType().equals(BitmapFont.class)) { for (FontData data : main.getProjectData().getJsonData().getFonts()) { if (value.equals(data.getName())) { BitmapFont font = new BitmapFont(data.file); previewFonts.add(font); field.set(returnValue, font); } } for (FreeTypeFontData data : main.getJsonData().getFreeTypeFonts()) { if (value.equals(data.name)) { field.set(returnValue, data.bitmapFont); } } } else if (field.getType().equals(Float.TYPE)) { field.set(returnValue, (float) value); } else if (field.getType().equals(ListStyle.class)) { Array<StyleData> datas = main.getProjectData().getJsonData().getClassStyleMap().get(List.class); for (StyleData data : datas) { if (value.equals(data.name)) { ListStyle style = createPreviewStyle(ListStyle.class, data); field.set(returnValue, style); break; } } } else if (field.getType().equals(ScrollPaneStyle.class)) { Array<StyleData> datas = main.getProjectData().getJsonData().getClassStyleMap().get(ScrollPane.class); for (StyleData data : datas) { if (value.equals(data.name)) { ScrollPaneStyle style = createPreviewStyle(ScrollPaneStyle.class, data); field.set(returnValue, style); break; } } } else if (field.getType().equals(LabelStyle.class)) { Array<StyleData> datas = main.getProjectData().getJsonData().getClassStyleMap().get(Label.class); for (StyleData data : datas) { if (value.equals(data.name)) { LabelStyle style = createPreviewStyle(LabelStyle.class, data); field.set(returnValue, style); break; } } } } } } finally { return returnValue; } } /** * Writes a TextureAtlas based on drawables list. Creates drawables to be * displayed on screen * @return */ public boolean produceAtlas() { try { if (atlas != null) { atlas.dispose(); atlas = null; } if (!main.getProjectData().getAtlasData().atlasCurrent) { main.getProjectData().getAtlasData().writeAtlas(); main.getProjectData().getAtlasData().atlasCurrent = true; } atlas = main.getProjectData().getAtlasData().getAtlas(); for (DrawableData data : main.getProjectData().getAtlasData().getDrawables()) { Drawable drawable; if (data.customized) { drawable = getSkin().getDrawable("custom-drawable-skincomposer-image"); } else if (data.tiled) { String name = data.file.name(); name = DrawableData.proper(name); drawable = new TiledDrawable(atlas.findRegion(name)); drawable.setMinWidth(data.minWidth); drawable.setMinHeight(data.minHeight); ((TiledDrawable) drawable).getColor().set(main.getJsonData().getColorByName(data.tintName).color); } else if (data.file.name().matches(".*\\.9\\.[a-zA-Z0-9]*$")) { String name = data.file.name(); name = DrawableData.proper(name); drawable = new NinePatchDrawable(atlas.createPatch(name)); if (data.tint != null) { drawable = ((NinePatchDrawable) drawable).tint(data.tint); } else if (data.tintName != null) { drawable = ((NinePatchDrawable) drawable).tint(main.getProjectData().getJsonData().getColorByName(data.tintName).color); } } else { String name = data.file.name(); name = DrawableData.proper(name); drawable = new SpriteDrawable(atlas.createSprite(name)); if (data.tint != null) { drawable = ((SpriteDrawable) drawable).tint(data.tint); } else if (data.tintName != null) { drawable = ((SpriteDrawable) drawable).tint(main.getProjectData().getJsonData().getColorByName(data.tintName).color); } } drawablePairs.put(data.name, drawable); } return true; } catch (Exception e) { Gdx.app.error(getClass().getName(), "Error while attempting to generate drawables.", e); main.getDialogFactory().showDialogError("Atlas Error...", "Error while attempting to generate drawables.\n\nOpen log?"); return false; } } private void addStatusBar() { Table table = new Table(); table.setBackground(getSkin().getDrawable("status-bar")); add(table).growX(); statusLabel = new Label("", getSkin()); statusLabel.setColor(1.0f, 1.0f, 1.0f, 0.0f); table.add(statusLabel).padLeft(10.0f); Label label = new Label("ver. " + Main.VERSION + " RAY3K.WORDPRESS.COM © 2018 Raymond \"Raeleus\" Buckley", getSkin()); table.add(label).expandX().right().padRight(25.0f); } private void display(final String text) { SequenceAction sequenceAction = new SequenceAction(); if (statusLabel.isVisible()) { statusLabel.clearActions(); AlphaAction alphaAction = new AlphaAction(); alphaAction.setAlpha(0.0f); alphaAction.setDuration(.25f); sequenceAction.addAction(alphaAction); RunnableAction runnableAction = new RunnableAction(); runnableAction.setRunnable(() -> { statusLabel.setText(text); }); sequenceAction.addAction(runnableAction); alphaAction = new AlphaAction(); alphaAction.setAlpha(1.0f); alphaAction.setDuration(.25f); sequenceAction.addAction(alphaAction); DelayAction delayAction = new DelayAction(); delayAction.setDuration(3.0f); sequenceAction.addAction(delayAction); alphaAction = new AlphaAction(); alphaAction.setAlpha(0.0f); alphaAction.setDuration(1.5f); sequenceAction.addAction(alphaAction); VisibleAction visibleAction = new VisibleAction(); visibleAction.setVisible(false); sequenceAction.addAction(visibleAction); } else { statusLabel.setText(text); statusLabel.clearActions(); statusLabel.setVisible(true); AlphaAction alphaAction = new AlphaAction(); alphaAction.setAlpha(1.0f); alphaAction.setDuration(.5f); sequenceAction.addAction(alphaAction); DelayAction delayAction = new DelayAction(); delayAction.setDuration(3.0f); sequenceAction.addAction(delayAction); alphaAction = new AlphaAction(); alphaAction.setAlpha(0.0f); alphaAction.setDuration(1.5f); sequenceAction.addAction(alphaAction); VisibleAction visibleAction = new VisibleAction(); visibleAction.setVisible(false); sequenceAction.addAction(visibleAction); } statusLabel.addAction(sequenceAction); } public void setStatusBarMessage(String text) { statusLabel.setColor(new Color(1.0f, 1.0f, 1.0f, statusLabel.getColor().a)); display(text); } public void setStatusBarError(String text) { statusLabel.setColor(new Color(1.0f, 0.0f, 0.0f, statusLabel.getColor().a)); display(text); } public SelectBox getClassSelectBox() { return classSelectBox; } public SelectBox getStyleSelectBox() { return styleSelectBox; } public Class getSelectedClass() { return Main.BASIC_CLASSES[classSelectBox.getSelectedIndex()]; } public StyleData getSelectedStyle() { OrderedMap<Class, Array<StyleData>> classStyleMap = main.getProjectData().getJsonData().getClassStyleMap(); return classStyleMap.get(getSelectedClass()).get(styleSelectBox.getSelectedIndex()); } public void setStyleProperties(Array<StyleProperty> styleProperties) { this.styleProperties = styleProperties; customProperties = null; } public void setCustomStyleProperties(Array<CustomProperty> styleProperties) { this.styleProperties = null; customProperties = styleProperties; } private class ScrollPaneListener extends InputListener { @Override public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) { if (event.getTarget() instanceof ScrollPane) { ScrollPane scrollPane = (ScrollPane) event.getTarget(); //if the scroll pane is scrollable if (!Float.isNaN(scrollPane.getScrollPercentY())) { stage.setScrollFocus(scrollPane); } } } } private class MenuBarListener extends MenuButtonListener { private final MenuButton<MenuItem> menuButton; public MenuBarListener(MenuButton<MenuItem> menuButton) { this.menuButton = menuButton; } @Override public void menuClicked() { fire(new RootTableEvent(menuButton.getSelectedItem().event)); } } private static class MenuItem { String text; RootTableEnum event; public MenuItem(String text, RootTableEnum enumeration) { this.text = text; this.event = enumeration; } @Override public String toString() { return text; } } public static enum RootTableEnum { NEW, OPEN, RECENT_FILES, SAVE, SAVE_AS, IMPORT, EXPORT, EXIT, UNDO, REDO, SETTINGS, COLORS, FONTS, DRAWABLES, ABOUT, CLASS_SELECTED, NEW_CLASS, DUPLICATE_CLASS, DELETE_CLASS, RENAME_CLASS, STYLE_SELECTED, NEW_STYLE, DUPLICATE_STYLE, DELETE_STYLE, RENAME_STYLE, PREVIEW_PROPERTY, WELCOME, REFRESH_ATLAS, DOWNLOAD_UPDATE, CHECK_FOR_UPDATES_COMPLETE; } public static class RootTableEvent extends Event { public RootTableEnum rootTableEnum; public RootTableEvent(RootTableEnum rootTableEnum) { this.rootTableEnum = rootTableEnum; } } private static class LoadClassesEvent extends Event { SelectBox classSelectBox; public LoadClassesEvent(SelectBox classSelectBox) { this.classSelectBox = classSelectBox; } } private static class LoadStylesEvent extends Event { SelectBox classSelectBox; SelectBox styleSelectBox; public LoadStylesEvent(SelectBox classSelectBox, SelectBox styleSelectBox) { this.classSelectBox = classSelectBox; this.styleSelectBox = styleSelectBox; } } private static class StylePropertyEvent extends Event { StyleProperty styleProperty; Actor styleActor; public StylePropertyEvent(StyleProperty styleProperty, Actor styleActor) { this.styleProperty = styleProperty; this.styleActor = styleActor; } } private static enum CustomPropertyEnum { NEW, DUPLICATE, DELETE, RENAME, CHANGE_VALUE; } private static class CustomPropertyEvent extends Event { private CustomProperty customProperty; private CustomPropertyEnum customPropertyEnum; private Actor styleActor; public CustomPropertyEvent(CustomProperty customProperty, Actor styleActor, CustomPropertyEnum customPropertyEnum) { this.customProperty = customProperty; this.customPropertyEnum = customPropertyEnum; this.styleActor = styleActor; } } public static abstract class RootTableListener implements EventListener { @Override public boolean handle(Event event) { if (event instanceof RootTableEvent) { rootEvent((RootTableEvent) event); } else if (event instanceof LoadClassesEvent) { loadClasses(((LoadClassesEvent) event).classSelectBox); } else if (event instanceof LoadStylesEvent) { loadStyles(((LoadStylesEvent) event).classSelectBox, ((LoadStylesEvent) event).styleSelectBox); } else if (event instanceof StylePropertyEvent) { stylePropertyChanged(((StylePropertyEvent) event).styleProperty, ((StylePropertyEvent) event).styleActor); } else if (event instanceof CustomPropertyEvent) { CustomPropertyEvent propertyEvent = (CustomPropertyEvent) event; if (null != propertyEvent.customPropertyEnum) switch (propertyEvent.customPropertyEnum) { case NEW: newCustomProperty(); break; case DELETE: deleteCustomProperty(propertyEvent.customProperty); break; case RENAME: renameCustomProperty(propertyEvent.customProperty); break; case DUPLICATE: duplicateCustomProperty(propertyEvent.customProperty); break; case CHANGE_VALUE: customPropertyValueChanged(propertyEvent.customProperty, propertyEvent.styleActor); break; default: break; } } return false; } public abstract void rootEvent(RootTableEvent event); public abstract void stylePropertyChanged(StyleProperty styleProperty, Actor styleActor); public abstract void loadClasses(SelectBox classSelectBox); public abstract void loadStyles(SelectBox classSelectBox, SelectBox styleSelectBox); public abstract void newCustomProperty(); public abstract void duplicateCustomProperty(CustomProperty customProperty); public abstract void deleteCustomProperty(CustomProperty customProperty); public abstract void customPropertyValueChanged(CustomProperty customProperty, Actor styleActor); public abstract void renameCustomProperty(CustomProperty customProperty); } public static class ShortcutListener extends InputListener { private final RootTable rootTable; public ShortcutListener(RootTable rootTable) { this.rootTable = rootTable; } @Override public boolean keyDown(InputEvent event, int keycode) { boolean listenForShortcuts = true; for (Actor actor : rootTable.getStage().getActors()) { if (actor instanceof Dialog) { listenForShortcuts = false; break; } } //trigger shortcuts only if no dialogs are open. if (listenForShortcuts) { if (Gdx.input.isKeyPressed(Input.Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Input.Keys.CONTROL_RIGHT)) { char character = rootTable.main.getDesktopWorker().getKeyName(keycode); switch (character) { case 'z': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.UNDO)); break; case 'y': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.REDO)); break; case 'n': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.NEW)); break; case 'o': rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.OPEN)); break; case 's': if (Gdx.input.isKeyPressed(Input.Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Input.Keys.SHIFT_RIGHT)) { rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.SAVE_AS)); } else { rootTable.fire(new RootTable.RootTableEvent(RootTable.RootTableEnum.SAVE)); } break; case 'e': rootTable.fire(new RootTable.RootTableEvent(RootTableEnum.EXPORT)); break; default: break; } } switch (keycode) { case Input.Keys.F5: rootTable.fire(new RootTable.RootTableEvent(RootTableEnum.REFRESH_ATLAS)); break; } } return false; } } public ObjectMap<String, Drawable> getDrawablePairs() { return drawablePairs; } }
Added missing hand listener.
core/src/com/ray3k/skincomposer/RootTable.java
Added missing hand listener.
<ide><path>ore/src/com/ray3k/skincomposer/RootTable.java <ide> <ide> TextTooltip toolTip = new TextTooltip("New Style Property", main.getTooltipManager(), getSkin()); <ide> button.addListener(toolTip); <add> button.addListener(main.getHandListener()); <ide> } <ide> } <ide>
Java
apache-2.0
9111602d7c2a88b7f9db6772d7d6d8399e2ff96b
0
grpc/grpc-java,stanley-cheung/grpc-java,dapengzhang0/grpc-java,grpc/grpc-java,stanley-cheung/grpc-java,carl-mastrangelo/grpc-java,dapengzhang0/grpc-java,stanley-cheung/grpc-java,dapengzhang0/grpc-java,ejona86/grpc-java,ejona86/grpc-java,stanley-cheung/grpc-java,carl-mastrangelo/grpc-java,carl-mastrangelo/grpc-java,grpc/grpc-java,ejona86/grpc-java,dapengzhang0/grpc-java,carl-mastrangelo/grpc-java,grpc/grpc-java,ejona86/grpc-java
/* * Copyright 2015 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.stub; import com.google.common.base.Preconditions; import io.grpc.ExperimentalApi; import java.util.Iterator; /** * Utility functions for working with {@link StreamObserver} and it's common subclasses like * {@link CallStreamObserver}. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4694") public final class StreamObservers { /** * Copy the values of an {@link Iterator} to the target {@link CallStreamObserver} while properly * accounting for outbound flow-control. After calling this method, {@code target} should no * longer be used. * * <p>For clients this method is safe to call inside {@link ClientResponseObserver#beforeStart}, * on servers it is safe to call inside the service method implementation. * </p> * * @param source of values expressed as an {@link Iterator}. * @param target {@link CallStreamObserver} which accepts values from the source. */ public static <V> void copyWithFlowControl(final Iterator<V> source, final CallStreamObserver<V> target) { Preconditions.checkNotNull(source, "source"); Preconditions.checkNotNull(target, "target"); final class FlowControllingOnReadyHandler implements Runnable { private boolean completed; @Override public void run() { if (completed) { return; } while (target.isReady() && source.hasNext()) { target.onNext(source.next()); } if (!source.hasNext()) { completed = true; target.onCompleted(); } } } target.setOnReadyHandler(new FlowControllingOnReadyHandler()); } /** * Copy the values of an {@link Iterable} to the target {@link CallStreamObserver} while properly * accounting for outbound flow-control. After calling this method, {@code target} should no * longer be used. * * <p>For clients this method is safe to call inside {@link ClientResponseObserver#beforeStart}, * on servers it is safe to call inside the service method implementation. * </p> * * @param source of values expressed as an {@link Iterable}. * @param target {@link CallStreamObserver} which accepts values from the source. */ public static <V> void copyWithFlowControl(final Iterable<V> source, CallStreamObserver<V> target) { Preconditions.checkNotNull(source, "source"); copyWithFlowControl(source.iterator(), target); } }
stub/src/main/java/io/grpc/stub/StreamObservers.java
/* * Copyright 2015 The gRPC Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.grpc.stub; import com.google.common.base.Preconditions; import io.grpc.ExperimentalApi; import java.util.Iterator; /** * Utility functions for working with {@link StreamObserver} and it's common subclasses like * {@link CallStreamObserver}. */ @ExperimentalApi("https://github.com/grpc/grpc-java/issues/4694") public final class StreamObservers { /** * Copy the values of an {@link Iterator} to the target {@link CallStreamObserver} while properly * accounting for outbound flow-control. After calling this method, {@code target} should no * longer be used. * * <p>For clients this method is safe to call inside {@link ClientResponseObserver#beforeStart}, * on servers it is safe to call inside the service method implementation. * </p> * * @param source of values expressed as an {@link Iterator}. * @param target {@link CallStreamObserver} which accepts values from the source. */ public static <V> void copyWithFlowControl(final Iterator<V> source, final CallStreamObserver<V> target) { Preconditions.checkNotNull(source, "source"); Preconditions.checkNotNull(target, "target"); final class FlowControllingOnReadyHandler implements Runnable { @Override public void run() { while (target.isReady() && source.hasNext()) { target.onNext(source.next()); } if (!source.hasNext()) { target.onCompleted(); } } } target.setOnReadyHandler(new FlowControllingOnReadyHandler()); } /** * Copy the values of an {@link Iterable} to the target {@link CallStreamObserver} while properly * accounting for outbound flow-control. After calling this method, {@code target} should no * longer be used. * * <p>For clients this method is safe to call inside {@link ClientResponseObserver#beforeStart}, * on servers it is safe to call inside the service method implementation. * </p> * * @param source of values expressed as an {@link Iterable}. * @param target {@link CallStreamObserver} which accepts values from the source. */ public static <V> void copyWithFlowControl(final Iterable<V> source, CallStreamObserver<V> target) { Preconditions.checkNotNull(source, "source"); copyWithFlowControl(source.iterator(), target); } }
StreamObservers: make sure onComplete only gets called once from onReadyHandler Fixes #4558
stub/src/main/java/io/grpc/stub/StreamObservers.java
StreamObservers: make sure onComplete only gets called once from onReadyHandler
<ide><path>tub/src/main/java/io/grpc/stub/StreamObservers.java <ide> Preconditions.checkNotNull(target, "target"); <ide> <ide> final class FlowControllingOnReadyHandler implements Runnable { <add> private boolean completed; <add> <ide> @Override <ide> public void run() { <add> if (completed) { <add> return; <add> } <add> <ide> while (target.isReady() && source.hasNext()) { <ide> target.onNext(source.next()); <ide> } <add> <ide> if (!source.hasNext()) { <add> completed = true; <ide> target.onCompleted(); <ide> } <ide> }
JavaScript
apache-2.0
457641fbd35ca2dda6ed5e15cfc8db7663c1ccb4
0
progsung/cesium,hodbauer/cesium,hodbauer/cesium,likangning93/cesium,soceur/cesium,YonatanKra/cesium,YonatanKra/cesium,YonatanKra/cesium,likangning93/cesium,AnalyticalGraphicsInc/cesium,geoscan/cesium,kaktus40/cesium,jasonbeverage/cesium,AnalyticalGraphicsInc/cesium,CesiumGS/cesium,soceur/cesium,likangning93/cesium,likangning93/cesium,CesiumGS/cesium,hodbauer/cesium,likangning93/cesium,YonatanKra/cesium,kaktus40/cesium,progsung/cesium,CesiumGS/cesium,soceur/cesium,geoscan/cesium,jasonbeverage/cesium,josh-bernstein/cesium,josh-bernstein/cesium,CesiumGS/cesium,CesiumGS/cesium
define([ '../Core/Cartesian3', '../Core/Cartographic', '../Core/Check', '../Core/defined', '../Core/destroyObject', '../Core/EasingFunction', '../Core/Math', '../Core/Matrix4', '../Core/OrthographicFrustum', '../Core/OrthographicOffCenterFrustum', '../Core/PerspectiveFrustum', '../Core/Ray', '../Core/ScreenSpaceEventHandler', '../Core/ScreenSpaceEventType', '../Core/Transforms', './Camera', './SceneMode' ], function( Cartesian3, Cartographic, Check, defined, destroyObject, EasingFunction, CesiumMath, Matrix4, OrthographicFrustum, OrthographicOffCenterFrustum, PerspectiveFrustum, Ray, ScreenSpaceEventHandler, ScreenSpaceEventType, Transforms, Camera, SceneMode) { 'use strict'; /** * @private */ function SceneTransitioner(scene) { //>>includeStart('debug', pragmas.debug); Check.typeOf.object('scene', scene); //>>includeEnd('debug'); this._scene = scene; this._currentTweens = []; this._morphHandler = undefined; this._morphCancelled = false; this._completeMorph = undefined; this._morphToOrthographic = false; } SceneTransitioner.prototype.completeMorph = function() { if (defined(this._completeMorph)) { this._completeMorph(); } }; SceneTransitioner.prototype.morphTo2D = function(duration, ellipsoid) { if (defined(this._completeMorph)) { this._completeMorph(); } var scene = this._scene; this._previousMode = scene.mode; this._morphToOrthographic = scene.camera.frustum instanceof OrthographicFrustum; if (this._previousMode === SceneMode.SCENE2D || this._previousMode === SceneMode.MORPHING) { return; } this._scene.morphStart.raiseEvent(this, this._previousMode, SceneMode.SCENE2D, true); scene._mode = SceneMode.MORPHING; scene.camera._setTransform(Matrix4.IDENTITY); if (this._previousMode === SceneMode.COLUMBUS_VIEW) { morphFromColumbusViewTo2D(this, duration); } else { morphFrom3DTo2D(this, duration, ellipsoid); } if (duration === 0.0 && defined(this._completeMorph)) { this._completeMorph(); } }; var scratchToCVPosition = new Cartesian3(); var scratchToCVDirection = new Cartesian3(); var scratchToCVUp = new Cartesian3(); var scratchToCVPosition2D = new Cartesian3(); var scratchToCVDirection2D = new Cartesian3(); var scratchToCVUp2D = new Cartesian3(); var scratchToCVSurfacePosition = new Cartesian3(); var scratchToCVCartographic = new Cartographic(); var scratchToCVToENU = new Matrix4(); var scratchToCVFrustumPerspective = new PerspectiveFrustum(); var scratchToCVFrustumOrthographic = new OrthographicFrustum(); var scratchToCVCamera = { position : undefined, direction : undefined, up : undefined, position2D : undefined, direction2D : undefined, up2D : undefined, frustum : undefined }; SceneTransitioner.prototype.morphToColumbusView = function(duration, ellipsoid) { if (defined(this._completeMorph)) { this._completeMorph(); } var scene = this._scene; this._previousMode = scene.mode; if (this._previousMode === SceneMode.COLUMBUS_VIEW || this._previousMode === SceneMode.MORPHING) { return; } this._scene.morphStart.raiseEvent(this, this._previousMode, SceneMode.COLUMBUS_VIEW, true); scene.camera._setTransform(Matrix4.IDENTITY); var position = scratchToCVPosition; var direction = scratchToCVDirection; var up = scratchToCVUp; if (duration > 0.0) { position.x = 0.0; position.y = -1.0; position.z = 1.0; position = Cartesian3.multiplyByScalar(Cartesian3.normalize(position, position), 5.0 * ellipsoid.maximumRadius, position); Cartesian3.negate(Cartesian3.normalize(position, direction), direction); Cartesian3.cross(Cartesian3.UNIT_X, direction, up); } else { var camera = scene.camera; if (this._previousMode === SceneMode.SCENE2D) { Cartesian3.clone(camera.position, position); position.z = camera.frustum.right - camera.frustum.left; Cartesian3.negate(Cartesian3.UNIT_Z, direction); Cartesian3.clone(Cartesian3.UNIT_Y, up); } else { Cartesian3.clone(camera.positionWC, position); Cartesian3.clone(camera.directionWC, direction); Cartesian3.clone(camera.upWC, up); var surfacePoint = ellipsoid.scaleToGeodeticSurface(position, scratchToCVSurfacePosition); var toENU = Transforms.eastNorthUpToFixedFrame(surfacePoint, ellipsoid, scratchToCVToENU); Matrix4.inverseTransformation(toENU, toENU); scene.mapProjection.project(ellipsoid.cartesianToCartographic(position, scratchToCVCartographic), position); Matrix4.multiplyByPointAsVector(toENU, direction, direction); Matrix4.multiplyByPointAsVector(toENU, up, up); } } var frustum; if (this._morphToOrthographic) { frustum = scratchToCVFrustumOrthographic; frustum.width = scene.camera.frustum.right - scene.camera.frustum.left; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; } else { frustum = scratchToCVFrustumPerspective; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = CesiumMath.toRadians(60.0); } var cameraCV = scratchToCVCamera; cameraCV.position = position; cameraCV.direction = direction; cameraCV.up = up; cameraCV.frustum = frustum; var complete = completeColumbusViewCallback(cameraCV); createMorphHandler(this, complete); if (this._previousMode === SceneMode.SCENE2D) { morphFrom2DToColumbusView(this, duration, cameraCV, complete); } else { cameraCV.position2D = Matrix4.multiplyByPoint(Camera.TRANSFORM_2D, position, scratchToCVPosition2D); cameraCV.direction2D = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, direction, scratchToCVDirection2D); cameraCV.up2D = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, up, scratchToCVUp2D); scene._mode = SceneMode.MORPHING; morphFrom3DToColumbusView(this, duration, cameraCV, complete); } if (duration === 0.0 && defined(this._completeMorph)) { this._completeMorph(); } }; var scratchCVTo3DCamera = { position : new Cartesian3(), direction : new Cartesian3(), up : new Cartesian3(), frustum : undefined }; var scratch2DTo3DFrustumPersp = new PerspectiveFrustum(); SceneTransitioner.prototype.morphTo3D = function(duration, ellipsoid) { if (defined(this._completeMorph)) { this._completeMorph(); } var scene = this._scene; this._previousMode = scene.mode; if (this._previousMode === SceneMode.SCENE3D || this._previousMode === SceneMode.MORPHING) { return; } this._scene.morphStart.raiseEvent(this, this._previousMode, SceneMode.SCENE3D, true); scene._mode = SceneMode.MORPHING; scene.camera._setTransform(Matrix4.IDENTITY); if (this._previousMode === SceneMode.SCENE2D) { morphFrom2DTo3D(this, duration, ellipsoid); } else { var camera3D; if (duration > 0.0) { camera3D = scratchCVTo3DCamera; Cartesian3.fromDegrees(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, ellipsoid, camera3D.position); Cartesian3.negate(camera3D.position, camera3D.direction); Cartesian3.normalize(camera3D.direction, camera3D.direction); Cartesian3.clone(Cartesian3.UNIT_Z, camera3D.up); } else { camera3D = getColumbusViewTo3DCamera(this, ellipsoid); } var frustum; var camera = scene.camera; if (camera.frustum instanceof OrthographicFrustum) { frustum = camera.frustum.clone(); } else { frustum = scratch2DTo3DFrustumPersp; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = CesiumMath.toRadians(60.0); } camera3D.frustum = frustum; var complete = complete3DCallback(camera3D); createMorphHandler(this, complete); morphFromColumbusViewTo3D(this, duration, camera3D, complete); } if (duration === 0.0 && defined(this._completeMorph)) { this._completeMorph(); } }; /** * Returns true if this object was destroyed; otherwise, false. * <br /><br /> * If this object was destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. * * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>. */ SceneTransitioner.prototype.isDestroyed = function() { return false; }; /** * Once an object is destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore, * assign the return value (<code>undefined</code>) to the object as done in the example. * * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called. * * @example * transitioner = transitioner && transitioner.destroy(); */ SceneTransitioner.prototype.destroy = function() { destroyMorphHandler(this); return destroyObject(this); }; function createMorphHandler(transitioner, completeMorphFunction) { if (transitioner._scene.completeMorphOnUserInput) { transitioner._morphHandler = new ScreenSpaceEventHandler(transitioner._scene.canvas, false); var completeMorph = function() { transitioner._morphCancelled = true; completeMorphFunction(transitioner); }; transitioner._completeMorph = completeMorph; transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.LEFT_DOWN); transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.MIDDLE_DOWN); transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.RIGHT_DOWN); transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.WHEEL); } } function destroyMorphHandler(transitioner) { var tweens = transitioner._currentTweens; for ( var i = 0; i < tweens.length; ++i) { tweens[i].cancelTween(); } transitioner._currentTweens.length = 0; transitioner._morphHandler = transitioner._morphHandler && transitioner._morphHandler.destroy(); } var scratchCVTo3DCartographic = new Cartographic(); var scratchCVTo3DSurfacePoint = new Cartesian3(); var scratchCVTo3DFromENU = new Matrix4(); function getColumbusViewTo3DCamera(transitioner, ellipsoid) { var scene = transitioner._scene; var camera = scene.camera; var camera3D = scratchCVTo3DCamera; var position = camera3D.position; var direction = camera3D.direction; var up = camera3D.up; var positionCarto = scene.mapProjection.unproject(camera.position, scratchCVTo3DCartographic); ellipsoid.cartographicToCartesian(positionCarto, position); var surfacePoint = ellipsoid.scaleToGeodeticSurface(position, scratchCVTo3DSurfacePoint); var fromENU = Transforms.eastNorthUpToFixedFrame(surfacePoint, ellipsoid, scratchCVTo3DFromENU); Matrix4.multiplyByPointAsVector(fromENU, camera.direction, direction); Matrix4.multiplyByPointAsVector(fromENU, camera.up, up); return camera3D; } var scratchCVTo3DStartPos = new Cartesian3(); var scratchCVTo3DStartDir = new Cartesian3(); var scratchCVTo3DStartUp = new Cartesian3(); var scratchCVTo3DEndPos = new Cartesian3(); var scratchCVTo3DEndDir = new Cartesian3(); var scratchCVTo3DEndUp = new Cartesian3(); function morphFromColumbusViewTo3D(transitioner, duration, endCamera, complete) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var startPos = Cartesian3.clone(camera.position, scratchCVTo3DStartPos); var startDir = Cartesian3.clone(camera.direction, scratchCVTo3DStartDir); var startUp = Cartesian3.clone(camera.up, scratchCVTo3DStartUp); var endPos = Matrix4.multiplyByPoint(Camera.TRANSFORM_2D_INVERSE, endCamera.position, scratchCVTo3DEndPos); var endDir = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D_INVERSE, endCamera.direction, scratchCVTo3DEndDir); var endUp = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D_INVERSE, endCamera.up, scratchCVTo3DEndUp); function update(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { addMorphTimeAnimations(transitioner, scene, 0.0, 1.0, duration, complete); } }); transitioner._currentTweens.push(tween); } var scratch2DTo3DFrustumOrtho = new OrthographicFrustum(); var scratch3DToCVStartPos = new Cartesian3(); var scratch3DToCVStartDir = new Cartesian3(); var scratch3DToCVStartUp = new Cartesian3(); var scratch3DToCVEndPos = new Cartesian3(); var scratch3DToCVEndDir = new Cartesian3(); var scratch3DToCVEndUp = new Cartesian3(); function morphFrom2DTo3D(transitioner, duration, ellipsoid) { duration /= 3.0; var scene = transitioner._scene; var camera = scene.camera; var camera3D; if (duration > 0.0) { camera3D = scratchCVTo3DCamera; Cartesian3.fromDegrees(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, ellipsoid, camera3D.position); Cartesian3.negate(camera3D.position, camera3D.direction); Cartesian3.normalize(camera3D.direction, camera3D.direction); Cartesian3.clone(Cartesian3.UNIT_Z, camera3D.up); } else { camera.position.z = camera.frustum.right - camera.frustum.left; camera3D = getColumbusViewTo3DCamera(transitioner, ellipsoid); } var frustum; if (transitioner._morphToOrthographic) { frustum = scratch2DTo3DFrustumOrtho; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.width = camera.frustum.right - camera.frustum.left; } else { frustum = scratch2DTo3DFrustumPersp; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = CesiumMath.toRadians(60.0); } camera3D.frustum = frustum; var complete = complete3DCallback(camera3D); createMorphHandler(transitioner, complete); var morph; if (transitioner._morphToOrthographic) { morph = function() { morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete); }; } else { morph = function() { morphOrthographicToPerspective(transitioner, duration, camera3D, function() { morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete); }); }; } if (duration > 0.0) { scene._mode = SceneMode.SCENE2D; camera.flyTo({ duration : duration, destination : Cartesian3.fromDegrees(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, ellipsoid, scratch3DToCVEndPos), complete : function() { scene._mode = SceneMode.MORPHING; morph(); } }); } else { morph(); } } function columbusViewMorph(startPosition, endPosition, time, result) { // Just linear for now. return Cartesian3.lerp(startPosition, endPosition, time, result); } function morphPerspectiveToOrthographic(transitioner, duration, endCamera, updateHeight, complete) { var scene = transitioner._scene; var camera = scene.camera; if (camera.frustum instanceof OrthographicFrustum) { return; } var startFOV = camera.frustum.fov; var endFOV = CesiumMath.RADIANS_PER_DEGREE * 0.5; var d = endCamera.position.z * Math.tan(startFOV * 0.5); camera.frustum.far = d / Math.tan(endFOV * 0.5) + 10000000.0; function update(value) { camera.frustum.fov = CesiumMath.lerp(startFOV, endFOV, value.time); var height = d / Math.tan(camera.frustum.fov * 0.5); updateHeight(camera, height); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { camera.frustum = endCamera.frustum.clone(); complete(transitioner); } }); transitioner._currentTweens.push(tween); } var scratchCVTo2DStartPos = new Cartesian3(); var scratchCVTo2DStartDir = new Cartesian3(); var scratchCVTo2DStartUp = new Cartesian3(); var scratchCVTo2DEndPos = new Cartesian3(); var scratchCVTo2DEndDir = new Cartesian3(); var scratchCVTo2DEndUp = new Cartesian3(); var scratchCVTo2DFrustum = new OrthographicOffCenterFrustum(); var scratchCVTo2DRay = new Ray(); var scratchCVTo2DPickPos = new Cartesian3(); var scratchCVTo2DCamera = { position : undefined, direction : undefined, up : undefined, frustum : undefined }; function morphFromColumbusViewTo2D(transitioner, duration) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var startPos = Cartesian3.clone(camera.position, scratchCVTo2DStartPos); var startDir = Cartesian3.clone(camera.direction, scratchCVTo2DStartDir); var startUp = Cartesian3.clone(camera.up, scratchCVTo2DStartUp); var endDir = Cartesian3.negate(Cartesian3.UNIT_Z, scratchCVTo2DEndDir); var endUp = Cartesian3.clone(Cartesian3.UNIT_Y, scratchCVTo2DEndUp); var endPos = scratchCVTo2DEndPos; if (duration > 0.0) { Cartesian3.clone(Cartesian3.ZERO, scratchCVTo2DEndPos); endPos.z = 5.0 * scene.mapProjection.ellipsoid.maximumRadius; } else { Cartesian3.clone(startPos, scratchCVTo2DEndPos); var ray = scratchCVTo2DRay; Matrix4.multiplyByPoint(Camera.TRANSFORM_2D, startPos, ray.origin); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, startDir, ray.direction); var globe = scene.globe; if (defined(globe)) { var pickPos = globe.pick(ray, scene, scratchCVTo2DPickPos); if (defined(pickPos)) { Matrix4.multiplyByPoint(Camera.TRANSFORM_2D_INVERSE, pickPos, endPos); endPos.z += Cartesian3.distance(startPos, endPos); } } } var frustum = scratchCVTo2DFrustum; frustum.right = endPos.z * 0.5; frustum.left = -frustum.right; frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); frustum.bottom = -frustum.top; var camera2D = scratchCVTo2DCamera; camera2D.position = endPos; camera2D.direction = endDir; camera2D.up = endUp; camera2D.frustum = frustum; var complete = complete2DCallback(camera2D); createMorphHandler(transitioner, complete); function updateCV(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera._adjustOrthographicFrustum(true); } function updateHeight(camera, height) { camera.position.z = height; } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : updateCV, complete : function() { morphPerspectiveToOrthographic(transitioner, duration, camera2D, updateHeight, complete); } }); transitioner._currentTweens.push(tween); } var scratch3DTo2DCartographic = new Cartographic(); var scratch3DTo2DCamera = { position : new Cartesian3(), direction : new Cartesian3(), up : new Cartesian3(), position2D : new Cartesian3(), direction2D : new Cartesian3(), up2D : new Cartesian3(), frustum : new OrthographicOffCenterFrustum() }; var scratch3DTo2DEndCamera = { position : new Cartesian3(), direction : new Cartesian3(), up : new Cartesian3(), frustum : undefined }; var scratch3DTo2DPickPosition = new Cartesian3(); var scratch3DTo2DRay = new Ray(); var scratch3DTo2DToENU = new Matrix4(); var scratch3DTo2DSurfacePoint = new Cartesian3(); function morphFrom3DTo2D(transitioner, duration, ellipsoid) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var camera2D = scratch3DTo2DCamera; if (duration > 0.0) { Cartesian3.clone(Cartesian3.ZERO, camera2D.position); camera2D.position.z = 5.0 * ellipsoid.maximumRadius; Cartesian3.negate(Cartesian3.UNIT_Z, camera2D.direction); Cartesian3.clone(Cartesian3.UNIT_Y, camera2D.up); } else { ellipsoid.cartesianToCartographic(camera.positionWC, scratch3DTo2DCartographic); scene.mapProjection.project(scratch3DTo2DCartographic, camera2D.position); Cartesian3.negate(Cartesian3.UNIT_Z, camera2D.direction); Cartesian3.clone(Cartesian3.UNIT_Y, camera2D.up); var ray = scratch3DTo2DRay; Cartesian3.clone(camera2D.position2D, ray.origin); var rayDirection = Cartesian3.clone(camera.directionWC, ray.direction); var surfacePoint = ellipsoid.scaleToGeodeticSurface(camera.positionWC, scratch3DTo2DSurfacePoint); var toENU = Transforms.eastNorthUpToFixedFrame(surfacePoint, ellipsoid, scratch3DTo2DToENU); Matrix4.inverseTransformation(toENU, toENU); Matrix4.multiplyByPointAsVector(toENU, rayDirection, rayDirection); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, rayDirection, rayDirection); var globe = scene.globe; if (defined(globe)) { var pickedPos = globe.pick(ray, scene, scratch3DTo2DPickPosition); if (defined(pickedPos)) { var height = Cartesian3.distance(camera2D.position2D, pickedPos); pickedPos.x += height; Cartesian3.clone(pickedPos, camera2D.position2D); } } } function updateHeight(camera, height) { camera.position.x = height; } Matrix4.multiplyByPoint(Camera.TRANSFORM_2D, camera2D.position, camera2D.position2D); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, camera2D.direction, camera2D.direction2D); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, camera2D.up, camera2D.up2D); var frustum = camera2D.frustum; frustum.right = camera2D.position.z * 0.5; frustum.left = -frustum.right; frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); frustum.bottom = -frustum.top; var endCamera = scratch3DTo2DEndCamera; Matrix4.multiplyByPoint(Camera.TRANSFORM_2D_INVERSE, camera2D.position2D, endCamera.position); Cartesian3.clone(camera2D.direction, endCamera.direction); Cartesian3.clone(camera2D.up, endCamera.up); endCamera.frustum = frustum; var complete = complete2DCallback(endCamera); createMorphHandler(transitioner, complete); function completeCallback() { morphPerspectiveToOrthographic(transitioner, duration, camera2D, updateHeight, complete); } morphFrom3DToColumbusView(transitioner, duration, camera2D, completeCallback); } function morphOrthographicToPerspective(transitioner, duration, cameraCV, complete) { var scene = transitioner._scene; var camera = scene.camera; var height = camera.frustum.right - camera.frustum.left; camera.frustum = cameraCV.frustum.clone(); var endFOV = camera.frustum.fov; var startFOV = CesiumMath.RADIANS_PER_DEGREE * 0.5; var d = height * Math.tan(endFOV * 0.5); camera.frustum.far = d / Math.tan(startFOV * 0.5) + 10000000.0; camera.frustum.fov = startFOV; function update(value) { camera.frustum.fov = CesiumMath.lerp(startFOV, endFOV, value.time); camera.position.z = d / Math.tan(camera.frustum.fov * 0.5); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { complete(transitioner); } }); transitioner._currentTweens.push(tween); } function morphFrom2DToColumbusView(transitioner, duration, cameraCV, complete) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var endPos = Cartesian3.clone(cameraCV.position, scratch3DToCVEndPos); var endDir = Cartesian3.clone(cameraCV.direction, scratch3DToCVEndDir); var endUp = Cartesian3.clone(cameraCV.up, scratch3DToCVEndUp); scene._mode = SceneMode.MORPHING; function morph() { camera.frustum = cameraCV.frustum.clone(); var startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos); var startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir); var startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp); startPos.z = endPos.z; function update(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { complete(transitioner); } }); transitioner._currentTweens.push(tween); } if (transitioner._morphToOrthographic) { morph(); } else { morphOrthographicToPerspective(transitioner, 0.0, cameraCV, morph); } } function morphFrom3DToColumbusView(transitioner, duration, endCamera, complete) { var scene = transitioner._scene; var camera = scene.camera; var startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos); var startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir); var startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp); var endPos = Cartesian3.clone(endCamera.position2D, scratch3DToCVEndPos); var endDir = Cartesian3.clone(endCamera.direction2D, scratch3DToCVEndDir); var endUp = Cartesian3.clone(endCamera.up2D, scratch3DToCVEndUp); function update(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera._adjustOrthographicFrustum(true); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { addMorphTimeAnimations(transitioner, scene, 1.0, 0.0, duration, complete); } }); transitioner._currentTweens.push(tween); } function addMorphTimeAnimations(transitioner, scene, start, stop, duration, complete) { // Later, this will be linear and each object will adjust, if desired, in its vertex shader. var options = { object : scene, property : 'morphTime', startValue : start, stopValue : stop, duration : duration, easingFunction : EasingFunction.QUARTIC_OUT }; if (defined(complete)) { options.complete = function() { complete(transitioner); }; } var tween = scene.tweens.addProperty(options); transitioner._currentTweens.push(tween); } function complete3DCallback(camera3D) { return function(transitioner) { var scene = transitioner._scene; scene._mode = SceneMode.SCENE3D; scene.morphTime = SceneMode.getMorphTime(SceneMode.SCENE3D); destroyMorphHandler(transitioner); var camera = scene.camera; if (transitioner._previousMode !== SceneMode.MORPHING || transitioner._morphCancelled) { transitioner._morphCancelled = false; Cartesian3.clone(camera3D.position, camera.position); Cartesian3.clone(camera3D.direction, camera.direction); Cartesian3.clone(camera3D.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera.frustum = camera3D.frustum.clone(); } var frustum = camera.frustum; if (scene._logDepthBuffer && !(frustum instanceof OrthographicFrustum || frustum instanceof OrthographicOffCenterFrustum)) { frustum.near = 0.1; frustum.far = 10000000000.0; } var wasMorphing = defined(transitioner._completeMorph); transitioner._completeMorph = undefined; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent(transitioner, transitioner._previousMode, SceneMode.SCENE3D, wasMorphing); }; } function complete2DCallback(camera2D) { return function(transitioner) { var scene = transitioner._scene; scene._mode = SceneMode.SCENE2D; scene.morphTime = SceneMode.getMorphTime(SceneMode.SCENE2D); destroyMorphHandler(transitioner); var camera = scene.camera; Cartesian3.clone(camera2D.position, camera.position); camera.position.z = scene.mapProjection.ellipsoid.maximumRadius * 2.0; Cartesian3.clone(camera2D.direction, camera.direction); Cartesian3.clone(camera2D.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera.frustum = camera2D.frustum.clone(); var wasMorphing = defined(transitioner._completeMorph); transitioner._completeMorph = undefined; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent(transitioner, transitioner._previousMode, SceneMode.SCENE2D, wasMorphing); }; } function completeColumbusViewCallback(cameraCV) { return function(transitioner) { var scene = transitioner._scene; scene._mode = SceneMode.COLUMBUS_VIEW; scene.morphTime = SceneMode.getMorphTime(SceneMode.COLUMBUS_VIEW); destroyMorphHandler(transitioner); var camera = scene.camera; if (transitioner._previousModeMode !== SceneMode.MORPHING || transitioner._morphCancelled) { transitioner._morphCancelled = false; Cartesian3.clone(cameraCV.position, camera.position); Cartesian3.clone(cameraCV.direction, camera.direction); Cartesian3.clone(cameraCV.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); } var frustum = camera.frustum; if (scene._logDepthBuffer && !(frustum instanceof OrthographicFrustum || frustum instanceof OrthographicOffCenterFrustum)) { frustum.near = 0.1; frustum.far = 10000000000.0; } var wasMorphing = defined(transitioner._completeMorph); transitioner._completeMorph = undefined; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent(transitioner, transitioner._previousMode, SceneMode.COLUMBUS_VIEW, wasMorphing); }; } return SceneTransitioner; });
Source/Scene/SceneTransitioner.js
define([ '../Core/Cartesian3', '../Core/Cartographic', '../Core/Check', '../Core/defined', '../Core/destroyObject', '../Core/EasingFunction', '../Core/Math', '../Core/Matrix4', '../Core/OrthographicFrustum', '../Core/OrthographicOffCenterFrustum', '../Core/PerspectiveFrustum', '../Core/Ray', '../Core/ScreenSpaceEventHandler', '../Core/ScreenSpaceEventType', '../Core/Transforms', './Camera', './SceneMode' ], function( Cartesian3, Cartographic, Check, defined, destroyObject, EasingFunction, CesiumMath, Matrix4, OrthographicFrustum, OrthographicOffCenterFrustum, PerspectiveFrustum, Ray, ScreenSpaceEventHandler, ScreenSpaceEventType, Transforms, Camera, SceneMode) { 'use strict'; /** * @private */ function SceneTransitioner(scene) { //>>includeStart('debug', pragmas.debug); Check.typeOf.object('scene', scene); //>>includeEnd('debug'); this._scene = scene; this._currentTweens = []; this._morphHandler = undefined; this._morphCancelled = false; this._completeMorph = undefined; this._morphToOrthographic = false; } SceneTransitioner.prototype.completeMorph = function() { if (defined(this._completeMorph)) { this._completeMorph(); } }; SceneTransitioner.prototype.morphTo2D = function(duration, ellipsoid) { if (defined(this._completeMorph)) { this._completeMorph(); } var scene = this._scene; this._previousMode = scene.mode; this._morphToOrthographic = scene.camera.frustum instanceof OrthographicFrustum; if (this._previousMode === SceneMode.SCENE2D || this._previousMode === SceneMode.MORPHING) { return; } this._scene.morphStart.raiseEvent(this, this._previousMode, SceneMode.SCENE2D, true); scene._mode = SceneMode.MORPHING; scene.camera._setTransform(Matrix4.IDENTITY); if (this._previousMode === SceneMode.COLUMBUS_VIEW) { morphFromColumbusViewTo2D(this, duration); } else { morphFrom3DTo2D(this, duration, ellipsoid); } if (duration === 0.0 && defined(this._completeMorph)) { this._completeMorph(); } }; var scratchToCVPosition = new Cartesian3(); var scratchToCVDirection = new Cartesian3(); var scratchToCVUp = new Cartesian3(); var scratchToCVPosition2D = new Cartesian3(); var scratchToCVDirection2D = new Cartesian3(); var scratchToCVUp2D = new Cartesian3(); var scratchToCVSurfacePosition = new Cartesian3(); var scratchToCVCartographic = new Cartographic(); var scratchToCVToENU = new Matrix4(); var scratchToCVFrustumPerspective = new PerspectiveFrustum(); var scratchToCVFrustumOrthographic = new OrthographicFrustum(); var scratchToCVCamera = { position : undefined, direction : undefined, up : undefined, position2D : undefined, direction2D : undefined, up2D : undefined, frustum : undefined }; SceneTransitioner.prototype.morphToColumbusView = function(duration, ellipsoid) { if (defined(this._completeMorph)) { this._completeMorph(); } var scene = this._scene; this._previousMode = scene.mode; if (this._previousMode === SceneMode.COLUMBUS_VIEW || this._previousMode === SceneMode.MORPHING) { return; } this._scene.morphStart.raiseEvent(this, this._previousMode, SceneMode.COLUMBUS_VIEW, true); scene.camera._setTransform(Matrix4.IDENTITY); var position = scratchToCVPosition; var direction = scratchToCVDirection; var up = scratchToCVUp; if (duration > 0.0) { position.x = 0.0; position.y = -1.0; position.z = 1.0; position = Cartesian3.multiplyByScalar(Cartesian3.normalize(position, position), 5.0 * ellipsoid.maximumRadius, position); Cartesian3.negate(Cartesian3.normalize(position, direction), direction); Cartesian3.cross(Cartesian3.UNIT_X, direction, up); } else { var camera = scene.camera; if (this._previousMode === SceneMode.SCENE2D) { Cartesian3.clone(camera.position, position); position.z = camera.frustum.right - camera.frustum.left; Cartesian3.negate(Cartesian3.UNIT_Z, direction); Cartesian3.clone(Cartesian3.UNIT_Y, up); } else { Cartesian3.clone(camera.positionWC, position); Cartesian3.clone(camera.directionWC, direction); Cartesian3.clone(camera.upWC, up); var surfacePoint = ellipsoid.scaleToGeodeticSurface(position, scratchToCVSurfacePosition); var toENU = Transforms.eastNorthUpToFixedFrame(surfacePoint, ellipsoid, scratchToCVToENU); Matrix4.inverseTransformation(toENU, toENU); scene.mapProjection.project(ellipsoid.cartesianToCartographic(position, scratchToCVCartographic), position); Matrix4.multiplyByPointAsVector(toENU, direction, direction); Matrix4.multiplyByPointAsVector(toENU, up, up); } } var frustum; if (this._morphToOrthographic) { frustum = scratchToCVFrustumOrthographic; frustum.width = scene.camera.frustum.right - scene.camera.frustum.left; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; } else { frustum = scratchToCVFrustumPerspective; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = CesiumMath.toRadians(60.0); } var cameraCV = scratchToCVCamera; cameraCV.position = position; cameraCV.direction = direction; cameraCV.up = up; cameraCV.frustum = frustum; var complete = completeColumbusViewCallback(cameraCV); createMorphHandler(this, complete); if (this._previousMode === SceneMode.SCENE2D) { morphFrom2DToColumbusView(this, duration, cameraCV, complete); } else { cameraCV.position2D = Matrix4.multiplyByPoint(Camera.TRANSFORM_2D, position, scratchToCVPosition2D); cameraCV.direction2D = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, direction, scratchToCVDirection2D); cameraCV.up2D = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, up, scratchToCVUp2D); scene._mode = SceneMode.MORPHING; morphFrom3DToColumbusView(this, duration, cameraCV, complete); } if (duration === 0.0 && defined(this._completeMorph)) { this._completeMorph(); } }; var scratchCVTo3DCamera = { position : new Cartesian3(), direction : new Cartesian3(), up : new Cartesian3(), frustum : undefined }; var scratch2DTo3DFrustumPersp = new PerspectiveFrustum(); SceneTransitioner.prototype.morphTo3D = function(duration, ellipsoid) { if (defined(this._completeMorph)) { this._completeMorph(); } var scene = this._scene; this._previousMode = scene.mode; if (this._previousMode === SceneMode.SCENE3D || this._previousMode === SceneMode.MORPHING) { return; } this._scene.morphStart.raiseEvent(this, this._previousMode, SceneMode.SCENE3D, true); scene._mode = SceneMode.MORPHING; scene.camera._setTransform(Matrix4.IDENTITY); if (this._previousMode === SceneMode.SCENE2D) { morphFrom2DTo3D(this, duration, ellipsoid); } else { var camera3D; if (duration > 0.0) { camera3D = scratchCVTo3DCamera; Cartesian3.fromDegrees(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, ellipsoid, camera3D.position); Cartesian3.negate(camera3D.position, camera3D.direction); Cartesian3.normalize(camera3D.direction, camera3D.direction); Cartesian3.clone(Cartesian3.UNIT_Z, camera3D.up); } else { camera3D = getColumbusViewTo3DCamera(this, ellipsoid); } var frustum; var camera = scene.camera; if (camera.frustum instanceof OrthographicFrustum) { frustum = camera.frustum.clone(); } else { frustum = scratch2DTo3DFrustumPersp; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = CesiumMath.toRadians(60.0); } camera3D.frustum = frustum; var complete = complete3DCallback(camera3D); createMorphHandler(this, complete); morphFromColumbusViewTo3D(this, duration, camera3D, complete); } if (duration === 0.0 && defined(this._completeMorph)) { this._completeMorph(); } }; /** * Returns true if this object was destroyed; otherwise, false. * <br /><br /> * If this object was destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. * * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>. */ SceneTransitioner.prototype.isDestroyed = function() { return false; }; /** * Once an object is destroyed, it should not be used; calling any function other than * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore, * assign the return value (<code>undefined</code>) to the object as done in the example. * * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called. * * @example * transitioner = transitioner && transitioner.destroy(); */ SceneTransitioner.prototype.destroy = function() { destroyMorphHandler(this); return destroyObject(this); }; function createMorphHandler(transitioner, completeMorphFunction) { if (transitioner._scene.completeMorphOnUserInput) { transitioner._morphHandler = new ScreenSpaceEventHandler(transitioner._scene.canvas, false); var completeMorph = function() { transitioner._morphCancelled = true; completeMorphFunction(transitioner); }; transitioner._completeMorph = completeMorph; transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.LEFT_DOWN); transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.MIDDLE_DOWN); transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.RIGHT_DOWN); transitioner._morphHandler.setInputAction(completeMorph, ScreenSpaceEventType.WHEEL); } } function destroyMorphHandler(transitioner) { var tweens = transitioner._currentTweens; for ( var i = 0; i < tweens.length; ++i) { tweens[i].cancelTween(); } transitioner._currentTweens.length = 0; transitioner._morphHandler = transitioner._morphHandler && transitioner._morphHandler.destroy(); } var scratchCVTo3DCartographic = new Cartographic(); var scratchCVTo3DSurfacePoint = new Cartesian3(); var scratchCVTo3DFromENU = new Matrix4(); function getColumbusViewTo3DCamera(transitioner, ellipsoid) { var scene = transitioner._scene; var camera = scene.camera; var camera3D = scratchCVTo3DCamera; var position = camera3D.position; var direction = camera3D.direction; var up = camera3D.up; var positionCarto = scene.mapProjection.unproject(camera.position, scratchCVTo3DCartographic); ellipsoid.cartographicToCartesian(positionCarto, position); var surfacePoint = ellipsoid.scaleToGeodeticSurface(position, scratchCVTo3DSurfacePoint); var fromENU = Transforms.eastNorthUpToFixedFrame(surfacePoint, ellipsoid, scratchCVTo3DFromENU); Matrix4.multiplyByPointAsVector(fromENU, camera.direction, direction); Matrix4.multiplyByPointAsVector(fromENU, camera.up, up); return camera3D; } var scratchCVTo3DStartPos = new Cartesian3(); var scratchCVTo3DStartDir = new Cartesian3(); var scratchCVTo3DStartUp = new Cartesian3(); var scratchCVTo3DEndPos = new Cartesian3(); var scratchCVTo3DEndDir = new Cartesian3(); var scratchCVTo3DEndUp = new Cartesian3(); function morphFromColumbusViewTo3D(transitioner, duration, endCamera, complete) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var startPos = Cartesian3.clone(camera.position, scratchCVTo3DStartPos); var startDir = Cartesian3.clone(camera.direction, scratchCVTo3DStartDir); var startUp = Cartesian3.clone(camera.up, scratchCVTo3DStartUp); var endPos = Matrix4.multiplyByPoint(Camera.TRANSFORM_2D_INVERSE, endCamera.position, scratchCVTo3DEndPos); var endDir = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D_INVERSE, endCamera.direction, scratchCVTo3DEndDir); var endUp = Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D_INVERSE, endCamera.up, scratchCVTo3DEndUp); function update(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { addMorphTimeAnimations(transitioner, scene, 0.0, 1.0, duration, complete); } }); transitioner._currentTweens.push(tween); } var scratch2DTo3DFrustumOrtho = new OrthographicFrustum(); var scratch3DToCVStartPos = new Cartesian3(); var scratch3DToCVStartDir = new Cartesian3(); var scratch3DToCVStartUp = new Cartesian3(); var scratch3DToCVEndPos = new Cartesian3(); var scratch3DToCVEndDir = new Cartesian3(); var scratch3DToCVEndUp = new Cartesian3(); function morphFrom2DTo3D(transitioner, duration, ellipsoid) { duration /= 3.0; var scene = transitioner._scene; var camera = scene.camera; var camera3D; if (duration > 0.0) { camera3D = scratchCVTo3DCamera; Cartesian3.fromDegrees(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, ellipsoid, camera3D.position); Cartesian3.negate(camera3D.position, camera3D.direction); Cartesian3.normalize(camera3D.direction, camera3D.direction); Cartesian3.clone(Cartesian3.UNIT_Z, camera3D.up); } else { camera.position.z = camera.frustum.right - camera.frustum.left; camera3D = getColumbusViewTo3DCamera(transitioner, ellipsoid); } var frustum; if (transitioner._morphToOrthographic) { frustum = scratch2DTo3DFrustumOrtho; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.width = camera.frustum.right - camera.frustum.left; } else { frustum = scratch2DTo3DFrustumPersp; frustum.aspectRatio = scene.drawingBufferWidth / scene.drawingBufferHeight; frustum.fov = CesiumMath.toRadians(60.0); } camera3D.frustum = frustum; var complete = complete3DCallback(camera3D); createMorphHandler(transitioner, complete); var startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos); var startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir); var startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp); var endPos = Cartesian3.fromElements(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, scratch3DToCVEndPos); var endDir = Cartesian3.negate(Cartesian3.UNIT_Z, scratch3DToCVEndDir); var endUp = Cartesian3.clone(Cartesian3.UNIT_Y, scratch3DToCVEndUp); var startRight = camera.frustum.right; var endRight = endPos.z * 0.5; function update(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); var frustum = camera.frustum; frustum.right = CesiumMath.lerp(startRight, endRight, value.time); frustum.left = -frustum.right; frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); frustum.bottom = -frustum.top; camera.position.z = 2.0 * scene.mapProjection.ellipsoid.maximumRadius; } var morph; if (transitioner._morphToOrthographic) { morph = function() { morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete); }; } else { morph = function() { morphOrthographicToPerspective(transitioner, duration, camera3D, function() { morphFromColumbusViewTo3D(transitioner, duration, camera3D, complete); }); }; } if (duration > 0.0) { var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { scene._mode = SceneMode.MORPHING; morph(); } }); transitioner._currentTweens.push(tween); } else { morph(); } } function columbusViewMorph(startPosition, endPosition, time, result) { // Just linear for now. return Cartesian3.lerp(startPosition, endPosition, time, result); } function morphPerspectiveToOrthographic(transitioner, duration, endCamera, updateHeight, complete) { var scene = transitioner._scene; var camera = scene.camera; if (camera.frustum instanceof OrthographicFrustum) { return; } var startFOV = camera.frustum.fov; var endFOV = CesiumMath.RADIANS_PER_DEGREE * 0.5; var d = endCamera.position.z * Math.tan(startFOV * 0.5); camera.frustum.far = d / Math.tan(endFOV * 0.5) + 10000000.0; function update(value) { camera.frustum.fov = CesiumMath.lerp(startFOV, endFOV, value.time); var height = d / Math.tan(camera.frustum.fov * 0.5); updateHeight(camera, height); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { camera.frustum = endCamera.frustum.clone(); complete(transitioner); } }); transitioner._currentTweens.push(tween); } var scratchCVTo2DStartPos = new Cartesian3(); var scratchCVTo2DStartDir = new Cartesian3(); var scratchCVTo2DStartUp = new Cartesian3(); var scratchCVTo2DEndPos = new Cartesian3(); var scratchCVTo2DEndDir = new Cartesian3(); var scratchCVTo2DEndUp = new Cartesian3(); var scratchCVTo2DFrustum = new OrthographicOffCenterFrustum(); var scratchCVTo2DRay = new Ray(); var scratchCVTo2DPickPos = new Cartesian3(); var scratchCVTo2DCamera = { position : undefined, direction : undefined, up : undefined, frustum : undefined }; function morphFromColumbusViewTo2D(transitioner, duration) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var startPos = Cartesian3.clone(camera.position, scratchCVTo2DStartPos); var startDir = Cartesian3.clone(camera.direction, scratchCVTo2DStartDir); var startUp = Cartesian3.clone(camera.up, scratchCVTo2DStartUp); var endDir = Cartesian3.negate(Cartesian3.UNIT_Z, scratchCVTo2DEndDir); var endUp = Cartesian3.clone(Cartesian3.UNIT_Y, scratchCVTo2DEndUp); var endPos = scratchCVTo2DEndPos; if (duration > 0.0) { Cartesian3.clone(Cartesian3.ZERO, scratchCVTo2DEndPos); endPos.z = 5.0 * scene.mapProjection.ellipsoid.maximumRadius; } else { Cartesian3.clone(startPos, scratchCVTo2DEndPos); var ray = scratchCVTo2DRay; Matrix4.multiplyByPoint(Camera.TRANSFORM_2D, startPos, ray.origin); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, startDir, ray.direction); var globe = scene.globe; if (defined(globe)) { var pickPos = globe.pick(ray, scene, scratchCVTo2DPickPos); if (defined(pickPos)) { Matrix4.multiplyByPoint(Camera.TRANSFORM_2D_INVERSE, pickPos, endPos); endPos.z += Cartesian3.distance(startPos, endPos); } } } var frustum = scratchCVTo2DFrustum; frustum.right = endPos.z * 0.5; frustum.left = -frustum.right; frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); frustum.bottom = -frustum.top; var camera2D = scratchCVTo2DCamera; camera2D.position = endPos; camera2D.direction = endDir; camera2D.up = endUp; camera2D.frustum = frustum; var complete = complete2DCallback(camera2D); createMorphHandler(transitioner, complete); function updateCV(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera._adjustOrthographicFrustum(true); } function updateHeight(camera, height) { camera.position.z = height; } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : updateCV, complete : function() { morphPerspectiveToOrthographic(transitioner, duration, camera2D, updateHeight, complete); } }); transitioner._currentTweens.push(tween); } var scratch3DTo2DCartographic = new Cartographic(); var scratch3DTo2DCamera = { position : new Cartesian3(), direction : new Cartesian3(), up : new Cartesian3(), position2D : new Cartesian3(), direction2D : new Cartesian3(), up2D : new Cartesian3(), frustum : new OrthographicOffCenterFrustum() }; var scratch3DTo2DEndCamera = { position : new Cartesian3(), direction : new Cartesian3(), up : new Cartesian3(), frustum : undefined }; var scratch3DTo2DPickPosition = new Cartesian3(); var scratch3DTo2DRay = new Ray(); var scratch3DTo2DToENU = new Matrix4(); var scratch3DTo2DSurfacePoint = new Cartesian3(); function morphFrom3DTo2D(transitioner, duration, ellipsoid) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var camera2D = scratch3DTo2DCamera; if (duration > 0.0) { Cartesian3.clone(Cartesian3.ZERO, camera2D.position); camera2D.position.z = 5.0 * ellipsoid.maximumRadius; Cartesian3.negate(Cartesian3.UNIT_Z, camera2D.direction); Cartesian3.clone(Cartesian3.UNIT_Y, camera2D.up); } else { ellipsoid.cartesianToCartographic(camera.positionWC, scratch3DTo2DCartographic); scene.mapProjection.project(scratch3DTo2DCartographic, camera2D.position); Cartesian3.negate(Cartesian3.UNIT_Z, camera2D.direction); Cartesian3.clone(Cartesian3.UNIT_Y, camera2D.up); var ray = scratch3DTo2DRay; Cartesian3.clone(camera2D.position2D, ray.origin); var rayDirection = Cartesian3.clone(camera.directionWC, ray.direction); var surfacePoint = ellipsoid.scaleToGeodeticSurface(camera.positionWC, scratch3DTo2DSurfacePoint); var toENU = Transforms.eastNorthUpToFixedFrame(surfacePoint, ellipsoid, scratch3DTo2DToENU); Matrix4.inverseTransformation(toENU, toENU); Matrix4.multiplyByPointAsVector(toENU, rayDirection, rayDirection); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, rayDirection, rayDirection); var globe = scene.globe; if (defined(globe)) { var pickedPos = globe.pick(ray, scene, scratch3DTo2DPickPosition); if (defined(pickedPos)) { var height = Cartesian3.distance(camera2D.position2D, pickedPos); pickedPos.x += height; Cartesian3.clone(pickedPos, camera2D.position2D); } } } function updateHeight(camera, height) { camera.position.x = height; } Matrix4.multiplyByPoint(Camera.TRANSFORM_2D, camera2D.position, camera2D.position2D); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, camera2D.direction, camera2D.direction2D); Matrix4.multiplyByPointAsVector(Camera.TRANSFORM_2D, camera2D.up, camera2D.up2D); var frustum = camera2D.frustum; frustum.right = camera2D.position.z * 0.5; frustum.left = -frustum.right; frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); frustum.bottom = -frustum.top; var endCamera = scratch3DTo2DEndCamera; Matrix4.multiplyByPoint(Camera.TRANSFORM_2D_INVERSE, camera2D.position2D, endCamera.position); Cartesian3.clone(camera2D.direction, endCamera.direction); Cartesian3.clone(camera2D.up, endCamera.up); endCamera.frustum = frustum; var complete = complete2DCallback(endCamera); createMorphHandler(transitioner, complete); function completeCallback() { morphPerspectiveToOrthographic(transitioner, duration, camera2D, updateHeight, complete); } morphFrom3DToColumbusView(transitioner, duration, camera2D, completeCallback); } function morphOrthographicToPerspective(transitioner, duration, cameraCV, complete) { var scene = transitioner._scene; var camera = scene.camera; var height = camera.frustum.right - camera.frustum.left; camera.frustum = cameraCV.frustum.clone(); var endFOV = camera.frustum.fov; var startFOV = CesiumMath.RADIANS_PER_DEGREE * 0.5; var d = height * Math.tan(endFOV * 0.5); camera.frustum.far = d / Math.tan(startFOV * 0.5) + 10000000.0; camera.frustum.fov = startFOV; function update(value) { camera.frustum.fov = CesiumMath.lerp(startFOV, endFOV, value.time); camera.position.z = d / Math.tan(camera.frustum.fov * 0.5); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { complete(transitioner); } }); transitioner._currentTweens.push(tween); } function morphFrom2DToColumbusView(transitioner, duration, cameraCV, complete) { duration *= 0.5; var scene = transitioner._scene; var camera = scene.camera; var endPos = Cartesian3.clone(cameraCV.position, scratch3DToCVEndPos); var endDir = Cartesian3.clone(cameraCV.direction, scratch3DToCVEndDir); var endUp = Cartesian3.clone(cameraCV.up, scratch3DToCVEndUp); scene._mode = SceneMode.MORPHING; function morph() { camera.frustum = cameraCV.frustum.clone(); var startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos); var startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir); var startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp); startPos.z = endPos.z; function update(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { complete(transitioner); } }); transitioner._currentTweens.push(tween); } if (transitioner._morphToOrthographic) { morph(); } else { morphOrthographicToPerspective(transitioner, 0.0, cameraCV, morph); } } function morphFrom3DToColumbusView(transitioner, duration, endCamera, complete) { var scene = transitioner._scene; var camera = scene.camera; var startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos); var startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir); var startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp); var endPos = Cartesian3.clone(endCamera.position2D, scratch3DToCVEndPos); var endDir = Cartesian3.clone(endCamera.direction2D, scratch3DToCVEndDir); var endUp = Cartesian3.clone(endCamera.up2D, scratch3DToCVEndUp); function update(value) { columbusViewMorph(startPos, endPos, value.time, camera.position); columbusViewMorph(startDir, endDir, value.time, camera.direction); columbusViewMorph(startUp, endUp, value.time, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera._adjustOrthographicFrustum(true); } var tween = scene.tweens.add({ duration : duration, easingFunction : EasingFunction.QUARTIC_OUT, startObject : { time : 0.0 }, stopObject : { time : 1.0 }, update : update, complete : function() { addMorphTimeAnimations(transitioner, scene, 1.0, 0.0, duration, complete); } }); transitioner._currentTweens.push(tween); } function addMorphTimeAnimations(transitioner, scene, start, stop, duration, complete) { // Later, this will be linear and each object will adjust, if desired, in its vertex shader. var options = { object : scene, property : 'morphTime', startValue : start, stopValue : stop, duration : duration, easingFunction : EasingFunction.QUARTIC_OUT }; if (defined(complete)) { options.complete = function() { complete(transitioner); }; } var tween = scene.tweens.addProperty(options); transitioner._currentTweens.push(tween); } function complete3DCallback(camera3D) { return function(transitioner) { var scene = transitioner._scene; scene._mode = SceneMode.SCENE3D; scene.morphTime = SceneMode.getMorphTime(SceneMode.SCENE3D); destroyMorphHandler(transitioner); var camera = scene.camera; if (transitioner._previousMode !== SceneMode.MORPHING || transitioner._morphCancelled) { transitioner._morphCancelled = false; Cartesian3.clone(camera3D.position, camera.position); Cartesian3.clone(camera3D.direction, camera.direction); Cartesian3.clone(camera3D.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera.frustum = camera3D.frustum.clone(); } var frustum = camera.frustum; if (scene._logDepthBuffer && !(frustum instanceof OrthographicFrustum || frustum instanceof OrthographicOffCenterFrustum)) { frustum.near = 0.1; frustum.far = 10000000000.0; } var wasMorphing = defined(transitioner._completeMorph); transitioner._completeMorph = undefined; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent(transitioner, transitioner._previousMode, SceneMode.SCENE3D, wasMorphing); }; } function complete2DCallback(camera2D) { return function(transitioner) { var scene = transitioner._scene; scene._mode = SceneMode.SCENE2D; scene.morphTime = SceneMode.getMorphTime(SceneMode.SCENE2D); destroyMorphHandler(transitioner); var camera = scene.camera; Cartesian3.clone(camera2D.position, camera.position); camera.position.z = scene.mapProjection.ellipsoid.maximumRadius * 2.0; Cartesian3.clone(camera2D.direction, camera.direction); Cartesian3.clone(camera2D.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); camera.frustum = camera2D.frustum.clone(); var wasMorphing = defined(transitioner._completeMorph); transitioner._completeMorph = undefined; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent(transitioner, transitioner._previousMode, SceneMode.SCENE2D, wasMorphing); }; } function completeColumbusViewCallback(cameraCV) { return function(transitioner) { var scene = transitioner._scene; scene._mode = SceneMode.COLUMBUS_VIEW; scene.morphTime = SceneMode.getMorphTime(SceneMode.COLUMBUS_VIEW); destroyMorphHandler(transitioner); var camera = scene.camera; if (transitioner._previousModeMode !== SceneMode.MORPHING || transitioner._morphCancelled) { transitioner._morphCancelled = false; Cartesian3.clone(cameraCV.position, camera.position); Cartesian3.clone(cameraCV.direction, camera.direction); Cartesian3.clone(cameraCV.up, camera.up); Cartesian3.cross(camera.direction, camera.up, camera.right); Cartesian3.normalize(camera.right, camera.right); } var frustum = camera.frustum; if (scene._logDepthBuffer && !(frustum instanceof OrthographicFrustum || frustum instanceof OrthographicOffCenterFrustum)) { frustum.near = 0.1; frustum.far = 10000000000.0; } var wasMorphing = defined(transitioner._completeMorph); transitioner._completeMorph = undefined; scene.camera.update(scene.mode); transitioner._scene.morphComplete.raiseEvent(transitioner, transitioner._previousMode, SceneMode.COLUMBUS_VIEW, wasMorphing); }; } return SceneTransitioner; });
Fix large billboards during morph from 2D to 3D.
Source/Scene/SceneTransitioner.js
Fix large billboards during morph from 2D to 3D.
<ide><path>ource/Scene/SceneTransitioner.js <ide> var complete = complete3DCallback(camera3D); <ide> createMorphHandler(transitioner, complete); <ide> <del> var startPos = Cartesian3.clone(camera.position, scratch3DToCVStartPos); <del> var startDir = Cartesian3.clone(camera.direction, scratch3DToCVStartDir); <del> var startUp = Cartesian3.clone(camera.up, scratch3DToCVStartUp); <del> <del> var endPos = Cartesian3.fromElements(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, scratch3DToCVEndPos); <del> var endDir = Cartesian3.negate(Cartesian3.UNIT_Z, scratch3DToCVEndDir); <del> var endUp = Cartesian3.clone(Cartesian3.UNIT_Y, scratch3DToCVEndUp); <del> <del> var startRight = camera.frustum.right; <del> var endRight = endPos.z * 0.5; <del> <del> function update(value) { <del> columbusViewMorph(startPos, endPos, value.time, camera.position); <del> columbusViewMorph(startDir, endDir, value.time, camera.direction); <del> columbusViewMorph(startUp, endUp, value.time, camera.up); <del> Cartesian3.cross(camera.direction, camera.up, camera.right); <del> Cartesian3.normalize(camera.right, camera.right); <del> <del> var frustum = camera.frustum; <del> frustum.right = CesiumMath.lerp(startRight, endRight, value.time); <del> frustum.left = -frustum.right; <del> frustum.top = frustum.right * (scene.drawingBufferHeight / scene.drawingBufferWidth); <del> frustum.bottom = -frustum.top; <del> <del> camera.position.z = 2.0 * scene.mapProjection.ellipsoid.maximumRadius; <del> } <del> <ide> var morph; <ide> if (transitioner._morphToOrthographic) { <ide> morph = function() { <ide> } <ide> <ide> if (duration > 0.0) { <del> var tween = scene.tweens.add({ <add> scene._mode = SceneMode.SCENE2D; <add> camera.flyTo({ <ide> duration : duration, <del> easingFunction : EasingFunction.QUARTIC_OUT, <del> startObject : { <del> time : 0.0 <del> }, <del> stopObject : { <del> time : 1.0 <del> }, <del> update : update, <add> destination : Cartesian3.fromDegrees(0.0, 0.0, 5.0 * ellipsoid.maximumRadius, ellipsoid, scratch3DToCVEndPos), <ide> complete : function() { <ide> scene._mode = SceneMode.MORPHING; <ide> morph(); <ide> } <ide> }); <del> transitioner._currentTweens.push(tween); <ide> } else { <ide> morph(); <ide> }
JavaScript
mit
3c10affcc77fbef2457eb3d0812a686c62c679cd
0
Tiny-Giant/Stack-Exchange-Editor-Toolkit
// ==UserScript== // @name Stack-Exchange-Editor-Toolkit // @author Cameron Bernhardt (AstroCB) // @developer Jonathan Todd (jt0dd) // @developer sathyabhat // @contributor Unihedron // @contributor Tiny Giant // @contributor Mogsdad // @grant none // @license MIT // @namespace http://github.com/AstroCB // @version 1.5.2.33 // @description Fix common grammar/usage annoyances on Stack Exchange posts with a click // @include /^https?://\w*.?(stackoverflow|stackexchange|serverfault|superuser|askubuntu|stackapps)\.com/(questions|posts|review)/(?!tagged|new).*/ // ==/UserScript== (function() { "use strict"; function extendEditor(root) { var App = {}; // Place edit items here App.items = {}; App.originals = {}; // Place selected jQuery items here App.selections = {}; // Place "global" app data here App.globals = {}; // Place "helper" functions here App.funcs = {}; // True to display counts and / or rule names in Edit Summary App.globals.showCounts = false; App.globals.showRules = false; //Preload icon alt var SEETicon = new Image(); SEETicon.src = '//i.imgur.com/d5ZL09o.png'; App.globals.root = root; App.globals.spacerHTML = '<li class="wmd-spacer wmd-spacer3" id="wmd-spacer3" style="left: 400px !important;"></li>'; App.globals.reasons = {}; App.globals.replacedStrings = { "auto": [], "quote": [], "inline": [], "block": [], "lsec": [], "links": [], "tags": [] }; App.globals.placeHolders = { "auto": "_xAutoxInsertxTextxPlacexHolder_", "quote": "_xBlockxQuotexPlacexHolderx_", "inline": "_xCodexInlinexPlacexHolderx_", "block": "_xCodexBlockxPlacexHolderx_", "lsec": "_xLinkxSectionxPlacexHolderx_", "links": "_xLinkxPlacexHolderx_", "tags": "_xTagxPlacexHolderx_" }; App.globals.placeHolderChecks = { "auto": /_xAutoxInsertxTextxPlacexHolder_/gi, "quote": /_xBlockxQuotexPlacexHolderx_/gi, "inline": /_xCodexInlinexPlacexHolderx_/gi, "block": /_xCodexBlockxPlacexHolderx_/gi, "lsec": /_xLinkxSectionxPlacexHolderx_/gi, "links": /_xLinkxPlacexHolderx_/gi, "tags": /_xTagxPlacexHolderx_/gi }; App.globals.checks = { // https://regex101.com/r/cI6oK2/1 automatically inserted text "auto": /[^]*\<\!\-\- End of automatically inserted text \-\-\>/g, // https://regex101.com/r/fU5lE6/1 blockquotes "quote": /^\>(?:(?!\n\n)[^])+/gm, // https://regex101.com/r/lL6fH3/1 single-line inline code "inline": /`[^`\n]+`/g, // https://regex101.com/r/eC7mF7/1 code blocks and multiline inline code. "block": /`[^`]+`|(?:(?:[ ]{4}|[ ]{0,3}\t).+(?:[\r\n]?(?!\n\S)(?:[ ]+\n)*)+)+/g, // https://regex101.com/r/tZ4eY3/7 link-sections "lsec": /(?: (?:\[\d\]): \w*:+\/\/.*\n*)+/g, // https://regex101.com/r/tZ4eY3/20 links and pathnames "links": /\[[^\]\n]+\](?:\([^\)\n]+\)|\[[^\]\n]+\])|(?:\/\w+\/|.:\\|\w*:\/\/|\.+\/[./\w\d]+|(?:\w+\.\w+){2,})[./\w\d:/?#\[\]@!$&'()*+,;=\-~%]*/g, // https://regex101.com/r/bF0iQ0/1 tags and html comments "tags": /\<[\/a-z]+\>|\<\!\-\-[^>]+\-\-\>/g }; App.globals.checksr = (function(o1){ var o2 = {}; var k= Object.keys(o1); for(var i = k.length-1; i >= 0; --i) o2[k[i]] = o1[k[i]]; return o2; })(App.globals.checks); // Assign modules here App.pipeMods = {}; // Define order in which mods affect here App.globals.order = ["omit", "codefix", "edit", "diff", "replace", "output"]; // Define edit rules App.edits = { // All caps noneedtoyell: { expr: /^((?=.*[A-Z])[^a-z]*)$/g, replacement: function(input) { return input.trim().substr(0, 1).toUpperCase() + input.trim().substr(1).toLowerCase(); }, reason: 'no need to yell' }, so: { expr: /\bstack\s*overflow\b/gi, replacement: "Stack Overflow", reason: "'Stack Overflow' is the legal name" }, se: { expr: /\bstack\s*exchange\b/gi, replacement: "Stack Exchange", reason: "'Stack Exchange' is the legal name" }, expansionSO: { expr: /([^\b\w.]|^)SO\b/g, replacement: "$1Stack Overflow", reason: "'Stack Overflow' is the legal name" }, expansionSE: { expr: /([^\b\w.]|^)SE\b/g, replacement: "$1Stack Exchange", reason: "'Stack Exchange' is the legal name" }, javascript: { expr: /([^\b\w.]|^)(javascript|js|java script)\b/gi, replacement: "$1JavaScript", reason: "trademark capitalization" }, jsfiddle: { expr: /\bjsfiddle\b/gi, replacement: "JSFiddle", reason: "trademark capitalization" }, jquery: { expr: /\bjque?rr?y\b/gi, // jqury, jquerry, jqurry... ~600 spelling mistakes replacement: "jQuery", reason: "trademark capitalization" }, angular: { expr: /\bangular(?:js)?\b/gi, replacement: "AngularJS", reason: "trademark capitalization" }, x_html: { expr: /(?:[^\b\w.]|^)(g|ht|x|xht)ml\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, css: { expr: /(?:[^\b\w.]|^)css\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, json: { expr: /(?:[^\b\w.]|^)json\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ajax: { expr: /\bajax\b/g, // Leave "Ajax" alone. See https://github.com/AstroCB/Stack-Exchange-Editor-Toolkit/issues/45 replacement: "AJAX", reason: "acronym capitalization" }, php: { expr: /(?:[^\b\w.]|^)php\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, voting: { expr: /\b(down|up)\Wvot/gi, replacement: "$1vote", reason: "the proper spelling (despite the tag name) is '$1vote' (one word)" }, c: { expr: /(?:[^\b\w.]|^)c\b(?:#|\+\+)?/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, java: { expr: /([^\b\w.]|^)java\b/gi, replacement: "$1Java", reason: "trademark capitalization" }, sql: { expr: /(?:[^\b\w.]|^)sql\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, sqlite: { expr: /\bsqlite\s*([0-9]*)\b/gi, replacement: "SQLite $2", reason: "trademark capitalization" }, android: { expr: /\bandroid\b/gi, replacement: "Android", reason: "trademark capitalization" }, oracle: { expr: /\boracle\b/gi, replacement: "Oracle", reason: "trademark capitalization" }, windows: { // https://regex101.com/r/jF9zK1/6 expr: /\b(?:win|windows)(?:\s+(2k|[0-9.]+|ce|me|nt|xp|vista|server))?\b/gi, replacement: function(match, ver) { ver = !ver ? '' : ver.replace(/ce/i, ' CE') .replace(/me/i, ' ME') .replace(/nt/i, ' NT') .replace(/xp/i, ' XP') .replace(/2k/i, ' 2000') .replace(/vista/i, ' Vista') .replace(/server/i, ' Server'); return 'Windows' + ver; }, reason: "trademark capitalization" }, linux: { expr: /\blinux\b/gi, replacement: "Linux", reason: "trademark capitalization" }, wordpress: { expr: /\bwordpress\b/gi, replacement: "WordPress", reason: "trademark capitalization" }, google: { expr: /\bgoogle\b/gi, replacement: "Google", reason: "trademark capitalization" }, mysql: { expr: /\bmysql\b/gi, replacement: "MySQL", reason: "trademark capitalization" }, nodejs: { expr: /\bnode\.?js\b/gi, replacement: "Node.js", reason: "trademark capitalization" }, apache: { expr: /\bapache\b/gi, replacement: "Apache", reason: "trademark capitalization" }, git: { expr: /([^\b\w.]|^)git\b/gi, replacement: "$1Git", reason: "trademark capitalization" }, github: { expr: /\bgithub\b/gi, replacement: "GitHub", reason: "trademark capitalization" }, facebook: { expr: /\bfacebook\b/gi, replacement: "Facebook", reason: "trademark capitalization" }, python: { expr: /\bpython\b/gi, replacement: "Python", reason: "trademark capitalization" }, urli: { expr: /\b(ur[li])\b/gi, replacement: function(match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ios: { expr: /\bios\b/gi, replacement: "iOS", reason: "trademark capitalization" }, iosnum: { expr: /\bios([0-9])\b/gi, replacement: "iOS $1", reason: "trademark capitalization" }, ubuntu: { expr: /\b[uoa]*b[uoa]*[tn][oua]*[tnu][oua]*\b/gi, replacement: "Ubuntu", reason: "trademark capitalization" }, vbnet: { // https://regex101.com/r/bB9pP3/4 expr: /(?:vb|asp|\s+|\()(?:\.net|\s*[0-9]+)\s*(?:framework|core)?/gi, replacement: function(str) { return str.replace(/vb/i, 'VB') .replace(/asp/i, 'ASP') .replace(/net/i, 'NET') .replace(/framework/i, 'Framework') .replace(/core/i, 'Core'); }, reason: "trademark capitalization" }, asp: { expr: /([^\b\w.]|^)asp/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, regex: { expr: /\bregex(p)?\b/gi, replacement: "RegEx$1", reason: "trademark capitalization" }, postgresql: { expr: /\bpostgres(ql|s)?\b/gi, replacement: "PostgreSQL", reason: "trademark capitalization" }, paypal: { expr: /\bpaypal\b/gi, replacement: "PayPal", reason: "trademark capitalization" }, pdf: { expr: /([^\b\w.]|^)pdf(s)?/gi, replacement: "$1PDF$2", reason: "trademark capitalization" }, api: { expr: /([^\b\w.]|^)api(s)?\b/gi, replacement: "$1API$2", reason: "acronym capitalization" }, ssl: { expr: /(?:[^\b\w.]|^)ssl\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, tomcat: { expr: /\btomcat([0-9.]*)/gi, replacement: "Tomcat$1", reason: "trademark capitalization" }, npm: { expr: /\bnpm(s)?\b/g, replacement: "NPM$1", reason: "acronym capitalization" }, succeed: { expr: /\b(s)uc[cs]?ee?d(ed|s)?\b/gi, replacement: "$1ucceed$2", reason: "grammar and spelling" }, ftp: { expr: /(?:[^\b\w.]|^)[st]?ftps?\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ipa: { expr: /(?:[^\b\w.]|^)ipa\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, avl: { expr: /(?:[^\b\w.]|^)avl\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, netbeans: { expr: /\b(netbeans|net-beans|net beans)\b/gi, replacement: "NetBeans", reason: "trademark capitalization" }, cli_cgi: { expr: /(?:[^\b\w.]|^)c[lg]i\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, nginx: { expr: /\bnginx\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, dll: { expr: /(?:[^\b\w.]|^)dll\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, source: { expr: /\b(s)orce(s|d)?\b/gi, replacement: "$1ource$2", reason: "grammar and spelling" }, standardize: { // https://regex101.com/r/vN7pM0/1 expr: /\b(s)tandari([sz](?:e|es|ed|ation))\b/gi, replacement: "$1tandardi$2", reason: "grammar and spelling" }, different: { // https://regex101.com/r/vN7pM0/1 expr: /\b(d)iff?e?ren(t|ce)\b/gi, replacement: "$1ifferen$2", reason: "grammar and spelling" }, personally: { // https://regex101.com/r/oL9aM1/2 expr: /\b(p)erso(?:nl|nl|nal)(ly)?\b/gi, replacement: "$1ersonal$2", reason: "grammar and spelling" }, problem: { // https://regex101.com/r/yA8jM7/1 expr: /\b(p)(?:or|ro)b(?:le|el)m(s)?\b/gi, replacement: "$1roblem$2", reason: "grammar and spelling" }, written: { expr: /\b(w)riten\b/gi, replacement: "$1ritten", reason: "grammar and spelling" }, maybe: { expr: /\b(m)aby\b/gi, replacement: "$1aybe", reason: "grammar and spelling" }, pseudo: { expr: /\b(p)suedo\b/gi, replacement: "$1seudo", reason: "grammar and spelling" }, // Noise reduction editupdate: { // https://regex101.com/r/tT2pK6/2 expr: /(?!(?:edit|update)\w*\s*[^:]*$)(?:^\**)(edit|update)\w*(\s*#?[0-9]+)?:?(?:\**):?/gmi, replacement: "", reason: "noise reduction" }, hello: { // TODO: Update badsentences (new) to catch everything hello (old) did. expr: /(?:^|\s)(hi\s+guys|hi|hello|good\s(?:evening|morning|day|afternoon))(?:\.|!|\ )/gmi, replacement: "", reason: "noise reduction" }, badwords: { expr: /[^\n.!?:]*\b(?:th?anks?|th(?:an)?x|tanx|folks?|ki‌nd(‌?:est|ly)|first\s*question)\b[^,.!?\n]*[,.!?]*/gi, replacement: "", reason: "noise reduction" }, badphrases: { expr: /[^\n.!?:]*(?:h[ea]lp|hope|appreciate|pl(?:ease|z|s))[^.!?\n]*(?:helps?|appreciated?)[^,.!?\n]*[,.!?]*/gi, replacement: "", reason: "noise reduction" }, imnew: { expr: /(?! )[\w\s]*\bi[' ]?a?m +(?:kinda|really) *new\w* +(?:to|in) *\w* *(?:and|[;,.!?])? */gi, replacement: "", reason: "noise reduction" }, salutations: { expr: /[\r\n]*(regards|cheers?),?[\t\f ]*[\r\n]?\w*\.?/gi, replacement: "", reason: "noise reduction" }, sorry4english: { // https://regex101.com/r/pG3oD6/1 expr: /(?:^|\s)[^.!\n\r]*(sorry).*?(english).*?(?:[.! \n\r])/gmi, replacement: "", reason: "noise reduction" }, // Grammar and spelling apostrophe_d: { expr: /\b(he|she|who|you)[^\w']*(d)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_ll: { expr: /\b(they|what|who|you)[^\w']*(ll)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_re: { expr: /\b(they|what|you)[^\w']*(re)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_s: { expr: /\b(he|she|that|there|what|where)[^\w']*(s)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_t: { expr: /\b(aren|can|didn|doesn|don|hasn|haven|isn|mightn|mustn|shan|shouldn|won|wouldn)[^\w']*(t)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, doesn_t: { // https://regex101.com/r/sL0uO9/1 expr: /\b(d)ose?n'?t\b/gi, replacement: "$1oesn't", reason: "grammar and spelling" }, doesn_t_work: { // >4K instances of this (Oct 2015) expr: /\b(d)oesn\'t (work|like|think|want|put|save|load|get|help|make)s\b/gi, replacement: "$1oesn't $2", reason: "grammar and spelling" }, prolly: { expr: /\b(p)roll?y\b/gi, replacement: "$1robably", reason: "grammar and spelling" }, keyboard: { expr: /\b(k)ey?boa?rd\b/gi, replacement: "$1eyboard", reason: "grammar and spelling" }, i: { // https://regex101.com/r/uO7qG0/1 expr: /\bi('|\b)(?!.e.)/g, // i or i-apostrophe replacement: "I", reason: "grammar and spelling" }, im: { expr: /\bi ?m\b/gi, replacement: "I'm", reason: "grammar and spelling" }, ive: { expr: /\bive\b/gi, replacement: "I've", reason: "grammar and spelling" }, ur: { expr: /\bur\b/gi, replacement: "your", // May also be "you are", but less common on SO reason: "grammar and spelling" }, u: { expr: /\bu\b/gi, replacement: "you", reason: "grammar and spelling" }, gr8: { expr: /\bgr8\b/gi, replacement: "great", reason: "grammar and spelling" }, allways: { expr: /\b(a)llways\b/gi, replacement: "$1lways", reason: "grammar and spelling" }, expect: { expr: /\b(e)spect(s)?\b/gi, replacement: "$1xpect$2", reason: "grammar and spelling" }, employe: { expr: /\b(e)mploye\b/gi, replacement: "$1mployee", reason: "grammar and spelling" }, retrieve: { expr: /\b(r)etreive(d)?\b/gi, replacement: "$1etrieve$2", reason: "grammar and spelling" }, firefox: { expr: /\bfire?fox\b/gi, replacement: "Firefox", reason: "trademark capitalization" }, success: { // https://regex101.com/r/hK2vG4/1 expr: /\b(s)ucc?ess?(ful|fully)?l?\b/gi, replacement: "$1uccess$2", reason: "grammar and spelling" }, safari: { expr: /\bsafari\b/gi, replacement: "Safari", reason: "trademark capitalization" }, chrome: { expr: /\bchrome\b/gi, replacement: "Chrome", reason: "trademark capitalization" }, anyones: { expr: /\b(a)nyones\b/gi, replacement: "$1nyone's", reason: "grammar and spelling" }, length: { expr: /\b(l)en(?:gh?t|th)\b/gi, replacement: "$1ength", reason: "grammar and spelling" }, height: { expr: /\b(h)(?:ei|i|ie)(?:gt|th|ghth|gth)\b/gi, replacement: "$1eight", reason: "grammar and spelling" }, width: { expr: /\b(w)idh?t\b/gi, replacement: "$1idth", reason: "grammar and spelling" }, centered: { expr: /\b(c)ent(?:red|erd)\b/gi, replacement: "$1entered", reason: "grammar and spelling" }, center: { expr: /\b(c)entre\b/gi, // "Centre" is a word, however in most cases on SO "center" is meant replacement: "$1enter", reason: "grammar and spelling" }, aint_isnt: { expr: /\bain't\b/gi, replacement: "isn't", reason: "grammar and spelling" }, coordinates: { expr: /\b(c)ordinate(s|d)?\b/gi, replacement: "$1oordinate$2", reason: "grammar and spelling" }, argument: { expr: /\b(a)rguement(s)?\b/gi, replacement: "$1rgument$2", reason: "grammar and spelling" }, gui: { expr: /([^\b\w.]|^)gui(s)?\b/gi, replacement: "$1GUI$2", reason: "acronym capitalization" }, iterate: { // https://regex101.com/r/iL6bV3/1 expr: /\b(i)(?:tter|tar)at(e[ds]?|ing|ion|ions)\b/gi, replacement: "$1terat$2", reason: "grammar and spelling" }, below: { expr: /\b(b)ellow\b/gi, // "Bellow" is a word, but extremely uncommon on StackOverflow.com. replacement: "$1elow", reason: "grammar and spelling" }, encrypt: { expr: /\b(en|de)cript(s|ing)?\b/gi, replacement: "$1crypt$2", reason: "grammar and spelling" }, gnu: { expr: /\bgnu\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, gcc: { expr: /(?:[^\b\w.]|^)gcc\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, stp: { expr: /(?:[^\b\w.]|^)stp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, tcp: { expr: /(?:[^\b\w.]|^)tcp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, wpf: { expr: /(?:[^\b\w.]|^)wpf\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, http: { expr: /(?:[^\b\w.]|^)https?\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, woff: { expr: /(?:[^\b\w.]|^)woff\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ttf: { expr: /(?:[^\b\w.]|^)ttf\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ipv_n: { expr: /\bip(v[46])?\b/gi, replacement: "IP$1", reason: "acronym capitalization" }, fq_dn_s: { // FQDN, DN, DNS expr: /(?:[^\b\w.]|^)(?:fq)?dns?\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, icmp: { expr: /\bicmp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, rsvp: { expr: /\brsvp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, snmp: { expr: /\bsnmp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, cpu: { expr: /\bcpu(s)?\b/gi, replacement: "CPU$1", reason: "acronym capitalization" }, rss: { expr: /(?:[^\b\w.]|^)rss?\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, mvc: { expr: /(?:[^\b\w.]|^)mvc\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, mvn: { expr: /(?:[^\b\w.]|^)mvn\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, ascii: { expr: /([^\b\w.]|^)ascii?\b/gi, replacement: "$1ASCII", reason: "acronym capitalization" }, maven: { expr: /\bmaven\b/gi, replacement: "Maven", reason: "trademark capitalization" }, youtube: { expr: /\byoutube\b/gi, replacement: "YouTube", reason: "trademark capitalization" }, amazon: { // https://regex101.com/r/dR0pJ7/1 expr: /\b(amazon(?: )?(?:redshift|web services|cloudfront|console)?)((?: )?(?:ec2|aws|s3|rds|sqs|iam|elb|emr|vpc))?\b/gi, replacement: function(str,titlecase,uppercase) { var fixed = titlecase.toTitleCase() + (uppercase ? uppercase.toUpperCase() : ''); return fixed; }, reason: "trademark capitalization" }, zend: { expr: /\bzend((?: )?(?:framework|studio|guard))?\b/gi, //replacement: String.toTitleCase, // Doesn't work like built-in toUpperCase, returns 'undefined'. Load order? replacement: function(str,prod) { return str.toTitleCase(); }, reason: "trademark capitalization" }, formatting: { expr: /\b(f)ormating\b/gi, replacement: "$1ormatting", reason: "grammar and spelling" }, process: { expr: /\b(p)roces(es|ed)?\b/gi, replacement: "$1rocess$2", reason: "grammar and spelling" }, programming: { expr: /\b(p)rogram(ing|ed|er)\b/gi, replacement: "$1rogramm$2", reason: "grammar and spelling" }, bear_with_me: { expr: /\b(b)are (with me|it|in mind)\b/gi, replacement: "$1ear $2", reason: "grammar and spelling" }, weird: { expr: /\b(w)ierd(ness|ly)\b/gi, replacement: "$1eird$2", reason: "grammar and spelling" }, believe: { expr: /\b(b)eleive(r|s|d)?\b/gi, replacement: "$1elieve$2", reason: "grammar and spelling" }, piece: { expr: /\b(p)eice(s|d)?\b/gi, replacement: "$1iece$2", reason: "grammar and spelling" }, sample: { expr: /\b(s)maple(s|d)?\b/gi, replacement: "$1ample$2", reason: "grammar and spelling" }, twitter: { expr: /\btwitter\b/gi, replacement: "Twitter", reason: "trademark capitalization" }, bootstrap: { // "bootstrap" is also a general computing term, so expect some false positives expr: /\bbootst?r?ap\b/gi, replacement: "Bootstrap", reason: "trademark capitalization" }, apple: { expr: /\bapple\b/g, replacement: "Apple", reason: "trademark capitalization" }, iphone: { expr: /\biph?one?\b/gi, replacement: "iPhone", reason: "trademark capitalization" }, google_apps_script: { expr: /\bgoogle ?(?:apps?)? ?script\b/gi, replacement: "Google Apps Script", reason: "trademark capitalization" }, // From Peter Mortensen list (http://pvm-professionalengineering.blogspot.de/2011/04/word-list-for-editing-stack-exchange.html) ie: { // http://english.stackexchange.com/questions/30106/can-i-start-a-sentence-with-i-e expr: /\b(i|I)e\b/g, // Careful here; IE is Internet Explorer replacement: "$1.e.", reason: "grammar and spelling" }, eg: { expr: /\b(e)g\b/gi, replacement: "$1.g.", reason: "grammar and spelling" }, unfortunately: { expr: /\b(u)nfortu?na?tly\b/gi, replacement: "$1nfortunately", reason: "grammar and spelling" }, whether: { expr: /\b(w)h?eth?er\b/gi, replacement: "$1hether", reason: "grammar and spelling" }, through: { // https://regex101.com/r/gQ0dZ1/4 expr: /\b(t)(?:hru|rough|hroug)\b/gi, replacement: "$1hrough", reason: "grammar and spelling" }, throughout: { expr: /\b(t)(?:hruout|roughout)\b/gi, replacement: "$1hroughout", reason: "grammar and spelling" }, breakthrough: { expr: /\b(b)reak\s+through(s)?\b/gi, replacement: "$1reakthrough$2", reason: "grammar and spelling" }, though: { expr: /\b(t)(?:ho|hou|hogh)\b/gi, replacement: "$1hough", reason: "grammar and spelling" }, although: { expr: /\b(a)l(?:tho|thou|thogh|tough)\b/gi, replacement: "$1lthough", reason: "grammar and spelling" }, thought: { expr: /\b(t)r?ought(s)?\b/gi, replacement: "$1hough$2", reason: "grammar and spelling" }, throwing: { expr: /\b(t)hroughing\b/gi, // Peter says this is "thoroughly", but a survey of SO questions indicates "throwing" replacement: "$1hrowing", reason: "grammar and spelling" }, a_lot: { expr: /\b(a)lot\b/gi, replacement: "$1 lot", reason: "grammar and spelling" }, one_r_two_r: { expr: /\b(refe|prefe|occu)r(ed|ing)\b/gi, replacement: "$1rr$2", reason: "grammar and spelling" }, preferably: { expr: /\b(p)referrably\b/gi, replacement: "$1referably", reason: "grammar and spelling" }, command_line: { expr: /\b(c)ommandline\b/gi, replacement: "$1ommand-line", reason: "grammar and spelling" }, benefits: { expr: /\b(b)enifits\b/gi, replacement: "$1enefits", reason: "grammar and spelling" }, authorization: { expr: /\b(a)uth\b/gi, // This may be too ambiguous, could also mean "authentication" replacement: "$1uthorization", reason: "grammar and spelling" }, persistent: { expr: /\b(p)ersistan(t|ce)\b/gi, replacement: "$1ersisten$2", reason: "grammar and spelling" }, _ibility: { expr: /\b(comp|incomp|access)abilit(y|ies)\b/gi, replacement: "$1ibilit$2", reason: "grammar and spelling" }, separate: { expr: /\b(s)epe?rate?(d|ly|s)?\b/gi, replacement: "$1eparate$2", reason: "grammar and spelling" }, separation: { expr: /\b(s)eperation(s)?\b/gi, replacement: "$1eparation$2", reason: "grammar and spelling" }, definite: { expr: /\b(d)efin(?:ate?|ite?|al|te?)(ly)?\b/gi, // Catches correct spelling, too. replacement: "$1efinite$2", reason: "grammar and spelling" }, definitive: { expr: /\b(d)efina?tive(ly)?\b/gi, replacement: "$1efinitive$2", reason: "grammar and spelling" }, independent: { expr: /\b(i)ndependant(ly)?\b/gi, replacement: "$1ndependent$2", reason: "grammar and spelling" }, recommend: { // https://regex101.com/r/pP9lB7/1 expr: /\b(r)ecomm?[ao]nd(ation)?\b/gi, replacement: "$1ecommend$2", reason: "grammar and spelling" }, compatibility: { expr: /\b(c)ompatability\b/gi, replacement: "$1ompatibility$2", reason: "grammar and spelling" }, ps: { expr: /\bps\b/g, replacement: "PS", reason: "grammar and spelling" }, ok: { expr: /\bok\b/g, replacement: "OK", reason: "grammar and spelling" }, etc: { expr: /\betc\b/g, replacement: "etc.", reason: "grammar and spelling" }, back_end: { // Interesting fact: backend 3x more common than back-end expr: /\b(b)ackend\b/g, replacement: "$1ack-end", reason: "grammar and spelling" }, front_end: { expr: /\b(f)rontend\b/g, replacement: "$1ront-end", reason: "grammar and spelling" }, data_type: { expr: /\b(d)atatype\b/g, replacement: "$1ata type", reason: "grammar and spelling" }, allotted: { expr: /\b(a)l+ot+ed\b/g, replacement: "$1llotted", reason: "grammar and spelling" }, every_time: { expr: /\b(e)ve?rytime\b/g, replacement: "$1very time", reason: "grammar and spelling" }, straightforward: { expr: /\b(s)traig?h?t[ -]forward\b/g, replacement: "$1traightforward", reason: "grammar and spelling" }, preceding: { expr: /\b(p)receeding\b/gi, replacement: "$1receding", reason: "grammar and spelling" }, no_one: { expr: /\b(n)o-?one\b/gi, replacement: "$1o one", reason: "grammar and spelling" }, de_facto: { expr: /\b(d)e-?facto\b/gi, replacement: "$1e facto", reason: "grammar and spelling" }, accommodate: { // https://regex101.com/r/cL3mD9/1 expr: /\b(a)(?:c+om|com+)odate\b/gi, replacement: "$1ccommodate", reason: "grammar and spelling" }, matlab: { expr: /([^\b\w.]|^)math?lab\b/gi, replacement: "$1MATLAB", reason: "trademark capitalization" }, internet: { expr: /\binternet\b/g, replacement: "Internet", reason: "trademark capitalization" }, web_services: { expr: /\bweb services\b/g, replacement: "Web services", reason: "trademark capitalization" }, kind_of: { expr: /\b(k)inda\b/gi, replacement: "$1ind of", reason: "grammar and spelling" }, want_to: { expr: /\b(w)ann?a\b/gi, replacement: "$1ant to", reason: "grammar and spelling" }, sort_of: { expr: /\b(s)orta\b/gi, replacement: "$1ort of", reason: "grammar and spelling" }, got_to: { // https://regex101.com/r/rK6xR5/1 expr: /\b(have\s+)?(g)otta\b/gi, replacement: "$1$2ot to", reason: "grammar and spelling" }, dont_know: { // https://regex101.com/r/rK6xR5/1 expr: /\b(d)[uo]nn?o\b/gi, replacement: "$1on't know", reason: "grammar and spelling" }, going_to: { expr: /\b(g)[ou]nn?a\b/gi, replacement: "$1oing to", reason: "grammar and spelling" }, // Punctuation & Spacing come last firstcaps: { // https://regex101.com/r/qR5fO9/18 // This doesn't work quite right, because is finds all sentences, not just ones needing caps. //expr: /(?:(?!\n\n)[^\s.!?]+[ ]*)+([.!?])*[ ]*/g, expr: /((?!\n\n)[A-z](?:(?!\n\n)[^?.!A-Z])+(?:\.[A-z][^?.!A-Z]+)*([?.!])?)/gm, replacement: function(str, endpunc) { if (str === "undefined") return str; // MUST match str, or gets counted as a change. // https://regex101.com/r/bL9xD7/1 find and capitalize first letter return str.replace(/^(\W*)([a-z])(.*)/g, function(sentence, pre, first, post) { if (!pre) pre = ''; if (!post) post = ''; var update = pre + first.toUpperCase() + post; // + (!endpunc && /\w/.test(post.substr(-1)) ? '.' : ''); return update; }); }, reason: "caps at start of sentences" }, multiplesymbols: { // https://regex101.com/r/bE9zM6/1 expr: /([^\w\s*#.\-_+])\1{1,}/g, replacement: "$1", reason: "punctuation & spacing" }, spacesbeforesymbols: { expr: /[ \t]*(?:([,!?;:](?!\)|\d)|[ \t](\.))(?=\s))[ \t]*/g, // https://regex101.com/r/vS3dS3/6 replacement: "$1 ", reason: "punctuation & spacing" }, multiplespaces: { // https://regex101.com/r/hY9hQ3/1 expr: /[ ]{2,}(?!\n)/g, replacement: " ", reason: "punctuation & spacing" }, blanklines: { expr: /(?:\s*[\r\n]){3,}/gm, replacement: "\n\n", reason: "punctuation & spacing" }, endblanklines: { expr: /[\s\r\n]+$/g, replacement: "", reason: "punctuation & spacing" }, // The title says it all thetitlesaysitall: { // https://regex101.com/r/bX1qB4/3 expr: /(?:the )?title says it all/gi, replacement: function(){ return '"' + App.selections.title.val() + '" says it all'; }, reason: "the title says it all" } }; // This is where the magic happens: this function takes a few pieces of information and applies edits to the post with a couple exceptions App.funcs.fixIt = function(input, expression, replacement, reasoning) { // If there is nothing to search, exit if (!input) return false; // Scan the post text using the expression to see if there are any matches var matches = input.match(expression); if (!matches) return false; var count = 0; // # replacements to do input = input.replace(expression, function(before){ var after = before.replace(expression, replacement); if(after !== before) ++count; return after; }); return count > 0 ? { reason: reasoning, fixed: String(input).trim(), count: count } : false; }; App.funcs.applyListeners = function() { // Removes default Stack Exchange listeners; see https://github.com/AstroCB/Stack-Exchange-Editor-Toolkit/issues/43 function removeEventListeners(e) { if (e.which === 13) { if (e.metaKey || e.ctrlKey) { // CTRL/CMD + Enter -> Activate the auto-editor App.selections.buttonFix.click(); } else { // It's possible to remove the event listeners, because of the way outerHTML works. this.outerHTML = this.outerHTML; App.funcs.fixEvent(); } } } // Tags box App.selections.tagField.keydown(removeEventListeners); // Edit summary box App.selections.summary.keydown(removeEventListeners); }; // Populate or refresh DOM selections App.funcs.popSelections = function() { App.selections.redoButton = App.globals.root.find('[id^="wmd-redo-button"]'); App.selections.body = App.globals.root.find('[id^="wmd-input"]'); App.selections.title = App.globals.root.find('[class*="title-field"]'); App.selections.summary = App.globals.root.find('[id^="edit-comment"], .edit-comment'); App.selections.tagField = App.globals.root.find(".tag-editor"); App.selections.submitButton = App.globals.root.find('[id^="submit-button"]'); App.selections.helpButton = App.globals.root.find('[id^="wmd-help-button"]'); App.selections.editor = App.globals.root.find('.post-editor'); App.selections.preview = App.globals.root.find('.wmd-preview'); App.selections.previewMenu = App.globals.root.find('.preview-options').append('&nbsp;&nbsp;'); if(!App.selections.previewMenu.length) { App.selections.previewMenu = $('<div class="preview-options post-menu" style="margin-top:5px;margin-bottom:8px;"/>').insertBefore(App.selections.preview); var previewToggleText = App.selections.preview.is(':visible') ? 'hide preview' : 'show preview'; App.selections.previewToggle = $('<a href="javascript:void(0)" class="hide-preview" style="margin-left:-2px;">' + previewToggleText + '</a>').click(App.funcs.togglePreview).appendTo(App.selections.previewMenu); App.selections.previewMenu.append('&nbsp;&nbsp;'); } else { App.selections.previewToggle = App.globals.root.find('.hide-preview').off('click').attr('href','javascript:void(0)').click(App.funcs.togglePreview); } App.selections.diffToggle = $('<a href="javascript:void(0)" class="hide-preview" style="margin-left:-2px;">show diff</a>').click(App.funcs.toggleDiff).appendTo(App.selections.previewMenu); App.selections.diff = $('<div class="wmd-preview"/>').hide().appendTo(App.selections.editor); }; App.funcs.showPreview = function() { App.selections.diff.hide(); App.selections.diffToggle.text('show diff'); App.selections.preview.show(); App.selections.previewToggle.text('hide preview'); } App.funcs.showDiff = function() { App.selections.preview.hide(); App.selections.previewToggle.text('show preview'); App.selections.diff.show(); App.selections.diffToggle.text('hide diff'); } App.funcs.togglePreview = function() { App.selections.diff.hide(); App.selections.diffToggle.text('show diff'); if(/hide/.test(App.selections.previewToggle.text())) return App.selections.previewToggle.text('show preview'), App.selections.preview.toggle(), true; if(/show/.test(App.selections.previewToggle.text())) return App.selections.previewToggle.text('hide preview'), App.selections.preview.toggle(), true; } App.funcs.toggleDiff = function() { App.selections.preview.hide(); App.selections.previewToggle.text('show preview'); if(/hide/.test(App.selections.diffToggle.text())) return App.selections.diffToggle.text('show diff'), App.selections.diff.toggle(), true; if(/show/.test(App.selections.diffToggle.text())) return App.selections.diffToggle.text('hide diff'), App.selections.diff.toggle(), true; } // Populate edit item sets from DOM selections App.funcs.popItems = function() { var i = App.items, s = App.selections; ['title', 'body', 'summary'].forEach(function(v) { i[v] = s[v].length ? s[v].val().trim() : ''; }); }; // Populate original item sets from edit items for the diff App.funcs.popOriginals = function() { var i = App.originals, s = App.items; ['title', 'body', 'summary'].forEach(function(v) { i[v] = s[v]; }); } // Insert editing button App.funcs.createButton = function() { if (!App.selections.redoButton.length) return false; App.selections.buttonWrapper = $('<div class="ToolkitButtonWrapper"/>'); App.selections.buttonFix = $('<button class="wmd-button ToolkitFix" title="Fix the content!" />'); App.selections.buttonInfo = $('<div class="ToolkitInfo">'); // Build the button App.selections.buttonWrapper.append(App.selections.buttonFix); App.selections.buttonWrapper.append(App.selections.buttonInfo); // Insert button App.selections.redoButton.after(App.selections.buttonWrapper); // Insert spacer App.selections.redoButton.after(App.globals.spacerHTML); // Attach the event listener to the button App.selections.buttonFix.click(App.funcs.fixEvent); App.selections.helpButton.css({ 'padding': '0px' }); App.selections.buttonWrapper.css({ 'position': 'relative', 'left': '430px', 'padding-top': '2%' }); App.selections.buttonFix.css({ 'position': 'static', 'float': 'left', 'border-width': '0px', 'background-color': 'white', 'background-image': 'url("//i.imgur.com/79qYzkQ.png")', 'background-size': '100% 100%', 'width': '18px', 'height': '18px', 'outline': 'none', 'box-shadow': 'none' }); App.selections.buttonInfo.css({ 'position': 'static', 'float': 'left', 'margin-left': '5px', 'font-size': '12px', 'color': '#424242', 'line-height': '19px' }); }; App.funcs.fixEvent = function() { return App.funcs.popItems(), App.pipe(App.items, App.pipeMods, App.globals.order), false; }; App.funcs.diff = function(a1, a2) { var strings = []; function maakRij(type, rij) { if (!type) return strings.push(rij.replace(/\</g, '&lt;')), true; if (type === '+') return strings.push('<span class="add">' + rij.replace(/\</g, '&lt;').replace(/(?=\n)/g,'↵') + '</span>'), true; if (type === '-') return strings.push('<span class="del">' + rij.replace(/\</g, '&lt;').replace(/(?=\n)/g,'↵') + '</span>'), true; } function getDiff(matrix, a1, a2, x, y) { if (x > 0 && y > 0 && a1[y - 1] === a2[x - 1]) { getDiff(matrix, a1, a2, x - 1, y - 1); maakRij(false, a1[y - 1]); } else { if (x > 0 && (y === 0 || matrix[y][x - 1] >= matrix[y - 1][x])) { getDiff(matrix, a1, a2, x - 1, y); maakRij('+', a2[x - 1]); } else if (y > 0 && (x === 0 || matrix[y][x - 1] < matrix[y - 1][x])) { getDiff(matrix, a1, a2, x, y - 1); maakRij('-', a1[y - 1]); } else { return; } } } a1 = a1.split(/(?=\b|\W)/g); a2 = a2.split(/(?=\b|\W)/g); var matrix = new Array(a1.length + 1); var x, y; for (y = 0; y < matrix.length; y++) { matrix[y] = new Array(a2.length + 1); for (x = 0; x < matrix[y].length; x++) { matrix[y][x] = 0; } } for (y = 1; y < matrix.length; y++) { for (x = 1; x < matrix[y].length; x++) { if (a1[y - 1] === a2[x - 1]) { matrix[y][x] = 1 + matrix[y - 1][x - 1]; } else { matrix[y][x] = Math.max(matrix[y - 1][x], matrix[y][x - 1]); } } } try { getDiff(matrix, a1, a2, x - 1, y - 1); return strings.join(''); } catch (e) { console.log(e); } }; // Pipe data through modules in proper order, returning the result App.pipe = function(data, mods, order) { var modName; for (var i in order) { if (order.hasOwnProperty(i)) { modName = order[i]; mods[modName](data); } } }; App.pipeMods.omit = function(data) { if (!data.body) return false; for (var type in App.globals.checks) { data.body = data.body.replace(App.globals.checks[type], function(match) { App.globals.replacedStrings[type].push(match); return App.globals.placeHolders[type]; }); } return data; }; App.pipeMods.codefix = function() { var replaced = App.globals.replacedStrings.block, str; for (var i in replaced) { // https://regex101.com/r/tX9pM3/1 https://regex101.com/r/tX9pM3/2 https://regex101.com/r/tX9pM3/3 if (/^`[^]+`$/.test(replaced[i])) replaced[i] = '\n\n' + /(?!`)((?!`)[^])+/.exec(replaced[i])[0].replace(/(.+)/g, ' $1'); } }; App.pipeMods.edit = function(data) { App.funcs.popOriginals(); // Visually confirm edit - SE makes it easy because the jQuery color animation plugin seems to be there by default App.selections.body.animate({ backgroundColor: '#c8ffa7' }, 10); App.selections.body.animate({ backgroundColor: '#fff' }, 1000); // List of fields to be edited var fields = {body:'body',title:'title'}; // Loop through all editing rules for (var j in App.edits) for (var field in fields) { var fix = App.funcs.fixIt(data[field], App.edits[j].expr, App.edits[j].replacement, App.edits[j].reason); if (!fix) continue; if (fix.reason in App.globals.reasons) App.globals.reasons[fix.reason].count += fix.count; else App.globals.reasons[fix.reason] = { reason:fix.reason, editId:j, count:fix.count }; data[field] = fix.fixed; App.edits[j].fixed = true; } // If there are no reasons, exit if (App.globals.reasons == {}) return false; // We need a place to store the reasons being applied to the summary. var reasons = []; App.globals.changes = 0; for (var z in App.globals.reasons) { // For each type of change made, add a reason string with the reason text, // optionally the rule ID, and the number of repeats if 2 or more. reasons.push(App.globals.reasons[z].reason + (App.globals.showRules ? ' ['+ App.globals.reasons[z].editId +']' : '') + (App.globals.showCounts ? ((App.globals.reasons[z].count > 1) ? ' ('+App.globals.reasons[z].count+')' : '') : '') ); App.globals.changes += App.globals.reasons[z].count; } var reasonStr = reasons.join('; ')+'.'; // Unique reasons separated by ; and terminated by . reasonStr = reasonStr.charAt(0).toUpperCase() + reasonStr.slice(1); // Cap first letter. if (!data.hasOwnProperty('summaryOrig')) data.summaryOrig = data.summary.trim(); // Remember original summary if (data.summaryOrig.length) data.summaryOrig = data.summaryOrig + ' '; data.summary = data.summaryOrig + reasonStr; // Limit summary to 300 chars if (data.summary.length > 300) data.summary = data.summary.substr(0,300-3) + '...'; return data; }; // Populate the diff App.pipeMods.diff = function() { App.selections.diff.empty().append('<div class="difftitle">' + App.funcs.diff(App.originals.title, App.items.title, true) + '</div>' + '<div class="diffbody">' + App.pipeMods.replace({body:App.funcs.diff(App.originals.body, App.items.body)}, true).body + '</div>'); App.funcs.showDiff(); } // Replace the previously omitted code App.pipeMods.replace = function(data, literal) { if (!data.body) return false; for (var type in App.globals.checksr) { var i = 0; data.body = data.body.replace(App.globals.placeHolderChecks[type], function(match) { var replace = App.globals.replacedStrings[type][i++]; if(literal && /block|lsec/.test(type)) { var after = replace.replace(/^\n\n/,''); var prepend = after !== replace ? '<span class="add">\n\n</span><span class="del">`</span>' : ''; var append = after !== replace ? '<span class="del">`</span>' : ''; var klass = /lsec/.test(type) ? ' class="lang-none prettyprint prettyprinted"' : ''; return prepend + '<pre' + klass + '><code>' + after.replace(/</g,'&lt;').replace(/^ /gm,'') + '</code></pre>' + append; } if(literal && /quote/.test(type)) return '<blockquote>' + replace.replace(/</g,'&lt;').replace(/^>/gm,'') + '</blockquote>'; if(literal) return '<code>' + replace.replace(/</g,'&lt;').replace(/(?:^`|`$)/g,'') + '</code>'; return replace; }); } return data; }; // Handle pipe output App.pipeMods.output = function(data) { App.selections.title.val(data.title); App.selections.body.val(data.body.replace(/\n{3,}/,'\n\n')); App.selections.summary.val(data.summary); App.globals.root.find('.actual-edit-overlay').remove(); App.selections.summary.css({opacity:1}); App.selections.buttonInfo.text(App.globals.changes + (App.globals.changes != 1 ? ' changes' : ' change')+' made'); StackExchange.MarkdownEditor.refreshAllPreviews(); }; // Init app App.init = function() { var count = 0; var toolbarchk = setInterval(function(){ if(++count === 10) clearInterval(toolbarchk); if(!App.globals.root.find('.wmd-button-row').length) return; clearInterval(toolbarchk); App.funcs.popSelections(); App.funcs.createButton(); App.funcs.applyListeners(); }, 100); return App; }; return App.init(); } try { var test = window.location.href.match(/.posts.(\d+).edit/); if(test) extendEditor($('form[action^="/posts/' + test[1] + '"]')); else $(document).ajaxComplete(function() { test = arguments[2].url.match(/posts.(\d+).edit-inline/); if(!test) { test = arguments[2].url.match(/review.inline-edit-post/); if(!test) return; test = arguments[2].data.match(/id=(\d+)/); if(!test) return; } extendEditor($('form[action^="/posts/' + test[1] + '"]')); }); if($('#post-form').length) $('#post-form').each(function(){ extendEditor($(this)); }); // This is the styling for the diff output. $('body').append('<style>' + '.difftitle {' + ' color: rgb(34, 34, 34);' + ' font-size: 24px;' + ' font-weight: normal;' + ' line-height: 36px;' + ' margin-bottom: 12px;' + '}' + '.diffbody {' + ' white-space: pre-wrap;' + ' font-family: "courier new", "lucida sans typewriter", mono, monospace' + '}' + '.add {' + ' background: #CFC;' + '}' + '.del {' + ' background: #FCC;' + '}' + '</style>'); } catch (e) { console.log(e); } })(); /* * To Title Case 2.1 – http://individed.com/code/to-title-case/ * Copyright © 2008–2013 David Gouch. Licensed under the MIT License. */ String.prototype.toTitleCase = function(){ var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; return this.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function(match, index, title){ if (index > 0 && index + match.length !== title.length && match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" && (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') && title.charAt(index - 1).search(/[^\s-]/) < 0) { return match.toLowerCase(); } if (match.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); }); };
editor.user.js
// ==UserScript== // @name Stack-Exchange-Editor-Toolkit // @author Cameron Bernhardt (AstroCB) // @developer Jonathan Todd (jt0dd) // @developer sathyabhat // @contributor Unihedron // @contributor Tiny Giant // @contributor Mogsdad // @grant none // @license MIT // @namespace http://github.com/AstroCB // @version 1.5.2.32 // @description Fix common grammar/usage annoyances on Stack Exchange posts with a click // @include /^https?://\w*.?(stackoverflow|stackexchange|serverfault|superuser|askubuntu|stackapps)\.com/(questions|posts|review)/(?!tagged|new).*/ // ==/UserScript== (function() { "use strict"; function extendEditor(root) { var App = {}; // Place edit items here App.items = {}; App.originals = {}; // Place selected jQuery items here App.selections = {}; // Place "global" app data here App.globals = {}; // Place "helper" functions here App.funcs = {}; // True to display counts and / or rule names in Edit Summary App.globals.showCounts = false; App.globals.showRules = false; //Preload icon alt var SEETicon = new Image(); SEETicon.src = '//i.imgur.com/d5ZL09o.png'; App.globals.root = root; App.globals.spacerHTML = '<li class="wmd-spacer wmd-spacer3" id="wmd-spacer3" style="left: 400px !important;"></li>'; App.globals.reasons = {}; App.globals.replacedStrings = { "auto": [], "quote": [], "inline": [], "block": [], "lsec": [], "links": [], "tags": [] }; App.globals.placeHolders = { "auto": "_xAutoxInsertxTextxPlacexHolder_", "quote": "_xBlockxQuotexPlacexHolderx_", "inline": "_xCodexInlinexPlacexHolderx_", "block": "_xCodexBlockxPlacexHolderx_", "lsec": "_xLinkxSectionxPlacexHolderx_", "links": "_xLinkxPlacexHolderx_", "tags": "_xTagxPlacexHolderx_" }; App.globals.placeHolderChecks = { "auto": /_xAutoxInsertxTextxPlacexHolder_/gi, "quote": /_xBlockxQuotexPlacexHolderx_/gi, "inline": /_xCodexInlinexPlacexHolderx_/gi, "block": /_xCodexBlockxPlacexHolderx_/gi, "lsec": /_xLinkxSectionxPlacexHolderx_/gi, "links": /_xLinkxPlacexHolderx_/gi, "tags": /_xTagxPlacexHolderx_/gi }; App.globals.checks = { // https://regex101.com/r/cI6oK2/1 automatically inserted text "auto": /[^]*\<\!\-\- End of automatically inserted text \-\-\>/g, // https://regex101.com/r/fU5lE6/1 blockquotes "quote": /^\>(?:(?!\n\n)[^])+/gm, // https://regex101.com/r/lL6fH3/1 single-line inline code "inline": /`[^`\n]+`/g, // https://regex101.com/r/eC7mF7/1 code blocks and multiline inline code. "block": /`[^`]+`|(?:(?:[ ]{4}|[ ]{0,3}\t).+(?:[\r\n]?(?!\n\S)(?:[ ]+\n)*)+)+/g, // https://regex101.com/r/tZ4eY3/7 link-sections "lsec": /(?: (?:\[\d\]): \w*:+\/\/.*\n*)+/g, // https://regex101.com/r/tZ4eY3/20 links and pathnames "links": /\[[^\]\n]+\](?:\([^\)\n]+\)|\[[^\]\n]+\])|(?:\/\w+\/|.:\\|\w*:\/\/|\.+\/[./\w\d]+|(?:\w+\.\w+){2,})[./\w\d:/?#\[\]@!$&'()*+,;=\-~%]*/g, // https://regex101.com/r/bF0iQ0/1 tags and html comments "tags": /\<[\/a-z]+\>|\<\!\-\-[^>]+\-\-\>/g }; App.globals.checksr = (function(o1){ var o2 = {}; var k= Object.keys(o1); for(var i = k.length-1; i >= 0; --i) o2[k[i]] = o1[k[i]]; return o2; })(App.globals.checks); // Assign modules here App.pipeMods = {}; // Define order in which mods affect here App.globals.order = ["omit", "codefix", "edit", "diff", "replace", "output"]; // Define edit rules App.edits = { // All caps noneedtoyell: { expr: /^((?=.*[A-Z])[^a-z]*)$/g, replacement: function(input) { return input.trim().substr(0, 1).toUpperCase() + input.trim().substr(1).toLowerCase(); }, reason: 'no need to yell' }, so: { expr: /\bstack\s*overflow\b/gi, replacement: "Stack Overflow", reason: "'Stack Overflow' is the legal name" }, se: { expr: /\bstack\s*exchange\b/gi, replacement: "Stack Exchange", reason: "'Stack Exchange' is the legal name" }, expansionSO: { expr: /([^\b\w.]|^)SO\b/g, replacement: "$1Stack Overflow", reason: "'Stack Overflow' is the legal name" }, expansionSE: { expr: /([^\b\w.]|^)SE\b/g, replacement: "$1Stack Exchange", reason: "'Stack Exchange' is the legal name" }, javascript: { expr: /([^\b\w.]|^)(javascript|js|java script)\b/gi, replacement: "$1JavaScript", reason: "trademark capitalization" }, jsfiddle: { expr: /\bjsfiddle\b/gi, replacement: "JSFiddle", reason: "trademark capitalization" }, jquery: { expr: /\bjquery\b/gi, replacement: "jQuery", reason: "trademark capitalization" }, angular: { expr: /\bangular(?:js)?\b/gi, replacement: "AngularJS", reason: "trademark capitalization" }, x_html: { expr: /(?:[^\b\w.]|^)(g|ht|x|xht)ml\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, css: { expr: /(?:[^\b\w.]|^)css\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, json: { expr: /(?:[^\b\w.]|^)json\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ajax: { expr: /\bajax\b/g, // Leave "Ajax" alone. See https://github.com/AstroCB/Stack-Exchange-Editor-Toolkit/issues/45 replacement: "AJAX", reason: "acronym capitalization" }, php: { expr: /(?:[^\b\w.]|^)php\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, voting: { expr: /\b(down|up)\Wvot/gi, replacement: "$1vote", reason: "the proper spelling (despite the tag name) is '$1vote' (one word)" }, c: { expr: /(?:[^\b\w.]|^)c\b(?:#|\+\+)?/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, java: { expr: /([^\b\w.]|^)java\b/gi, replacement: "$1Java", reason: "trademark capitalization" }, sql: { expr: /(?:[^\b\w.]|^)sql\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, sqlite: { expr: /\bsqlite\s*([0-9]*)\b/gi, replacement: "SQLite $2", reason: "trademark capitalization" }, android: { expr: /\bandroid\b/gi, replacement: "Android", reason: "trademark capitalization" }, oracle: { expr: /\boracle\b/gi, replacement: "Oracle", reason: "trademark capitalization" }, windows: { // https://regex101.com/r/jF9zK1/6 expr: /\b(?:win|windows)(?:\s+(2k|[0-9.]+|ce|me|nt|xp|vista|server))?\b/gi, replacement: function(match, ver) { ver = !ver ? '' : ver.replace(/ce/i, ' CE') .replace(/me/i, ' ME') .replace(/nt/i, ' NT') .replace(/xp/i, ' XP') .replace(/2k/i, ' 2000') .replace(/vista/i, ' Vista') .replace(/server/i, ' Server'); return 'Windows' + ver; }, reason: "trademark capitalization" }, linux: { expr: /\blinux\b/gi, replacement: "Linux", reason: "trademark capitalization" }, wordpress: { expr: /\bwordpress\b/gi, replacement: "WordPress", reason: "trademark capitalization" }, google: { expr: /\bgoogle\b/gi, replacement: "Google", reason: "trademark capitalization" }, mysql: { expr: /\bmysql\b/gi, replacement: "MySQL", reason: "trademark capitalization" }, nodejs: { expr: /\bnode\.?js\b/gi, replacement: "Node.js", reason: "trademark capitalization" }, apache: { expr: /\bapache\b/gi, replacement: "Apache", reason: "trademark capitalization" }, git: { expr: /([^\b\w.]|^)git\b/gi, replacement: "$1Git", reason: "trademark capitalization" }, github: { expr: /\bgithub\b/gi, replacement: "GitHub", reason: "trademark capitalization" }, facebook: { expr: /\bfacebook\b/gi, replacement: "Facebook", reason: "trademark capitalization" }, python: { expr: /\bpython\b/gi, replacement: "Python", reason: "trademark capitalization" }, urli: { expr: /\b(ur[li])\b/gi, replacement: function(match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ios: { expr: /\bios\b/gi, replacement: "iOS", reason: "trademark capitalization" }, iosnum: { expr: /\bios([0-9])\b/gi, replacement: "iOS $1", reason: "trademark capitalization" }, ubuntu: { expr: /\b[uoa]*b[uoa]*[tn][oua]*[tnu][oua]*\b/gi, replacement: "Ubuntu", reason: "trademark capitalization" }, vbnet: { // https://regex101.com/r/bB9pP3/1 expr: /(?:vb|\s+)(?:\.net|\s*[0-9]+)\s*(?:framework|core)?/gi, replacement: function(str) { return str.replace(/vb/i, 'VB') .replace(/net/i, 'NET') .replace(/framework/i, 'Framework') .replace(/core/i, 'Core'); }, reason: "trademark capitalization" }, regex: { expr: /\bregex(p)?\b/gi, replacement: "RegEx$1", reason: "trademark capitalization" }, postgresql: { expr: /\bpostgres(ql|s)?\b/gi, replacement: "PostgreSQL", reason: "trademark capitalization" }, paypal: { expr: /\bpaypal\b/gi, replacement: "PayPal", reason: "trademark capitalization" }, pdf: { expr: /([^\b\w.]|^)pdf(s)?/gi, replacement: "$1PDF$2", reason: "trademark capitalization" }, api: { expr: /([^\b\w.]|^)api(s)?\b/gi, replacement: "$1API$2", reason: "acronym capitalization" }, ssl: { expr: /(?:[^\b\w.]|^)ssl\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, tomcat: { expr: /\btomcat([0-9.]*)/gi, replacement: "Tomcat$1", reason: "trademark capitalization" }, npm: { expr: /\bnpm(s)?\b/g, replacement: "NPM$1", reason: "acronym capitalization" }, succeed: { expr: /\b(s)uc[cs]?ee?d(ed|s)?\b/gi, replacement: "$1ucceed$2", reason: "grammar and spelling" }, ftp: { expr: /(?:[^\b\w.]|^)[st]?ftps?\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ipa: { expr: /(?:[^\b\w.]|^)ipa\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, avl: { expr: /(?:[^\b\w.]|^)avl\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, netbeans: { expr: /\b(netbeans|net-beans|net beans)\b/gi, replacement: "NetBeans", reason: "trademark capitalization" }, cli_cgi: { expr: /(?:[^\b\w.]|^)c[lg]i\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, nginx: { expr: /\bnginx\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, dll: { expr: /(?:[^\b\w.]|^)dll\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, source: { expr: /\b(s)orce(s|d)?\b/gi, replacement: "$1ource$2", reason: "grammar and spelling" }, standardize: { // https://regex101.com/r/vN7pM0/1 expr: /\b(s)tandari([sz](?:e|es|ed|ation))\b/gi, replacement: "$1tandardi$2", reason: "grammar and spelling" }, different: { // https://regex101.com/r/vN7pM0/1 expr: /\b(d)iff?e?ren(t|ce)\b/gi, replacement: "$1ifferen$2", reason: "grammar and spelling" }, personally: { // https://regex101.com/r/oL9aM1/1 expr: /\b(p)ersona?l?(ly)?\b/gi, replacement: "$1ersonal$2", reason: "grammar and spelling" }, problem: { expr: /\b(p)orblem(s)?\b/gi, replacement: "$1roblem$2", reason: "grammar and spelling" }, maybe: { expr: /\b(m)aby\b/gi, replacement: "$1aybe", reason: "grammar and spelling" }, // Noise reduction editupdate: { // https://regex101.com/r/tT2pK6/2 expr: /(?!(?:edit|update)\w*\s*[^:]*$)(?:^\**)(edit|update)\w*(\s*#?[0-9]+)?:?(?:\**):?/gmi, replacement: "", reason: "noise reduction" }, hello: { // TODO: Update badsentences (new) to catch everything hello (old) did. expr: /(?:^|\s)(hi\s+guys|hi|hello|good\s(?:evening|morning|day|afternoon))(?:\.|!|\ )/gmi, replacement: "", reason: "noise reduction" }, badwords: { expr: /[^\n.!?:]*\b(?:th?anks?|th(?:an)?x|tanx|folks?|ki‌nd(‌?:est|ly)|first\s*question)\b[^,.!?\n]*[,.!?]*/gi, replacement: "", reason: "noise reduction" }, badphrases: { expr: /[^\n.!?:]*(?:h[ea]lp|hope|appreciate|pl(?:ease|z|s))[^.!?\n]*(?:helps?|appreciated?)[^,.!?\n]*[,.!?]*/gi, replacement: "", reason: "noise reduction" }, imnew: { expr: /(?! )[\w\s]*\bi[' ]?a?m +(?:kinda|really) *new\w* +(?:to|in) *\w* *(?:and|[;,.!?])? */gi, replacement: "", reason: "noise reduction" }, salutations: { expr: /[\r\n]*(regards|cheers?),?[\t\f ]*[\r\n]?\w*\.?/gi, replacement: "", reason: "noise reduction" }, sorry4english: { // https://regex101.com/r/pG3oD6/1 expr: /(?:^|\s)[^.!\n\r]*(sorry).*?(english).*?(?:[.! \n\r])/gmi, replacement: "", reason: "noise reduction" }, // Grammar and spelling apostrophe_d: { expr: /\b(he|she|who|you)[^\w']*(d)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_ll: { expr: /\b(they|what|who|you)[^\w']*(ll)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_re: { expr: /\b(they|what|you)[^\w']*(re)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_s: { expr: /\b(he|she|that|there|what|where)[^\w']*(s)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, apostrophe_t: { expr: /\b(aren|can|didn|doesn|don|hasn|haven|isn|mightn|mustn|shan|shouldn|won|wouldn)[^\w']*(t)\b/gi, replacement: "$1'$2", reason: "grammar and spelling" }, doesn_t: { expr: /\b(d)ose?nt\b/gi, replacement: "$1oesn't", reason: "grammar and spelling" }, prolly: { expr: /\b(p)roll?y\b/gi, replacement: "$1robably", reason: "grammar and spelling" }, keyboard: { expr: /\b(k)ey?boa?rd\b/gi, replacement: "$1eyboard", reason: "grammar and spelling" }, i: { expr: /\bi('|\b)/g, // i or i-apostrophe replacement: "I", reason: "grammar and spelling" }, im: { expr: /\bi ?m\b/gi, replacement: "I'm", reason: "grammar and spelling" }, ive: { expr: /\bive\b/gi, replacement: "I've", reason: "grammar and spelling" }, ur: { expr: /\bur\b/gi, replacement: "your", // May also be "you are", but less common on SO reason: "grammar and spelling" }, u: { expr: /\bu\b/gi, replacement: "you", reason: "grammar and spelling" }, gr8: { expr: /\bgr8\b/gi, replacement: "great", reason: "grammar and spelling" }, allways: { expr: /\b(a)llways\b/gi, replacement: "$1lways", reason: "grammar and spelling" }, expect: { expr: /\b(e)spect(s)?\b/gi, replacement: "$1xpect$2", reason: "grammar and spelling" }, employe: { expr: /\b(e)mploye\b/gi, replacement: "$1mployee", reason: "grammar and spelling" }, retrieve: { expr: /\b(r)etreive(d)?\b/gi, replacement: "$1etrieve$2", reason: "grammar and spelling" }, firefox: { expr: /\bfire?fox\b/gi, replacement: "Firefox", reason: "trademark capitalization" }, success: { // https://regex101.com/r/hK2vG4/1 expr: /\b(s)ucc?ess?(ful|fully)?l?\b/gi, replacement: "$1uccess$2", reason: "grammar and spelling" }, safari: { expr: /\bsafari\b/gi, replacement: "Safari", reason: "trademark capitalization" }, chrome: { expr: /\bchrome\b/gi, replacement: "Chrome", reason: "trademark capitalization" }, anyones: { expr: /\b(a)nyones\b/gi, replacement: "$1nyone's", reason: "grammar and spelling" }, length: { expr: /\b(l)en(?:gh?t|th)\b/gi, replacement: "$1ength", reason: "grammar and spelling" }, height: { expr: /\b(h)(?:ei|i|ie)(?:gt|th|ghth|gth)\b/gi, replacement: "$1eight", reason: "grammar and spelling" }, width: { expr: /\b(w)idh?t\b/gi, replacement: "$1idth", reason: "grammar and spelling" }, centered: { expr: /\b(c)ent(?:red|erd)\b/gi, replacement: "$1entered", reason: "grammar and spelling" }, center: { expr: /\b(c)entre\b/gi, // "Centre" is a word, however in most cases on SO "center" is meant replacement: "$1enter", reason: "grammar and spelling" }, aint_isnt: { expr: /\bain't\b/gi, replacement: "isn't", reason: "grammar and spelling" }, coordinates: { expr: /\b(c)ordinate(s|d)?\b/gi, replacement: "$1oordinate$2", reason: "grammar and spelling" }, argument: { expr: /\b(a)rguement(s)?\b/gi, replacement: "$1rgument$2", reason: "grammar and spelling" }, gui: { expr: /([^\b\w.]|^)gui(s)?\b/gi, replacement: "$1GUI$2", reason: "acronym capitalization" }, iterate: { // https://regex101.com/r/iL6bV3/1 expr: /\b(i)(?:tter|tar)at(e[ds]?|ing|ion|ions)\b/gi, replacement: "$1terat$2", reason: "grammar and spelling" }, below: { expr: /\b(b)ellow\b/gi, // "Bellow" is a word, but extremely uncommon on StackOverflow.com. replacement: "$1elow", reason: "grammar and spelling" }, encrypt: { expr: /\b(en|de)cript(s|ing)?\b/gi, replacement: "$1crypt$2", reason: "grammar and spelling" }, gnu: { expr: /\bgnu\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, gcc: { expr: /(?:[^\b\w.]|^)gcc\b/g, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, stp: { expr: /(?:[^\b\w.]|^)stp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, tcp: { expr: /(?:[^\b\w.]|^)tcp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, ipv_n: { expr: /\bip(v[46])?\b/gi, replacement: "IP$1", reason: "acronym capitalization" }, fq_dn_s: { // FQDN, DN, DNS expr: /(?:[^\b\w.]|^)(?:fq)?dns?\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, icmp: { expr: /\bicmp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, rsvp: { expr: /\brsvp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, snmp: { expr: /\bsnmp\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, cpu: { expr: /\bcpu(s)?\b/gi, replacement: "CPU$1", reason: "acronym capitalization" }, rss: { expr: /(?:[^\b\w.]|^)rss?\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, mvc: { expr: /(?:[^\b\w.]|^)mvc\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "acronym capitalization" }, mvn: { expr: /(?:[^\b\w.]|^)mvn\b/gi, replacement: function (match) { return match.toUpperCase(); }, reason: "trademark capitalization" }, ascii: { expr: /([^\b\w.]|^)ascii?\b/gi, replacement: "$1ASCII", reason: "acronym capitalization" }, maven: { expr: /\bmaven\b/gi, replacement: "Maven", reason: "trademark capitalization" }, youtube: { expr: /\byoutube\b/gi, replacement: "YouTube", reason: "trademark capitalization" }, amazon: { // https://regex101.com/r/dR0pJ7/1 expr: /\b(amazon(?: )?(?:redshift|web services|cloudfront|console)?)((?: )?(?:ec2|aws|s3|rds|sqs|iam|elb|emr|vpc))?\b/gi, replacement: function(str,titlecase,uppercase) { var fixed = titlecase.toTitleCase() + (uppercase ? uppercase.toUpperCase() : ''); return fixed; }, reason: "trademark capitalization" }, zend: { expr: /\bzend((?: )?(?:framework|studio|guard))?\b/gi, //replacement: String.toTitleCase, // Doesn't work like built-in toUpperCase, returns 'undefined'. Load order? replacement: function(str,prod) { return str.toTitleCase(); }, reason: "trademark capitalization" }, formatting: { expr: /\b(f)ormating\b/gi, replacement: "$1ormatting", reason: "grammar and spelling" }, process: { expr: /\b(p)roces(es|ed)?\b/gi, replacement: "$1rocess$2", reason: "grammar and spelling" }, programming: { expr: /\b(p)rogram(ing|ed|er)\b/gi, replacement: "$1rogramm$2", reason: "grammar and spelling" }, twitter: { expr: /\btwitter\b/gi, replacement: "Twitter", reason: "trademark capitalization" }, bootstrap: { // "bootstrap" is also a general computing term, so expect some false positives expr: /\bbootst?r?ap\b/gi, replacement: "Bootstrap", reason: "trademark capitalization" }, apple: { expr: /\bapple\b/g, replacement: "Apple", reason: "trademark capitalization" }, iphone: { expr: /\biph?one?\b/gi, replacement: "iPhone", reason: "trademark capitalization" }, google_apps_script: { expr: /\bgoogle ?(?:apps?)? ?script\b/gi, replacement: "Google Apps Script", reason: "trademark capitalization" }, // From Peter Mortensen list (http://pvm-professionalengineering.blogspot.de/2011/04/word-list-for-editing-stack-exchange.html) ie: { // http://english.stackexchange.com/questions/30106/can-i-start-a-sentence-with-i-e expr: /\b(i|I)e\b/g, // Careful here; IE is Internet Explorer replacement: "$1.e.", reason: "grammar and spelling" }, eg: { expr: /\b(e)g\b/gi, replacement: "$1.g.", reason: "grammar and spelling" }, unfortunately: { expr: /\b(u)nfortu?na?tly\b/gi, replacement: "$1nfortunately", reason: "grammar and spelling" }, whether: { expr: /\b(w)h?eth?er\b/gi, replacement: "$1hether", reason: "grammar and spelling" }, through: { // https://regex101.com/r/gQ0dZ1/4 expr: /\b(t)(?:hru|rough|hroug)\b/gi, replacement: "$1hrough", reason: "grammar and spelling" }, throughout: { expr: /\b(t)(?:hruout|roughout)\b/gi, replacement: "$1hroughout", reason: "grammar and spelling" }, breakthrough: { expr: /\b(b)reak\s+through(s)?\b/gi, replacement: "$1reakthrough$2", reason: "grammar and spelling" }, though: { expr: /\b(t)(?:ho|hou|hogh)\b/gi, replacement: "$1hough", reason: "grammar and spelling" }, although: { expr: /\b(a)l(?:tho|thou|thogh|tough)\b/gi, replacement: "$1lthough", reason: "grammar and spelling" }, thought: { expr: /\b(t)r?ought(s)?\b/gi, replacement: "$1hough$2", reason: "grammar and spelling" }, throwing: { expr: /\b(t)hroughing\b/gi, // Peter says this is "thoroughly", but a survey of SO questions indicates "throwing" replacement: "$1hrowing", reason: "grammar and spelling" }, a_lot: { expr: /\b(a)lot\b/gi, replacement: "$1 lot", reason: "grammar and spelling" }, one_r_two_r: { expr: /\b(refe|prefe|occu)r(ed|ing)\b/gi, replacement: "$1rr$2", reason: "grammar and spelling" }, preferably: { expr: /\b(p)referrably\b/gi, replacement: "$1referably", reason: "grammar and spelling" }, command_line: { expr: /\b(c)ommandline\b/gi, replacement: "$1ommand-line", reason: "grammar and spelling" }, benefits: { expr: /\b(b)enifits\b/gi, replacement: "$1enefits", reason: "grammar and spelling" }, authorization: { expr: /\b(a)uth\b/gi, // This may be too ambiguous, could also mean "authentication" replacement: "$1uthorization", reason: "grammar and spelling" }, persistent: { expr: /\b(p)ersistan(t|ce)\b/gi, replacement: "$1ersisten$2", reason: "grammar and spelling" }, _ibility: { expr: /\b(comp|incomp|access)abilit(y|ies)\b/gi, replacement: "$1ibilit$2", reason: "grammar and spelling" }, separate: { expr: /\b(s)epe?rate?(d|ly|s)?\b/gi, replacement: "$1eparate$2", reason: "grammar and spelling" }, separation: { expr: /\b(s)eperation(s)?\b/gi, replacement: "$1eparation$2", reason: "grammar and spelling" }, definite: { expr: /\b(d)efin(?:ate?|ite?|al|te?)(ly)?\b/gi, // Catches correct spelling, too. replacement: "$1efinite$2", reason: "grammar and spelling" }, definitive: { expr: /\b(d)efina?tive(ly)?\b/gi, replacement: "$1efinitive$2", reason: "grammar and spelling" }, independent: { expr: /\b(i)ndependant(ly)?\b/gi, replacement: "$1ndependent$2", reason: "grammar and spelling" }, recommend: { expr: /\b(r)ecomm?and(ation)?\b/gi, replacement: "$1ecommend$2", reason: "grammar and spelling" }, compatibility: { expr: /\b(c)ompatability\b/gi, replacement: "$1ompatibility$2", reason: "grammar and spelling" }, ps: { expr: /\bps\b/g, replacement: "PS", reason: "grammar and spelling" }, ok: { expr: /\bok\b/g, replacement: "OK", reason: "grammar and spelling" }, etc: { expr: /\betc\b/g, replacement: "etc.", reason: "grammar and spelling" }, back_end: { // Interesting fact: backend 3x more common than back-end expr: /\b(b)ackend\b/g, replacement: "$1ack-end", reason: "grammar and spelling" }, front_end: { expr: /\b(f)rontend\b/g, replacement: "$1ront-end", reason: "grammar and spelling" }, data_type: { expr: /\b(d)atatype\b/g, replacement: "$1ata type", reason: "grammar and spelling" }, allotted: { expr: /\b(a)l+ot+ed\b/g, replacement: "$1llotted", reason: "grammar and spelling" }, every_time: { expr: /\b(e)ve?rytime\b/g, replacement: "$1very time", reason: "grammar and spelling" }, straightforward: { expr: /\b(s)traig?h?t[ -]forward\b/g, replacement: "$1traightforward", reason: "grammar and spelling" }, preceding: { expr: /\b(p)receeding\b/gi, replacement: "$1receding", reason: "grammar and spelling" }, no_one: { expr: /\b(n)o-?one\b/gi, replacement: "$1o one", reason: "grammar and spelling" }, de_facto: { expr: /\b(d)e-?facto\b/gi, replacement: "$1e facto", reason: "grammar and spelling" }, accommodate: { // https://regex101.com/r/cL3mD9/1 expr: /\b(a)(?:c+om|com+)odate\b/gi, replacement: "$1ccommodate", reason: "grammar and spelling" }, matlab: { expr: /([^\b\w.]|^)math?lab\b/gi, replacement: "$1MATLAB", reason: "trademark capitalization" }, internet: { expr: /\binternet\b/g, replacement: "Internet", reason: "trademark capitalization" }, web_services: { expr: /\bweb services\b/g, replacement: "Web services", reason: "trademark capitalization" }, kind_of: { expr: /\b(k)inda\b/gi, replacement: "$1ind of", reason: "grammar and spelling" }, want_to: { expr: /\b(w)ann?a\b/gi, replacement: "$1ant to", reason: "grammar and spelling" }, sort_of: { expr: /\b(s)orta\b/gi, replacement: "$1ort of", reason: "grammar and spelling" }, got_to: { // https://regex101.com/r/rK6xR5/1 expr: /\b(have\s+)?(g)otta\b/gi, replacement: "$1$2ot to", reason: "grammar and spelling" }, dont_know: { // https://regex101.com/r/rK6xR5/1 expr: /\b(d)[uo]nn?o\b/gi, replacement: "$1on't know", reason: "grammar and spelling" }, going_to: { expr: /\b(g)[ou]nn?a\b/gi, replacement: "$1oing to", reason: "grammar and spelling" }, // Punctuation & Spacing come last firstcaps: { // https://regex101.com/r/qR5fO9/18 // This doesn't work quite right, because is finds all sentences, not just ones needing caps. //expr: /(?:(?!\n\n)[^\s.!?]+[ ]*)+([.!?])*[ ]*/g, expr: /((?!\n\n)[A-z](?:(?!\n\n)[^?.!A-Z])+(?:\.[A-z][^?.!A-Z]+)*([?.!])?)/gm, replacement: function(str, endpunc) { if (str === "undefined") return str; // MUST match str, or gets counted as a change. // https://regex101.com/r/bL9xD7/1 find and capitalize first letter return str.replace(/^(\W*)([a-z])(.*)/g, function(sentence, pre, first, post) { if (!pre) pre = ''; if (!post) post = ''; var update = pre + first.toUpperCase() + post; // + (!endpunc && /\w/.test(post.substr(-1)) ? '.' : ''); return update; }); }, reason: "caps at start of sentences" }, multiplesymbols: { // https://regex101.com/r/bE9zM6/1 expr: /([^\w\s*#.\-_+])\1{1,}/g, replacement: "$1", reason: "punctuation & spacing" }, spacesbeforesymbols: { expr: /[ \t]*(?:([,!?;:](?!\)|\d)|[ \t](\.))(?=\s))[ \t]*/g, // https://regex101.com/r/vS3dS3/6 replacement: "$1 ", reason: "punctuation & spacing" }, multiplespaces: { // https://regex101.com/r/hY9hQ3/1 expr: /[ ]{2,}(?!\n)/g, replacement: " ", reason: "punctuation & spacing" }, blanklines: { expr: /(?:\s*[\r\n]){3,}/gm, replacement: "\n\n", reason: "punctuation & spacing" }, endblanklines: { expr: /[\s\r\n]+$/g, replacement: "", reason: "punctuation & spacing" }, // The title says it all thetitlesaysitall: { // https://regex101.com/r/bX1qB4/3 expr: /(?:the )?title says it all/gi, replacement: function(){ return '"' + App.selections.title.val() + '" says it all'; }, reason: "the title says it all" } }; // This is where the magic happens: this function takes a few pieces of information and applies edits to the post with a couple exceptions App.funcs.fixIt = function(input, expression, replacement, reasoning) { // If there is nothing to search, exit if (!input) return false; // Scan the post text using the expression to see if there are any matches var matches = input.match(expression); if (!matches) return false; var count = 0; // # replacements to do input = input.replace(expression, function(before){ var after = before.replace(expression, replacement); if(after !== before) ++count; return after; }); return count > 0 ? { reason: reasoning, fixed: String(input).trim(), count: count } : false; }; App.funcs.applyListeners = function() { // Removes default Stack Exchange listeners; see https://github.com/AstroCB/Stack-Exchange-Editor-Toolkit/issues/43 function removeEventListeners(e) { if (e.which === 13) { if (e.metaKey || e.ctrlKey) { // CTRL/CMD + Enter -> Activate the auto-editor App.selections.buttonFix.click(); } else { // It's possible to remove the event listeners, because of the way outerHTML works. this.outerHTML = this.outerHTML; App.funcs.fixEvent(); } } } // Tags box App.selections.tagField.keydown(removeEventListeners); // Edit summary box App.selections.summary.keydown(removeEventListeners); }; // Populate or refresh DOM selections App.funcs.popSelections = function() { App.selections.redoButton = App.globals.root.find('[id^="wmd-redo-button"]'); App.selections.body = App.globals.root.find('[id^="wmd-input"]'); App.selections.title = App.globals.root.find('[class*="title-field"]'); App.selections.summary = App.globals.root.find('[id^="edit-comment"], .edit-comment'); App.selections.tagField = App.globals.root.find(".tag-editor"); App.selections.submitButton = App.globals.root.find('[id^="submit-button"]'); App.selections.helpButton = App.globals.root.find('[id^="wmd-help-button"]'); App.selections.editor = App.globals.root.find('.post-editor'); App.selections.preview = App.globals.root.find('.wmd-preview'); App.selections.previewMenu = App.globals.root.find('.preview-options').append('&nbsp;&nbsp;'); if(!App.selections.previewMenu.length) { App.selections.previewMenu = $('<div class="preview-options post-menu" style="margin-top:5px;margin-bottom:8px;"/>').insertBefore(App.selections.preview); var previewToggleText = App.selections.preview.is(':visible') ? 'hide preview' : 'show preview'; App.selections.previewToggle = $('<a href="javascript:void(0)" class="hide-preview" style="margin-left:-2px;">' + previewToggleText + '</a>').click(App.funcs.togglePreview).appendTo(App.selections.previewMenu); App.selections.previewMenu.append('&nbsp;&nbsp;'); } else { App.selections.previewToggle = App.globals.root.find('.hide-preview').off('click').attr('href','javascript:void(0)').click(App.funcs.togglePreview); } App.selections.diffToggle = $('<a href="javascript:void(0)" class="hide-preview" style="margin-left:-2px;">show diff</a>').click(App.funcs.toggleDiff).appendTo(App.selections.previewMenu); App.selections.diff = $('<div class="wmd-preview"/>').hide().appendTo(App.selections.editor); }; App.funcs.showPreview = function() { App.selections.diff.hide(); App.selections.diffToggle.text('show diff'); App.selections.preview.show(); App.selections.previewToggle.text('hide preview'); } App.funcs.showDiff = function() { App.selections.preview.hide(); App.selections.previewToggle.text('show preview'); App.selections.diff.show(); App.selections.diffToggle.text('hide diff'); } App.funcs.togglePreview = function() { App.selections.diff.hide(); App.selections.diffToggle.text('show diff'); if(/hide/.test(App.selections.previewToggle.text())) return App.selections.previewToggle.text('show preview'), App.selections.preview.toggle(), true; if(/show/.test(App.selections.previewToggle.text())) return App.selections.previewToggle.text('hide preview'), App.selections.preview.toggle(), true; } App.funcs.toggleDiff = function() { App.selections.preview.hide(); App.selections.previewToggle.text('show preview'); if(/hide/.test(App.selections.diffToggle.text())) return App.selections.diffToggle.text('show diff'), App.selections.diff.toggle(), true; if(/show/.test(App.selections.diffToggle.text())) return App.selections.diffToggle.text('hide diff'), App.selections.diff.toggle(), true; } // Populate edit item sets from DOM selections App.funcs.popItems = function() { var i = App.items, s = App.selections; ['title', 'body', 'summary'].forEach(function(v) { i[v] = s[v].length ? s[v].val().trim() : ''; }); }; // Populate original item sets from edit items for the diff App.funcs.popOriginals = function() { var i = App.originals, s = App.items; ['title', 'body', 'summary'].forEach(function(v) { i[v] = s[v]; }); } // Insert editing button App.funcs.createButton = function() { if (!App.selections.redoButton.length) return false; App.selections.buttonWrapper = $('<div class="ToolkitButtonWrapper"/>'); App.selections.buttonFix = $('<button class="wmd-button ToolkitFix" title="Fix the content!" />'); App.selections.buttonInfo = $('<div class="ToolkitInfo">'); // Build the button App.selections.buttonWrapper.append(App.selections.buttonFix); App.selections.buttonWrapper.append(App.selections.buttonInfo); // Insert button App.selections.redoButton.after(App.selections.buttonWrapper); // Insert spacer App.selections.redoButton.after(App.globals.spacerHTML); // Attach the event listener to the button App.selections.buttonFix.click(App.funcs.fixEvent); App.selections.helpButton.css({ 'padding': '0px' }); App.selections.buttonWrapper.css({ 'position': 'relative', 'left': '430px', 'padding-top': '2%' }); App.selections.buttonFix.css({ 'position': 'static', 'float': 'left', 'border-width': '0px', 'background-color': 'white', 'background-image': 'url("//i.imgur.com/79qYzkQ.png")', 'background-size': '100% 100%', 'width': '18px', 'height': '18px', 'outline': 'none', 'box-shadow': 'none' }); App.selections.buttonInfo.css({ 'position': 'static', 'float': 'left', 'margin-left': '5px', 'font-size': '12px', 'color': '#424242', 'line-height': '19px' }); }; App.funcs.fixEvent = function() { return App.funcs.popItems(), App.pipe(App.items, App.pipeMods, App.globals.order), false; }; App.funcs.diff = function(a1, a2) { var strings = []; function maakRij(type, rij) { if (!type) return strings.push(rij.replace(/\</g, '&lt;')), true; if (type === '+') return strings.push('<span class="add">' + rij.replace(/\</g, '&lt;').replace(/(?=\n)/g,'↵') + '</span>'), true; if (type === '-') return strings.push('<span class="del">' + rij.replace(/\</g, '&lt;').replace(/(?=\n)/g,'↵') + '</span>'), true; } function getDiff(matrix, a1, a2, x, y) { if (x > 0 && y > 0 && a1[y - 1] === a2[x - 1]) { getDiff(matrix, a1, a2, x - 1, y - 1); maakRij(false, a1[y - 1]); } else { if (x > 0 && (y === 0 || matrix[y][x - 1] >= matrix[y - 1][x])) { getDiff(matrix, a1, a2, x - 1, y); maakRij('+', a2[x - 1]); } else if (y > 0 && (x === 0 || matrix[y][x - 1] < matrix[y - 1][x])) { getDiff(matrix, a1, a2, x, y - 1); maakRij('-', a1[y - 1]); } else { return; } } } a1 = a1.split(/(?=\b|\W)/g); a2 = a2.split(/(?=\b|\W)/g); var matrix = new Array(a1.length + 1); var x, y; for (y = 0; y < matrix.length; y++) { matrix[y] = new Array(a2.length + 1); for (x = 0; x < matrix[y].length; x++) { matrix[y][x] = 0; } } for (y = 1; y < matrix.length; y++) { for (x = 1; x < matrix[y].length; x++) { if (a1[y - 1] === a2[x - 1]) { matrix[y][x] = 1 + matrix[y - 1][x - 1]; } else { matrix[y][x] = Math.max(matrix[y - 1][x], matrix[y][x - 1]); } } } try { getDiff(matrix, a1, a2, x - 1, y - 1); return strings.join(''); } catch (e) { console.log(e); } }; // Pipe data through modules in proper order, returning the result App.pipe = function(data, mods, order) { var modName; for (var i in order) { if (order.hasOwnProperty(i)) { modName = order[i]; mods[modName](data); } } }; App.pipeMods.omit = function(data) { if (!data.body) return false; for (var type in App.globals.checks) { data.body = data.body.replace(App.globals.checks[type], function(match) { App.globals.replacedStrings[type].push(match); return App.globals.placeHolders[type]; }); } return data; }; App.pipeMods.codefix = function() { var replaced = App.globals.replacedStrings.block, str; for (var i in replaced) { // https://regex101.com/r/tX9pM3/1 https://regex101.com/r/tX9pM3/2 https://regex101.com/r/tX9pM3/3 if (/^`[^]+`$/.test(replaced[i])) replaced[i] = '\n\n' + /(?!`)((?!`)[^])+/.exec(replaced[i])[0].replace(/(.+)/g, ' $1'); } }; App.pipeMods.edit = function(data) { App.funcs.popOriginals(); // Visually confirm edit - SE makes it easy because the jQuery color animation plugin seems to be there by default App.selections.body.animate({ backgroundColor: '#c8ffa7' }, 10); App.selections.body.animate({ backgroundColor: '#fff' }, 1000); // List of fields to be edited var fields = {body:'body',title:'title'}; // Loop through all editing rules for (var j in App.edits) for (var field in fields) { var fix = App.funcs.fixIt(data[field], App.edits[j].expr, App.edits[j].replacement, App.edits[j].reason); if (!fix) continue; if (fix.reason in App.globals.reasons) App.globals.reasons[fix.reason].count += fix.count; else App.globals.reasons[fix.reason] = { reason:fix.reason, editId:j, count:fix.count }; data[field] = fix.fixed; App.edits[j].fixed = true; } // If there are no reasons, exit if (App.globals.reasons == {}) return false; // We need a place to store the reasons being applied to the summary. var reasons = []; App.globals.changes = 0; for (var z in App.globals.reasons) { // For each type of change made, add a reason string with the reason text, // optionally the rule ID, and the number of repeats if 2 or more. reasons.push(App.globals.reasons[z].reason + (App.globals.showRules ? ' ['+ App.globals.reasons[z].editId +']' : '') + (App.globals.showCounts ? ((App.globals.reasons[z].count > 1) ? ' ('+App.globals.reasons[z].count+')' : '') : '') ); App.globals.changes += App.globals.reasons[z].count; } var reasonStr = reasons.join('; ')+'.'; // Unique reasons separated by ; and terminated by . reasonStr = reasonStr.charAt(0).toUpperCase() + reasonStr.slice(1); // Cap first letter. if (!data.hasOwnProperty('summaryOrig')) data.summaryOrig = data.summary.trim(); // Remember original summary if (data.summaryOrig.length) data.summaryOrig = data.summaryOrig + ' '; data.summary = data.summaryOrig + reasonStr; // Limit summary to 300 chars if (data.summary.length > 300) data.summary = data.summary.substr(0,300-3) + '...'; return data; }; // Populate the diff App.pipeMods.diff = function() { App.selections.diff.empty().append('<div class="difftitle">' + App.funcs.diff(App.originals.title, App.items.title, true) + '</div>' + '<div class="diffbody">' + App.pipeMods.replace({body:App.funcs.diff(App.originals.body, App.items.body)}, true).body + '</div>'); App.funcs.showDiff(); } // Replace the previously omitted code App.pipeMods.replace = function(data, literal) { if (!data.body) return false; for (var type in App.globals.checksr) { var i = 0; data.body = data.body.replace(App.globals.placeHolderChecks[type], function(match) { var replace = App.globals.replacedStrings[type][i++]; if(literal && /block|lsec/.test(type)) { var after = replace.replace(/^\n\n/,''); var prepend = after !== replace ? '<span class="add">\n\n</span><span class="del">`</span>' : ''; var append = after !== replace ? '<span class="del">`</span>' : ''; var klass = /lsec/.test(type) ? ' class="lang-none prettyprint prettyprinted"' : ''; return prepend + '<pre' + klass + '><code>' + after.replace(/</g,'&lt;').replace(/^ /gm,'') + '</code></pre>' + append; } if(literal && /quote/.test(type)) return '<blockquote>' + replace.replace(/</g,'&lt;').replace(/^>/gm,'') + '</blockquote>'; if(literal) return '<code>' + replace.replace(/</g,'&lt;').replace(/(?:^`|`$)/g,'') + '</code>'; return replace; }); } return data; }; // Handle pipe output App.pipeMods.output = function(data) { App.selections.title.val(data.title); App.selections.body.val(data.body.replace(/\n{3,}/,'\n\n')); App.selections.summary.val(data.summary); App.globals.root.find('.actual-edit-overlay').remove(); App.selections.summary.css({opacity:1}); App.selections.buttonInfo.text(App.globals.changes + (App.globals.changes != 1 ? ' changes' : ' change')+' made'); StackExchange.MarkdownEditor.refreshAllPreviews(); }; // Init app App.init = function() { var count = 0; var toolbarchk = setInterval(function(){ if(++count === 10) clearInterval(toolbarchk); if(!App.globals.root.find('.wmd-button-row').length) return; clearInterval(toolbarchk); App.funcs.popSelections(); App.funcs.createButton(); App.funcs.applyListeners(); }, 100); return App; }; return App.init(); } try { var test = window.location.href.match(/.posts.(\d+).edit/); if(test) extendEditor($('form[action^="/posts/' + test[1] + '"]')); else $(document).ajaxComplete(function() { test = arguments[2].url.match(/posts.(\d+).edit-inline/); if(!test) { test = arguments[2].url.match(/review.inline-edit-post/); if(!test) return; test = arguments[2].data.match(/id=(\d+)/); if(!test) return; } extendEditor($('form[action^="/posts/' + test[1] + '"]')); }); if($('#post-form').length) $('#post-form').each(function(){ extendEditor($(this)); }); // This is the styling for the diff output. $('body').append('<style>' + '.difftitle {' + ' color: rgb(34, 34, 34);' + ' font-size: 24px;' + ' font-weight: normal;' + ' line-height: 36px;' + ' margin-bottom: 12px;' + '}' + '.diffbody {' + ' white-space: pre-wrap;' + ' font-family: "courier new", "lucida sans typewriter", mono, monospace' + '}' + '.add {' + ' background: #CFC;' + '}' + '.del {' + ' background: #FCC;' + '}' + '</style>'); } catch (e) { console.log(e); } })(); /* * To Title Case 2.1 – http://individed.com/code/to-title-case/ * Copyright © 2008–2013 David Gouch. Licensed under the MIT License. */ String.prototype.toTitleCase = function(){ var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i; return this.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function(match, index, title){ if (index > 0 && index + match.length !== title.length && match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" && (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') && title.charAt(index - 1).search(/[^\s-]/) < 0) { return match.toLowerCase(); } if (match.substr(1).search(/[A-Z]|\../) > -1) { return match; } return match.charAt(0).toUpperCase() + match.substr(1); }); };
Upversioned + new rules New: asp, written, pseudo, doesn_t_work, wpf, http, woff, ttf, bear_with_me, weird, believe, piece, sample Improved: jquery, vbnet, personally, doesn_t, i, problem, recommend
editor.user.js
Upversioned + new rules
<ide><path>ditor.user.js <ide> // @grant none <ide> // @license MIT <ide> // @namespace http://github.com/AstroCB <del>// @version 1.5.2.32 <add>// @version 1.5.2.33 <ide> // @description Fix common grammar/usage annoyances on Stack Exchange posts with a click <ide> // @include /^https?://\w*.?(stackoverflow|stackexchange|serverfault|superuser|askubuntu|stackapps)\.com/(questions|posts|review)/(?!tagged|new).*/ <ide> // ==/UserScript== <ide> reason: "trademark capitalization" <ide> }, <ide> jquery: { <del> expr: /\bjquery\b/gi, <add> expr: /\bjque?rr?y\b/gi, // jqury, jquerry, jqurry... ~600 spelling mistakes <ide> replacement: "jQuery", <ide> reason: "trademark capitalization" <ide> }, <ide> replacement: "Ubuntu", <ide> reason: "trademark capitalization" <ide> }, <del> vbnet: { // https://regex101.com/r/bB9pP3/1 <del> expr: /(?:vb|\s+)(?:\.net|\s*[0-9]+)\s*(?:framework|core)?/gi, <add> vbnet: { // https://regex101.com/r/bB9pP3/4 <add> expr: /(?:vb|asp|\s+|\()(?:\.net|\s*[0-9]+)\s*(?:framework|core)?/gi, <ide> replacement: function(str) { <ide> return str.replace(/vb/i, 'VB') <add> .replace(/asp/i, 'ASP') <ide> .replace(/net/i, 'NET') <ide> .replace(/framework/i, 'Framework') <ide> .replace(/core/i, 'Core'); <ide> }, <ide> reason: "trademark capitalization" <ide> }, <add> asp: { <add> expr: /([^\b\w.]|^)asp/gi, <add> replacement: function (match) { return match.toUpperCase(); }, <add> reason: "trademark capitalization" <add> }, <ide> regex: { <ide> expr: /\bregex(p)?\b/gi, <ide> replacement: "RegEx$1", <ide> replacement: "$1ifferen$2", <ide> reason: "grammar and spelling" <ide> }, <del> personally: { // https://regex101.com/r/oL9aM1/1 <del> expr: /\b(p)ersona?l?(ly)?\b/gi, <add> personally: { // https://regex101.com/r/oL9aM1/2 <add> expr: /\b(p)erso(?:nl|nl|nal)(ly)?\b/gi, <ide> replacement: "$1ersonal$2", <ide> reason: "grammar and spelling" <ide> }, <del> problem: { <del> expr: /\b(p)orblem(s)?\b/gi, <add> problem: { // https://regex101.com/r/yA8jM7/1 <add> expr: /\b(p)(?:or|ro)b(?:le|el)m(s)?\b/gi, <ide> replacement: "$1roblem$2", <add> reason: "grammar and spelling" <add> }, <add> written: { <add> expr: /\b(w)riten\b/gi, <add> replacement: "$1ritten", <ide> reason: "grammar and spelling" <ide> }, <ide> maybe: { <ide> expr: /\b(m)aby\b/gi, <ide> replacement: "$1aybe", <add> reason: "grammar and spelling" <add> }, <add> pseudo: { <add> expr: /\b(p)suedo\b/gi, <add> replacement: "$1seudo", <ide> reason: "grammar and spelling" <ide> }, <ide> // Noise reduction <ide> replacement: "$1'$2", <ide> reason: "grammar and spelling" <ide> }, <del> doesn_t: { <del> expr: /\b(d)ose?nt\b/gi, <add> doesn_t: { // https://regex101.com/r/sL0uO9/1 <add> expr: /\b(d)ose?n'?t\b/gi, <ide> replacement: "$1oesn't", <add> reason: "grammar and spelling" <add> }, <add> doesn_t_work: { // >4K instances of this (Oct 2015) <add> expr: /\b(d)oesn\'t (work|like|think|want|put|save|load|get|help|make)s\b/gi, <add> replacement: "$1oesn't $2", <ide> reason: "grammar and spelling" <ide> }, <ide> prolly: { <ide> replacement: "$1eyboard", <ide> reason: "grammar and spelling" <ide> }, <del> i: { <del> expr: /\bi('|\b)/g, // i or i-apostrophe <add> i: { // https://regex101.com/r/uO7qG0/1 <add> expr: /\bi('|\b)(?!.e.)/g, // i or i-apostrophe <ide> replacement: "I", <ide> reason: "grammar and spelling" <ide> }, <ide> }, <ide> tcp: { <ide> expr: /(?:[^\b\w.]|^)tcp\b/gi, <add> replacement: function (match) { return match.toUpperCase(); }, <add> reason: "acronym capitalization" <add> }, <add> wpf: { <add> expr: /(?:[^\b\w.]|^)wpf\b/gi, <add> replacement: function (match) { return match.toUpperCase(); }, <add> reason: "acronym capitalization" <add> }, <add> http: { <add> expr: /(?:[^\b\w.]|^)https?\b/gi, <add> replacement: function (match) { return match.toUpperCase(); }, <add> reason: "acronym capitalization" <add> }, <add> woff: { <add> expr: /(?:[^\b\w.]|^)woff\b/gi, <add> replacement: function (match) { return match.toUpperCase(); }, <add> reason: "acronym capitalization" <add> }, <add> ttf: { <add> expr: /(?:[^\b\w.]|^)ttf\b/gi, <ide> replacement: function (match) { return match.toUpperCase(); }, <ide> reason: "acronym capitalization" <ide> }, <ide> replacement: "$1rogramm$2", <ide> reason: "grammar and spelling" <ide> }, <add> bear_with_me: { <add> expr: /\b(b)are (with me|it|in mind)\b/gi, <add> replacement: "$1ear $2", <add> reason: "grammar and spelling" <add> }, <add> weird: { <add> expr: /\b(w)ierd(ness|ly)\b/gi, <add> replacement: "$1eird$2", <add> reason: "grammar and spelling" <add> }, <add> believe: { <add> expr: /\b(b)eleive(r|s|d)?\b/gi, <add> replacement: "$1elieve$2", <add> reason: "grammar and spelling" <add> }, <add> piece: { <add> expr: /\b(p)eice(s|d)?\b/gi, <add> replacement: "$1iece$2", <add> reason: "grammar and spelling" <add> }, <add> sample: { <add> expr: /\b(s)maple(s|d)?\b/gi, <add> replacement: "$1ample$2", <add> reason: "grammar and spelling" <add> }, <ide> twitter: { <ide> expr: /\btwitter\b/gi, <ide> replacement: "Twitter", <ide> replacement: "$1ndependent$2", <ide> reason: "grammar and spelling" <ide> }, <del> recommend: { <del> expr: /\b(r)ecomm?and(ation)?\b/gi, <add> recommend: { // https://regex101.com/r/pP9lB7/1 <add> expr: /\b(r)ecomm?[ao]nd(ation)?\b/gi, <ide> replacement: "$1ecommend$2", <ide> reason: "grammar and spelling" <ide> },
Java
mit
65f9bf5fa7899887d6e4adfcafc3ec0f5e39603d
0
dreamhead/moco,dreamhead/moco
package com.github.dreamhead.moco; import com.github.dreamhead.moco.resource.Resource; public final class HttpHeader implements ResponseElement { private String name; private Resource value; public HttpHeader(final String name, final Resource value) { this.name = name; this.value = value; } public String getName() { return name; } public Resource getValue() { return value; } }
moco-core/src/main/java/com/github/dreamhead/moco/HttpHeader.java
package com.github.dreamhead.moco; import com.github.dreamhead.moco.resource.Resource; public class HttpHeader implements ResponseElement { private String name; private Resource value; public HttpHeader(final String name, final Resource value) { this.name = name; this.value = value; } public String getName() { return name; } public Resource getValue() { return value; } }
added missing final to http header
moco-core/src/main/java/com/github/dreamhead/moco/HttpHeader.java
added missing final to http header
<ide><path>oco-core/src/main/java/com/github/dreamhead/moco/HttpHeader.java <ide> <ide> import com.github.dreamhead.moco.resource.Resource; <ide> <del>public class HttpHeader implements ResponseElement { <add>public final class HttpHeader implements ResponseElement { <ide> private String name; <ide> private Resource value; <ide>
Java
mit
4ae667b5d8d83c7a3574fc82900dec0c8ee439ce
0
ControlSystemStudio/diirt,diirt/diirt,berryma4/diirt,ControlSystemStudio/diirt,diirt/diirt,richardfearn/diirt,richardfearn/diirt,diirt/diirt,berryma4/diirt,berryma4/diirt,ControlSystemStudio/diirt,ControlSystemStudio/diirt,berryma4/diirt,richardfearn/diirt,diirt/diirt
/** * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.epics.vtype; import java.text.NumberFormat; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.epics.util.text.NumberFormats; import org.epics.util.array.ArrayDouble; import org.epics.util.array.ArrayInt; import org.epics.util.array.ListByte; import org.epics.util.array.ListDouble; import org.epics.util.array.ListFloat; import org.epics.util.array.ListInt; import org.epics.util.array.ListNumber; import org.epics.util.array.ListNumbers; import org.epics.util.array.ListShort; import org.epics.util.time.Timestamp; /** * Factory class for all concrete implementation of the types. * <p> * The factory methods do not do anything in terms of defensive copy and * immutability to the objects, which they are passed as they are. It's the * client responsibility to prepare them appropriately, which is automatically * done anyway for all objects except collections. * * @author carcassi */ public class ValueFactory { /** * Creates a new VString. * * @param value the string value * @param alarm the alarm * @param time the time * @return the new value */ public static VString newVString(final String value, final Alarm alarm, final Time time) { return new IVString(value, alarm, time); } /** * Creates a new VBoolean. * * @param value the boolean value * @param alarm the alarm * @param time the time * @return the new value */ public static VBoolean newVBoolean(final boolean value, final Alarm alarm, final Time time) { return new IVBoolean(value, alarm, time); } /** * Creates a new VMultiDouble. * * @param values the values * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VMultiDouble newVMultiDouble(List<VDouble> values, final Alarm alarm, final Time time, final Display display) { return new IVMultiDouble(values, alarm, time, display); } /** * Creates a new VInt. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VInt newVInt(final Integer value, final Alarm alarm, final Time time, final Display display) { return new IVInt(value, alarm, time, display); } /** * Creates a new VShort. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VShort newVShort(final Short value, final Alarm alarm, final Time time, final Display display) { return new IVShort(value, alarm, time, display); } /** * Creates a new VByte. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VByte newVByte(final Byte value, final Alarm alarm, final Time time, final Display display) { return new IVByte(value, alarm, time, display); } /** * New alarm with the given severity and status. * * @param alarmSeverity the alarm severity * @param alarmName the alarm name * @return the new alarm */ public static Alarm newAlarm(final AlarmSeverity alarmSeverity, final String alarmName) { return new Alarm() { @Override public AlarmSeverity getAlarmSeverity() { return alarmSeverity; } @Override public String getAlarmName() { return alarmName; } @Override public String toString() { return VTypeToString.alarmToString(this); } }; } private static final Alarm alarmNone = newAlarm(AlarmSeverity.NONE, "NONE"); private static final Display displayBoolean = newDisplay(0.0, 0.0, 0.0, "", NumberFormats.toStringFormat(), 1.0, 1.0, 1.0, 0.0, 1.0); /** * No alarm. * * @return severity and status NONE */ public static Alarm alarmNone() { return alarmNone; } /** * Alarm based on the value and the display ranges. * * @param value the value * @param display the display information * @return the new alarm */ public static Alarm newAlarm(Number value, Display display) { // Calculate new AlarmSeverity, using display ranges AlarmSeverity severity = AlarmSeverity.NONE; String status = "NONE"; if (value.doubleValue() <= display.getLowerAlarmLimit()) { status = "LOLO"; severity = AlarmSeverity.MAJOR; } else if (value.doubleValue() >= display.getUpperAlarmLimit()) { status = "HIHI"; severity = AlarmSeverity.MAJOR; } else if (value.doubleValue() <= display.getLowerWarningLimit()) { status = "LOW"; severity = AlarmSeverity.MINOR; } else if (value.doubleValue() >= display.getUpperWarningLimit()) { status = "HIGH"; severity = AlarmSeverity.MINOR; } return newAlarm(severity, status); } /** * Creates a new time. * * @param timestamp the timestamp * @param timeUserTag the user tag * @param timeValid whether the time is valid * @return the new time */ public static Time newTime(final Timestamp timestamp, final Integer timeUserTag, final boolean timeValid) { return new Time() { @Override public Timestamp getTimestamp() { return timestamp; } @Override public Integer getTimeUserTag() { return timeUserTag; } @Override public boolean isTimeValid() { return timeValid; } }; } /** * New time, with no user tag and valid data. * * @param timestamp the timestamp * @return the new time */ public static Time newTime(final Timestamp timestamp) { return newTime(timestamp, null, true); } /** * New time with the current timestamp, no user tag and valid data. * * @return the new time */ public static Time timeNow() { return newTime(Timestamp.now(), null, true); } /** * Creates a new display * * @param lowerDisplayLimit lower display limit * @param lowerAlarmLimit lower alarm limit * @param lowerWarningLimit lower warning limit * @param units the units * @param numberFormat the formatter * @param upperWarningLimit the upper warning limit * @param upperAlarmLimit the upper alarm limit * @param upperDisplayLimit the upper display limit * @param lowerCtrlLimit the lower control limit * @param upperCtrlLimit the upper control limit * @return the new display */ public static Display newDisplay(final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new Display() { @Override public Double getLowerCtrlLimit() { return lowerCtrlLimit; } @Override public Double getUpperCtrlLimit() { return upperCtrlLimit; } @Override public Double getLowerDisplayLimit() { return lowerDisplayLimit; } @Override public Double getLowerAlarmLimit() { return lowerAlarmLimit; } @Override public Double getLowerWarningLimit() { return lowerWarningLimit; } @Override public String getUnits() { return units; } @Override public NumberFormat getFormat() { return numberFormat; } @Override public Double getUpperWarningLimit() { return upperWarningLimit; } @Override public Double getUpperAlarmLimit() { return upperAlarmLimit; } @Override public Double getUpperDisplayLimit() { return upperDisplayLimit; } }; } public static ArrayDimensionDisplay newDisplay(final ListNumber boundaries, final String unit) { return new ArrayDimensionDisplay() { @Override public ListNumber getCellBoundaries() { return boundaries; } @Override public String getUnits() { return unit; } }; } /** * Returns an array display where the index is used to calculate the * cell boundaries. * * @param nCells the number of cells along the direction * @return a new array display */ public static ArrayDimensionDisplay newDisplay(int nCells) { final ListNumber boundaries = ListNumbers.linearList(0, 1, nCells + 1); return newDisplay(boundaries, ""); } private static final Display displayNone = newDisplay(Double.NaN, Double.NaN, Double.NaN, "", NumberFormats.toStringFormat(), Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN); /** * Empty display information. * * @return no display */ public static Display displayNone() { return displayNone; } /** * Returns a display from 0 to 1, suitable for booleans. * * @return a display for boolean */ public static Display displayBoolean() { return displayBoolean; } /** * Creates a new VNumber based on the type of the data * * @param value * @param alarm * @param time * @param display * @return */ public static VNumber newVNumber(Number value, Alarm alarm, Time time, Display display){ if(value instanceof Double){ return newVDouble((Double) value, alarm, time, display); }else if(value instanceof Integer){ return newVInt((Integer)value, alarm, time, display); }else if(value instanceof Short){ return newVShort((Short)value, alarm, time, display); }else if(value instanceof Byte){ return newVByte((Byte)value, alarm, time, display); }else if(value instanceof Float){ return newVFloat((Float)value, alarm, time, display); } throw new UnsupportedOperationException(); } /** * Creates a new VDouble. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VDouble newVDouble(final Double value, final Alarm alarm, final Time time, final Display display) { return new IVDouble(value, alarm, time, display); } /** * Creates a new VDouble using the given value, time, display and * generating the alarm from the value and display information. * * @param value the new value * @param time the time * @param display the display information * @return the new value */ public static VDouble newVDouble(Double value, Time time, Display display) { return newVDouble(value, newAlarm(value, display), time, display); } /** * Creates new immutable VDouble by using metadata from the old value, * now as timestamp and computing alarm from the metadata range. * * @param value new numeric value * @param display metadata * @return new value */ public static VDouble newVDouble(Double value, Display display) { return newVDouble(value, timeNow(), display); } /** * Creates a new VDouble, no alarm, time now, no display. * * @param value the value * @return the new value */ public static VDouble newVDouble(Double value) { return newVDouble(value, alarmNone(), timeNow(), displayNone()); } /** * Creates a new VDouble, no alarm, no display. * * @param value the value * @param time the time * @return the new value */ public static VDouble newVDouble(Double value, Time time) { return newVDouble(value, alarmNone(), time, displayNone()); } /** * Creates a new VFloat. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VFloat newVFloat(final Float value, final Alarm alarm, final Time time, final Display display) { return new IVFloat(value, alarm, time, display); } /** * Create a new VEnum. * * @param index the index in the label array * @param labels the labels * @param alarm the alarm * @param time the time * @return the new value */ public static VEnum newVEnum(int index, List<String> labels, Alarm alarm, Time time) { return new IVEnum(index, labels, alarm, time); } /** * Creates a new VStatistics. * * @param average average * @param stdDev standard deviation * @param min minimum * @param max maximum * @param nSamples number of samples * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VStatistics newVStatistics(final double average, final double stdDev, final double min, final double max, final int nSamples, final Alarm alarm, final Time time, final Display display) { return new IVStatistics(average, stdDev, min, max, nSamples, alarm, time, display); } /** * Creates a new VNumberArray based on the type of the data. * * @param data the array data * @param alarm the alarm * @param time the time * @param display the display * @return a new value */ public static VNumberArray newVNumberArray(final ListNumber data, final Alarm alarm, final Time time, final Display display){ ListInt sizes = new ArrayInt(data.size()); List<ArrayDimensionDisplay> dimensionDisplay = ValueUtil.defaultArrayDisplay(sizes); return newVNumberArray(data, sizes, dimensionDisplay, alarm, time, display); } /** * Creates a new VNumberArray based on the type of the data. * * @param data the array data * @param sizes the array shape * @param dimensionDisplay the array axis display information * @param alarm the alarm * @param time the time * @param display the display * @return a new value */ public static VNumberArray newVNumberArray(final ListNumber data, final ListInt sizes, final List<ArrayDimensionDisplay> dimensionDisplay, final Alarm alarm, final Time time, final Display display){ if (data instanceof ListDouble){ return new IVDoubleArray((ListDouble) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListFloat){ return new IVFloatArray((ListFloat) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListInt){ return new IVIntArray((ListInt) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListByte){ return new IVByteArray((ListByte) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListShort){ return new IVShortArray((ListShort) data, sizes, dimensionDisplay, alarm, time, display); } throw new UnsupportedOperationException("Data is of an unsupported type (" + data.getClass() + ")"); } /** * Creates a new VDoubleArray. * * @param data array data * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VDoubleArray newVDoubleArray(ListDouble data, Alarm alarm, Time time, Display display) { return new IVDoubleArray(data, new ArrayInt(data.size()), alarm, time, display); } /** * Creates a new VFloatArray. * * @param data array data * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VFloatArray newVFloatArray(ListFloat data, Alarm alarm, Time time, Display display) { return new IVFloatArray(data, new ArrayInt(data.size()), alarm, time, display); } /** * Creates a new VImage given the data and the size. * * @param height the height * @param width the width * @param data the data * @return a new object */ public static VImage newVImage(int height, int width, byte[] data) { return new IVImage(height, width, data); } /** * Creates a new VIntArray. * * @param values array values * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VIntArray newVIntArray(final ListInt values, Alarm alarm, Time time, Display display) { return new IVIntArray(values, new ArrayInt(values.size()), alarm, time, display); } /** * Create a new VEnumArray. * * @param indexes the indexes in the label array * @param labels the labels * @param alarm the alarm * @param time the time * @return the new value */ public static VEnumArray newVEnumArray(ListInt indexes, List<String> labels, Alarm alarm, Time time) { return new IVEnumArray(indexes, labels, new ArrayInt(indexes.size()), alarm, time); } /** * Creates a new VStringArray. * * @param data the strings * @param alarm the alarm * @param time the time * @return the new value */ public static VStringArray newVStringArray(List<String> data, Alarm alarm, Time time) { return new IVStringArray(data, new ArrayInt(data.size()), alarm, time); } /** * Creates a new VTable - this method is provisional and will change in the future. * * @param types the types for each column * @param names the names for each column * @param values the values for each column * @return the new value */ public static VTable newVTable(List<Class<?>> types, List<String> names, List<Object> values) { return new IVTable(types, names, values); } /** * Takes a java objects and wraps it into a vType. All numbers are wrapped * as VDouble. String is wrapped as VString. double[] and ListDouble are wrapped as * VDoubleArray. A List of String is wrapped to a VStringArray. Alarms * are alarmNone(), time are timeNow() and display are displayNone(); * * @param value the value to wrap * @return the wrapped value * @deprecated use {@link #toVType() } */ @Deprecated public static VType wrapValue(Object value) { return wrapValue(value, alarmNone()); } /** * Takes a java objects and wraps it into a vType. All numbers are wrapped * as VDouble. String is wrapped as VString. double[] and ListDouble are wrapped as * VDoubleArray. A List of String is wrapped to a VStringArray. Alarms * are alarm, time are timeNow() and display are displayNone(); * * @param value the value to wrap * @param alarm the alarm for the value * @return the wrapped value * @deprecated use {@link #toVType(java.lang.Object, org.epics.vtype.Alarm, org.epics.vtype.Time, org.epics.vtype.Display) } */ @Deprecated public static VType wrapValue(Object value, Alarm alarm) { if (value instanceof Number) { // Special support for numbers return newVDouble(((Number) value).doubleValue(), alarm, timeNow(), displayNone()); } else if (value instanceof String) { // Special support for strings return newVString(((String) value), alarm, timeNow()); } else if (value instanceof double[]) { return newVDoubleArray(new ArrayDouble((double[]) value), alarm, timeNow(), displayNone()); } else if (value instanceof ListDouble) { return newVDoubleArray((ListDouble) value, alarm, timeNow(), displayNone()); } else if (value instanceof List) { boolean matches = true; List list = (List) value; for (Object object : list) { if (!(object instanceof String)) { matches = false; } } if (matches) { @SuppressWarnings("unchecked") List<String> newList = (List<String>) list; return newVStringArray(Collections.unmodifiableList(newList), alarm, timeNow()); } else { throw new UnsupportedOperationException("Type " + value.getClass().getName() + " contains non Strings"); } } else { // TODO: need to implement all the other arrays throw new UnsupportedOperationException("Type " + value.getClass().getName() + " is not yet supported"); } } /** * Converts a standard java type to VTypes. Returns null if no conversion * is possible. Calls {@link #toVType(java.lang.Object, org.epics.vtype.Alarm, org.epics.vtype.Time, org.epics.vtype.Display) * with no alarm, time now and no display. * * @param javaObject the value to wrap * @return the new VType value */ public static VType toVType(Object javaObject) { return toVType(javaObject, alarmNone(), timeNow(), displayNone()); } /** * Converts a standard java type to VTypes. Returns null if no conversion * is possible. * <p> * Types are converted as follow: * <ul> * <li>Boolean -> VBoolean</li> * <li>Number -> corresponding VNumber</li> * <li>String -> VString</li> * <li>number array -> corresponding VNumberArray</li> * <li>ListNumber -> corresponding VNumberArray</li> * <li>List-> if all elements are String, VStringArray</li> * </ul> * * @param javaObject the value to wrap * @param alarm the alarm * @param time the time * @param display the display * @return the new VType value */ public static VType toVType(Object javaObject, Alarm alarm, Time time, Display display) { if (javaObject instanceof Number) { return ValueFactory.newVNumber((Number) javaObject, alarm, time, display); } else if (javaObject instanceof String) { return newVString((String) javaObject, alarm, time); } else if (javaObject instanceof Boolean) { return newVBoolean((Boolean) javaObject, alarm, time); } else if (javaObject instanceof byte[] || javaObject instanceof short[] || javaObject instanceof int[] || javaObject instanceof long[] || javaObject instanceof float[] || javaObject instanceof double[]) { return newVNumberArray(ListNumbers.toListNumber(javaObject), alarm, time, display); } else if (javaObject instanceof ListNumber) { return newVNumberArray((ListNumber) javaObject, alarm, time, display); } else if (javaObject instanceof String[]) { return newVStringArray(Arrays.asList((String[]) javaObject), alarm, time); } else if (javaObject instanceof List) { boolean matches = true; List list = (List) javaObject; for (Object object : list) { if (!(object instanceof String)) { matches = false; } } if (matches) { @SuppressWarnings("unchecked") List<String> newList = (List<String>) list; return newVStringArray(Collections.unmodifiableList(newList), alarm, time); } else { return null; } } else { return null; } } /** * As {@link #toVType(java.lang.Object)} but throws an exception * if conversion not possible. * * @param javaObject the value to wrap * @return the new VType value */ public static VType toVTypeChecked(Object javaObject) { VType value = toVType(javaObject); if (value == null) { throw new RuntimeException("Value " + value + " cannot be converted to VType."); } return value; } /** * As {@link #toVType(java.lang.Object, org.epics.vtype.Alarm, org.epics.vtype.Time, org.epics.vtype.Display)} but throws an exception * if conversion not possible. * * @param javaObject the value to wrap * @param alarm the alarm * @param time the time * @param display the display * @return the new VType value */ public static VType toVTypeChecked(Object javaObject, Alarm alarm, Time time, Display display) { VType value = toVType(javaObject, alarm, time, display); if (value == null) { throw new RuntimeException("Value " + value + " cannot be converted to VType."); } return value; } }
epics-vtype/src/main/java/org/epics/vtype/ValueFactory.java
/** * Copyright (C) 2010-14 pvmanager developers. See COPYRIGHT.TXT * All rights reserved. Use is subject to license terms. See LICENSE.TXT */ package org.epics.vtype; import java.text.NumberFormat; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.epics.util.text.NumberFormats; import org.epics.util.array.ArrayDouble; import org.epics.util.array.ArrayInt; import org.epics.util.array.ListByte; import org.epics.util.array.ListDouble; import org.epics.util.array.ListFloat; import org.epics.util.array.ListInt; import org.epics.util.array.ListNumber; import org.epics.util.array.ListNumbers; import org.epics.util.array.ListShort; import org.epics.util.time.Timestamp; /** * Factory class for all concrete implementation of the types. * <p> * The factory methods do not do anything in terms of defensive copy and * immutability to the objects, which they are passed as they are. It's the * client responsibility to prepare them appropriately, which is automatically * done anyway for all objects except collections. * * @author carcassi */ public class ValueFactory { /** * Creates a new VString. * * @param value the string value * @param alarm the alarm * @param time the time * @return the new value */ public static VString newVString(final String value, final Alarm alarm, final Time time) { return new IVString(value, alarm, time); } /** * Creates a new VBoolean. * * @param value the boolean value * @param alarm the alarm * @param time the time * @return the new value */ public static VBoolean newVBoolean(final boolean value, final Alarm alarm, final Time time) { return new IVBoolean(value, alarm, time); } /** * Creates a new VMultiDouble. * * @param values the values * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VMultiDouble newVMultiDouble(List<VDouble> values, final Alarm alarm, final Time time, final Display display) { return new IVMultiDouble(values, alarm, time, display); } /** * Creates a new VInt. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VInt newVInt(final Integer value, final Alarm alarm, final Time time, final Display display) { return new IVInt(value, alarm, time, display); } /** * Creates a new VShort. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VShort newVShort(final Short value, final Alarm alarm, final Time time, final Display display) { return new IVShort(value, alarm, time, display); } /** * Creates a new VByte. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VByte newVByte(final Byte value, final Alarm alarm, final Time time, final Display display) { return new IVByte(value, alarm, time, display); } /** * New alarm with the given severity and status. * * @param alarmSeverity the alarm severity * @param alarmName the alarm name * @return the new alarm */ public static Alarm newAlarm(final AlarmSeverity alarmSeverity, final String alarmName) { return new Alarm() { @Override public AlarmSeverity getAlarmSeverity() { return alarmSeverity; } @Override public String getAlarmName() { return alarmName; } @Override public String toString() { return VTypeToString.alarmToString(this); } }; } private static final Alarm alarmNone = newAlarm(AlarmSeverity.NONE, "NONE"); private static final Display displayBoolean = newDisplay(0.0, 0.0, 0.0, "", NumberFormats.toStringFormat(), 1.0, 1.0, 1.0, 0.0, 1.0); /** * No alarm. * * @return severity and status NONE */ public static Alarm alarmNone() { return alarmNone; } /** * Alarm based on the value and the display ranges. * * @param value the value * @param display the display information * @return the new alarm */ public static Alarm newAlarm(Number value, Display display) { // Calculate new AlarmSeverity, using display ranges AlarmSeverity severity = AlarmSeverity.NONE; String status = "NONE"; if (value.doubleValue() <= display.getLowerAlarmLimit()) { status = "LOLO"; severity = AlarmSeverity.MAJOR; } else if (value.doubleValue() >= display.getUpperAlarmLimit()) { status = "HIHI"; severity = AlarmSeverity.MAJOR; } else if (value.doubleValue() <= display.getLowerWarningLimit()) { status = "LOW"; severity = AlarmSeverity.MINOR; } else if (value.doubleValue() >= display.getUpperWarningLimit()) { status = "HIGH"; severity = AlarmSeverity.MINOR; } return newAlarm(severity, status); } /** * Creates a new time. * * @param timestamp the timestamp * @param timeUserTag the user tag * @param timeValid whether the time is valid * @return the new time */ public static Time newTime(final Timestamp timestamp, final Integer timeUserTag, final boolean timeValid) { return new Time() { @Override public Timestamp getTimestamp() { return timestamp; } @Override public Integer getTimeUserTag() { return timeUserTag; } @Override public boolean isTimeValid() { return timeValid; } }; } /** * New time, with no user tag and valid data. * * @param timestamp the timestamp * @return the new time */ public static Time newTime(final Timestamp timestamp) { return newTime(timestamp, null, true); } /** * New time with the current timestamp, no user tag and valid data. * * @return the new time */ public static Time timeNow() { return newTime(Timestamp.now(), null, true); } /** * Creates a new display * * @param lowerDisplayLimit lower display limit * @param lowerAlarmLimit lower alarm limit * @param lowerWarningLimit lower warning limit * @param units the units * @param numberFormat the formatter * @param upperWarningLimit the upper warning limit * @param upperAlarmLimit the upper alarm limit * @param upperDisplayLimit the upper display limit * @param lowerCtrlLimit the lower control limit * @param upperCtrlLimit the upper control limit * @return the new display */ public static Display newDisplay(final Double lowerDisplayLimit, final Double lowerAlarmLimit, final Double lowerWarningLimit, final String units, final NumberFormat numberFormat, final Double upperWarningLimit, final Double upperAlarmLimit, final Double upperDisplayLimit, final Double lowerCtrlLimit, final Double upperCtrlLimit) { return new Display() { @Override public Double getLowerCtrlLimit() { return lowerCtrlLimit; } @Override public Double getUpperCtrlLimit() { return upperCtrlLimit; } @Override public Double getLowerDisplayLimit() { return lowerDisplayLimit; } @Override public Double getLowerAlarmLimit() { return lowerAlarmLimit; } @Override public Double getLowerWarningLimit() { return lowerWarningLimit; } @Override public String getUnits() { return units; } @Override public NumberFormat getFormat() { return numberFormat; } @Override public Double getUpperWarningLimit() { return upperWarningLimit; } @Override public Double getUpperAlarmLimit() { return upperAlarmLimit; } @Override public Double getUpperDisplayLimit() { return upperDisplayLimit; } }; } public static ArrayDimensionDisplay newDisplay(final ListNumber boundaries, final String unit) { return new ArrayDimensionDisplay() { @Override public ListNumber getCellBoundaries() { return boundaries; } @Override public String getUnits() { return unit; } }; } /** * Returns an array display where the index is used to calculate the * cell boundaries. * * @param nCells the number of cells along the direction * @return a new array display */ public static ArrayDimensionDisplay newDisplay(int nCells) { final ListNumber boundaries = ListNumbers.linearList(0, 1, nCells + 1); return newDisplay(boundaries, ""); } private static final Display displayNone = newDisplay(Double.NaN, Double.NaN, Double.NaN, "", NumberFormats.toStringFormat(), Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN); /** * Empty display information. * * @return no display */ public static Display displayNone() { return displayNone; } /** * Returns a display from 0 to 1, suitable for booleans. * * @return a display for boolean */ public static Display displayBoolean() { return displayBoolean; } /** * Creates a new VNumber based on the type of the data * * @param value * @param alarm * @param time * @param display * @return */ public static VNumber newVNumber(Number value, Alarm alarm, Time time, Display display){ if(value instanceof Double){ return newVDouble((Double) value, alarm, time, display); }else if(value instanceof Integer){ return newVInt((Integer)value, alarm, time, display); }else if(value instanceof Short){ return newVShort((Short)value, alarm, time, display); }else if(value instanceof Byte){ return newVByte((Byte)value, alarm, time, display); }else if(value instanceof Float){ return newVFloat((Float)value, alarm, time, display); } throw new UnsupportedOperationException(); } /** * Creates a new VDouble. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VDouble newVDouble(final Double value, final Alarm alarm, final Time time, final Display display) { return new IVDouble(value, alarm, time, display); } /** * Creates a new VDouble using the given value, time, display and * generating the alarm from the value and display information. * * @param value the new value * @param time the time * @param display the display information * @return the new value */ public static VDouble newVDouble(Double value, Time time, Display display) { return newVDouble(value, newAlarm(value, display), time, display); } /** * Creates new immutable VDouble by using metadata from the old value, * now as timestamp and computing alarm from the metadata range. * * @param value new numeric value * @param display metadata * @return new value */ public static VDouble newVDouble(Double value, Display display) { return newVDouble(value, timeNow(), display); } /** * Creates a new VDouble, no alarm, time now, no display. * * @param value the value * @return the new value */ public static VDouble newVDouble(Double value) { return newVDouble(value, alarmNone(), timeNow(), displayNone()); } /** * Creates a new VDouble, no alarm, no display. * * @param value the value * @param time the time * @return the new value */ public static VDouble newVDouble(Double value, Time time) { return newVDouble(value, alarmNone(), time, displayNone()); } /** * Creates a new VFloat. * * @param value the value * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VFloat newVFloat(final Float value, final Alarm alarm, final Time time, final Display display) { return new IVFloat(value, alarm, time, display); } /** * Create a new VEnum. * * @param index the index in the label array * @param labels the labels * @param alarm the alarm * @param time the time * @return the new value */ public static VEnum newVEnum(int index, List<String> labels, Alarm alarm, Time time) { return new IVEnum(index, labels, alarm, time); } /** * Creates a new VStatistics. * * @param average average * @param stdDev standard deviation * @param min minimum * @param max maximum * @param nSamples number of samples * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VStatistics newVStatistics(final double average, final double stdDev, final double min, final double max, final int nSamples, final Alarm alarm, final Time time, final Display display) { return new IVStatistics(average, stdDev, min, max, nSamples, alarm, time, display); } /** * Creates a new VDoubleArray. * * @param values array values * @param sizes sizes * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ @Deprecated public static VDoubleArray newVDoubleArray(final double[] values, final ListInt sizes, Alarm alarm, Time time, Display display) { return new IVDoubleArray(new ArrayDouble(values), sizes, alarm, time, display); } /** * Creates a new VNumberArray based on the type of the data. * * @param data the array data * @param alarm the alarm * @param time the time * @param display the display * @return a new value */ public static VNumberArray newVNumberArray(final ListNumber data, final Alarm alarm, final Time time, final Display display){ ListInt sizes = new ArrayInt(data.size()); List<ArrayDimensionDisplay> dimensionDisplay = ValueUtil.defaultArrayDisplay(sizes); return newVNumberArray(data, sizes, dimensionDisplay, alarm, time, display); } /** * Creates a new VNumberArray based on the type of the data. * * @param data the array data * @param sizes the array shape * @param dimensionDisplay the array axis display information * @param alarm the alarm * @param time the time * @param display the display * @return a new value */ public static VNumberArray newVNumberArray(final ListNumber data, final ListInt sizes, final List<ArrayDimensionDisplay> dimensionDisplay, final Alarm alarm, final Time time, final Display display){ if (data instanceof ListDouble){ return new IVDoubleArray((ListDouble) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListFloat){ return new IVFloatArray((ListFloat) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListInt){ return new IVIntArray((ListInt) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListByte){ return new IVByteArray((ListByte) data, sizes, dimensionDisplay, alarm, time, display); } else if (data instanceof ListShort){ return new IVShortArray((ListShort) data, sizes, dimensionDisplay, alarm, time, display); } throw new UnsupportedOperationException("Data is of an unsupported type (" + data.getClass() + ")"); } /** * Creates a new VDoubleArray. * * @param values array values * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ @Deprecated public static VDoubleArray newVDoubleArray(final double[] values, Alarm alarm, Time time, Display display) { return newVDoubleArray(values, new ArrayInt(values.length), alarm, time, display); } /** * Creates a new VDoubleArray. * * @param data array data * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VDoubleArray newVDoubleArray(ListDouble data, Alarm alarm, Time time, Display display) { return new IVDoubleArray(data, new ArrayInt(data.size()), alarm, time, display); } /** * Creates a new VFloatArray. * * @param data array data * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VFloatArray newVFloatArray(ListFloat data, Alarm alarm, Time time, Display display) { return new IVFloatArray(data, new ArrayInt(data.size()), alarm, time, display); } /** * Creates a new VDoubleArray. * * @param values array values * @param display the display * @return the new value */ @Deprecated public static VDoubleArray newVDoubleArray(final double[] values, Display display) { return newVDoubleArray(values, new ArrayInt(values.length), alarmNone(), timeNow(), display); } /** * Creates a new VImage given the data and the size. * * @param height the height * @param width the width * @param data the data * @return a new object */ public static VImage newVImage(int height, int width, byte[] data) { return new IVImage(height, width, data); } /** * Creates a new VIntArray. * * @param values array values * @param alarm the alarm * @param time the time * @param display the display * @return the new value */ public static VIntArray newVIntArray(final ListInt values, Alarm alarm, Time time, Display display) { return new IVIntArray(values, new ArrayInt(values.size()), alarm, time, display); } /** * Create a new VEnumArray. * * @param indexes the indexes in the label array * @param labels the labels * @param alarm the alarm * @param time the time * @return the new value */ public static VEnumArray newVEnumArray(ListInt indexes, List<String> labels, Alarm alarm, Time time) { return new IVEnumArray(indexes, labels, new ArrayInt(indexes.size()), alarm, time); } /** * Creates a new VStringArray. * * @param data the strings * @param alarm the alarm * @param time the time * @return the new value */ public static VStringArray newVStringArray(List<String> data, Alarm alarm, Time time) { return new IVStringArray(data, new ArrayInt(data.size()), alarm, time); } /** * Creates a new VTable - this method is provisional and will change in the future. * * @param types the types for each column * @param names the names for each column * @param values the values for each column * @return the new value */ public static VTable newVTable(List<Class<?>> types, List<String> names, List<Object> values) { return new IVTable(types, names, values); } /** * Takes a java objects and wraps it into a vType. All numbers are wrapped * as VDouble. String is wrapped as VString. double[] and ListDouble are wrapped as * VDoubleArray. A List of String is wrapped to a VStringArray. Alarms * are alarmNone(), time are timeNow() and display are displayNone(); * * @param value the value to wrap * @return the wrapped value * @deprecated use {@link #toVType() } */ @Deprecated public static VType wrapValue(Object value) { return wrapValue(value, alarmNone()); } /** * Takes a java objects and wraps it into a vType. All numbers are wrapped * as VDouble. String is wrapped as VString. double[] and ListDouble are wrapped as * VDoubleArray. A List of String is wrapped to a VStringArray. Alarms * are alarm, time are timeNow() and display are displayNone(); * * @param value the value to wrap * @param alarm the alarm for the value * @return the wrapped value * @deprecated use {@link #toVType(java.lang.Object, org.epics.vtype.Alarm, org.epics.vtype.Time, org.epics.vtype.Display) } */ @Deprecated public static VType wrapValue(Object value, Alarm alarm) { if (value instanceof Number) { // Special support for numbers return newVDouble(((Number) value).doubleValue(), alarm, timeNow(), displayNone()); } else if (value instanceof String) { // Special support for strings return newVString(((String) value), alarm, timeNow()); } else if (value instanceof double[]) { return newVDoubleArray(new ArrayDouble((double[]) value), alarm, timeNow(), displayNone()); } else if (value instanceof ListDouble) { return newVDoubleArray((ListDouble) value, alarm, timeNow(), displayNone()); } else if (value instanceof List) { boolean matches = true; List list = (List) value; for (Object object : list) { if (!(object instanceof String)) { matches = false; } } if (matches) { @SuppressWarnings("unchecked") List<String> newList = (List<String>) list; return newVStringArray(Collections.unmodifiableList(newList), alarm, timeNow()); } else { throw new UnsupportedOperationException("Type " + value.getClass().getName() + " contains non Strings"); } } else { // TODO: need to implement all the other arrays throw new UnsupportedOperationException("Type " + value.getClass().getName() + " is not yet supported"); } } /** * Converts a standard java type to VTypes. Returns null if no conversion * is possible. Calls {@link #toVType(java.lang.Object, org.epics.vtype.Alarm, org.epics.vtype.Time, org.epics.vtype.Display) * with no alarm, time now and no display. * * @param javaObject the value to wrap * @return the new VType value */ public static VType toVType(Object javaObject) { return toVType(javaObject, alarmNone(), timeNow(), displayNone()); } /** * Converts a standard java type to VTypes. Returns null if no conversion * is possible. * <p> * Types are converted as follow: * <ul> * <li>Boolean -> VBoolean</li> * <li>Number -> corresponding VNumber</li> * <li>String -> VString</li> * <li>number array -> corresponding VNumberArray</li> * <li>ListNumber -> corresponding VNumberArray</li> * <li>List-> if all elements are String, VStringArray</li> * </ul> * * @param javaObject the value to wrap * @param alarm the alarm * @param time the time * @param display the display * @return the new VType value */ public static VType toVType(Object javaObject, Alarm alarm, Time time, Display display) { if (javaObject instanceof Number) { return ValueFactory.newVNumber((Number) javaObject, alarm, time, display); } else if (javaObject instanceof String) { return newVString((String) javaObject, alarm, time); } else if (javaObject instanceof Boolean) { return newVBoolean((Boolean) javaObject, alarm, time); } else if (javaObject instanceof byte[] || javaObject instanceof short[] || javaObject instanceof int[] || javaObject instanceof long[] || javaObject instanceof float[] || javaObject instanceof double[]) { return newVNumberArray(ListNumbers.toListNumber(javaObject), alarm, time, display); } else if (javaObject instanceof ListNumber) { return newVNumberArray((ListNumber) javaObject, alarm, time, display); } else if (javaObject instanceof String[]) { return newVStringArray(Arrays.asList((String[]) javaObject), alarm, time); } else if (javaObject instanceof List) { boolean matches = true; List list = (List) javaObject; for (Object object : list) { if (!(object instanceof String)) { matches = false; } } if (matches) { @SuppressWarnings("unchecked") List<String> newList = (List<String>) list; return newVStringArray(Collections.unmodifiableList(newList), alarm, time); } else { return null; } } else { return null; } } }
vtype: adding checked vType conversion
epics-vtype/src/main/java/org/epics/vtype/ValueFactory.java
vtype: adding checked vType conversion
<ide><path>pics-vtype/src/main/java/org/epics/vtype/ValueFactory.java <ide> } <ide> <ide> /** <del> * Creates a new VDoubleArray. <del> * <del> * @param values array values <del> * @param sizes sizes <del> * @param alarm the alarm <del> * @param time the time <del> * @param display the display <del> * @return the new value <del> */ <del> @Deprecated <del> public static VDoubleArray newVDoubleArray(final double[] values, final ListInt sizes, Alarm alarm, Time time, Display display) { <del> return new IVDoubleArray(new ArrayDouble(values), sizes, alarm, time, display); <del> } <del> <del> /** <ide> * Creates a new VNumberArray based on the type of the data. <ide> * <ide> * @param data the array data <ide> /** <ide> * Creates a new VDoubleArray. <ide> * <del> * @param values array values <del> * @param alarm the alarm <del> * @param time the time <del> * @param display the display <del> * @return the new value <del> */ <del> @Deprecated <del> public static VDoubleArray newVDoubleArray(final double[] values, Alarm alarm, Time time, Display display) { <del> return newVDoubleArray(values, new ArrayInt(values.length), alarm, time, display); <del> } <del> <del> /** <del> * Creates a new VDoubleArray. <del> * <ide> * @param data array data <ide> * @param alarm the alarm <ide> * @param time the time <ide> public static VFloatArray newVFloatArray(ListFloat data, Alarm alarm, Time time, Display display) { <ide> return new IVFloatArray(data, new ArrayInt(data.size()), alarm, <ide> time, display); <del> } <del> <del> /** <del> * Creates a new VDoubleArray. <del> * <del> * @param values array values <del> * @param display the display <del> * @return the new value <del> */ <del> @Deprecated <del> public static VDoubleArray newVDoubleArray(final double[] values, Display display) { <del> return newVDoubleArray(values, new ArrayInt(values.length), alarmNone(), timeNow(), display); <ide> } <ide> <ide> /** <ide> return null; <ide> } <ide> } <add> <add> /** <add> * As {@link #toVType(java.lang.Object)} but throws an exception <add> * if conversion not possible. <add> * <add> * @param javaObject the value to wrap <add> * @return the new VType value <add> */ <add> public static VType toVTypeChecked(Object javaObject) { <add> VType value = toVType(javaObject); <add> if (value == null) { <add> throw new RuntimeException("Value " + value + " cannot be converted to VType."); <add> } <add> return value; <add> } <add> <add> /** <add> * As {@link #toVType(java.lang.Object, org.epics.vtype.Alarm, org.epics.vtype.Time, org.epics.vtype.Display)} but throws an exception <add> * if conversion not possible. <add> * <add> * @param javaObject the value to wrap <add> * @param alarm the alarm <add> * @param time the time <add> * @param display the display <add> * @return the new VType value <add> */ <add> public static VType toVTypeChecked(Object javaObject, Alarm alarm, Time time, Display display) { <add> VType value = toVType(javaObject, alarm, time, display); <add> if (value == null) { <add> throw new RuntimeException("Value " + value + " cannot be converted to VType."); <add> } <add> return value; <add> } <ide> }
Java
apache-2.0
80d4ca21e2814869592379f0278cbcd95a260808
0
vt0r/vector-android,vector-im/riot-android,noepitome/neon-android,riot-spanish/riot-android,vt0r/vector-android,vector-im/vector-android,vector-im/riot-android,noepitome/neon-android,vector-im/vector-android,riot-spanish/riot-android,vt0r/vector-android,vector-im/riot-android,vector-im/vector-android,vector-im/vector-android,floviolleau/vector-android,noepitome/neon-android,vector-im/riot-android,vector-im/riot-android,floviolleau/vector-android,floviolleau/vector-android,noepitome/neon-android,riot-spanish/riot-android,riot-spanish/riot-android
/* * Copyright 2015 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Browser; import android.support.v4.app.FragmentManager; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.adapters.MessageRow; import org.matrix.androidsdk.adapters.MessagesAdapter; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.fragments.MatrixMessageListFragment; import org.matrix.androidsdk.listeners.MXMediaDownloadListener; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.FileMessage; import org.matrix.androidsdk.rest.model.ImageMessage; import org.matrix.androidsdk.rest.model.MatrixError; import org.matrix.androidsdk.rest.model.Message; import org.matrix.androidsdk.rest.model.VideoMessage; import org.matrix.androidsdk.util.JsonUtils; import im.vector.Matrix; import im.vector.R; import im.vector.VectorApp; import im.vector.activity.CommonActivityUtils; import im.vector.activity.MXCActionBarActivity; import im.vector.activity.VectorHomeActivity; import im.vector.activity.VectorMemberDetailsActivity; import im.vector.activity.VectorRoomActivity; import im.vector.activity.VectorMediasViewerActivity; import im.vector.adapters.VectorMessagesAdapter; import im.vector.db.VectorContentProvider; import im.vector.receiver.VectorUniversalLinkReceiver; import im.vector.util.BugReporter; import im.vector.util.SlidableMediaInfo; import im.vector.util.VectorUtils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; public class VectorMessageListFragment extends MatrixMessageListFragment implements VectorMessagesAdapter.VectorMessagesAdapterActionsListener { private static final String LOG_TAG = "VectorMessageListFrg"; public interface IListFragmentEventListener{ void onListTouch(); } private static final String TAG_FRAGMENT_RECEIPTS_DIALOG = "TAG_FRAGMENT_RECEIPTS_DIALOG"; private IListFragmentEventListener mHostActivityListener; // onMediaAction actions // private static final int ACTION_VECTOR_SHARE = R.id.ic_action_vector_share; private static final int ACTION_VECTOR_FORWARD = R.id.ic_action_vector_forward; private static final int ACTION_VECTOR_SAVE = R.id.ic_action_vector_save; public static final int ACTION_VECTOR_OPEN = 123456; // spinners private View mBackProgressView; private View mForwardProgressView; private View mMainProgressView; public static VectorMessageListFragment newInstance(String matrixId, String roomId, String eventId, String previewMode, int layoutResId) { VectorMessageListFragment f = new VectorMessageListFragment(); Bundle args = new Bundle(); args.putInt(ARG_LAYOUT_ID, layoutResId); args.putString(ARG_MATRIX_ID, matrixId); args.putString(ARG_ROOM_ID, roomId); if (null != eventId) { args.putString(ARG_EVENT_ID, eventId); } if (null != previewMode) { args.putString(ARG_PREVIEW_MODE_ID, previewMode); } f.setArguments(args); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreateView"); View v = super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); // when an event id is defined, display a thick green line to its left if (args.containsKey(ARG_EVENT_ID) && (mAdapter instanceof VectorMessagesAdapter)) { ((VectorMessagesAdapter) mAdapter).setSearchedEventId(args.getString(ARG_EVENT_ID, "")); } return v; } /** * @return the fragment tag to use to restore the matrix messages fragment */ protected String getMatrixMessagesFragmentTag() { return getClass().getName() + ".MATRIX_MESSAGE_FRAGMENT_TAG"; } /** * Called when a fragment is first attached to its activity. * {@link #onCreate(Bundle)} will be called after this. * * @param aHostActivity parent activity */ @Override public void onAttach(Activity aHostActivity) { super.onAttach(aHostActivity); try { mHostActivityListener = (IListFragmentEventListener) aHostActivity; } catch(ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG,"## onAttach(): host activity does not implement IListFragmentEventListener " + aHostActivity); mHostActivityListener = null; } mBackProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_back_progress); mForwardProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_forward_progress); mMainProgressView = aHostActivity.findViewById(R.id.main_progress_layout); } @Override public void onPause() { super.onPause(); if (mAdapter instanceof VectorMessagesAdapter) { ((VectorMessagesAdapter)mAdapter).onPause(); } } /** * Called when the fragment is no longer attached to its activity. This * is called after {@link #onDestroy()}. */ @Override public void onDetach() { super.onDetach(); mHostActivityListener = null; } @Override public MXSession getSession(String matrixId) { return Matrix.getMXSession(getActivity(), matrixId); } @Override public MXMediasCache getMXMediasCache() { return Matrix.getInstance(getActivity()).getMediasCache(); } @Override public MessagesAdapter createMessagesAdapter() { VectorMessagesAdapter vectorMessagesAdapter = new VectorMessagesAdapter(mSession, getActivity(), getMXMediasCache()); vectorMessagesAdapter.setVectorMessagesAdapterActionsListener(this); return vectorMessagesAdapter; } /** * The user scrolls the list. * Apply an expected behaviour * @param event the scroll event */ @Override public void onListTouch(MotionEvent event) { // the user scroll over the keyboard // hides the keyboard if (mCheckSlideToHide && (event.getY() > mMessageListView.getHeight())) { mCheckSlideToHide = false; MXCActionBarActivity.dismissKeyboard(getActivity()); } // notify host activity if(null != mHostActivityListener) mHostActivityListener.onListTouch(); } /** * Cancel the messages selection mode. */ public void cancelSelectionMode() { ((VectorMessagesAdapter)mAdapter).cancelSelectionMode(); } /** * An action has been triggered on an event. * @param event the event. * @param textMsg the event text * @param action an action ic_action_vector_XXX */ public void onEventAction(final Event event, final String textMsg, final int action) { if (action == R.id.ic_action_vector_resend_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { resend(event); } }); } else if (action == R.id.ic_action_vector_redact_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (event.isUndeliverable()) { // delete from the store mSession.getDataHandler().getStore().deleteEvent(event); mSession.getDataHandler().getStore().commit(); // remove from the adapter mAdapter.removeEventById(event.eventId); mAdapter.notifyDataSetChanged(); mEventSendingListener.onMessageRedacted(event); } else { redactEvent(event.eventId); } } }); } else if (action == R.id.ic_action_vector_copy) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { VectorUtils.copyToClipboard(getActivity(), textMsg); } }); } else if ((action == R.id.ic_action_vector_cancel_upload) || (action == R.id.ic_action_vector_cancel_download)) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { new AlertDialog.Builder(VectorApp.getCurrentActivity()) .setMessage((action == R.id.ic_action_vector_cancel_upload) ? R.string.attachment_cancel_upload : R.string.attachment_cancel_download) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mRoom.cancelEventSending(event); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_save)) { // Message message = JsonUtils.toMessage(event.content); String mediaUrl = null; String mediaMimeType = null; if (message instanceof ImageMessage) { ImageMessage imageMessage = (ImageMessage) message; mediaUrl = imageMessage.url; mediaMimeType = imageMessage.getMimeType(); } else if (message instanceof VideoMessage) { VideoMessage videoMessage = (VideoMessage) message; mediaUrl = videoMessage.url; if (null != videoMessage.info) { mediaMimeType = videoMessage.info.mimetype; } } else if (message instanceof FileMessage) { FileMessage fileMessage = (FileMessage) message; mediaUrl = fileMessage.url; mediaMimeType = fileMessage.getMimeType(); } // media file ? if (null != mediaUrl) { onMediaAction(action, mediaUrl, mediaMimeType, message.body); } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward)) { // use the body final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, message.body); sendIntent.setType("text/plain"); if (action == R.id.ic_action_vector_forward) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } else if (action == R.id.ic_action_vector_permalink) { VectorUtils.copyToClipboard(getActivity(), VectorUtils.getPermalink(event.roomId, event.eventId)); } else if (action == R.id.ic_action_vector_report) { onMessageReport(event); } else if (action == R.id.ic_action_view_source) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View view= getActivity().getLayoutInflater().inflate(R.layout.dialog_event_content, null); TextView textview = (TextView)view.findViewById(R.id.event_content_text_view); Gson gson = new GsonBuilder().setPrettyPrinting().create(); textview.setText(gson.toJson(JsonUtils.toJson(event))); builder.setView(view); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } }); } } /** * The user reports a content problem to the server * @param event the event to report */ private void onMessageReport(final Event event) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.room_event_action_report_prompt_reason); // add a text input final EditText input = new EditText(getActivity()); builder.setView(input); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String reason = input.getText().toString(); mRoom.report(event.eventId, -100, reason, new SimpleApiCallback<Void>(getActivity()) { @Override public void onSuccess(Void info) { new AlertDialog.Builder(VectorApp.getCurrentActivity()) .setMessage(R.string.room_event_action_report_prompt_ignore_user) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ArrayList<String> userIdsList = new ArrayList<>(); userIdsList.add(event.sender); mSession.ignoreUsers(userIdsList, new SimpleApiCallback<Void>() { @Override public void onSuccess(Void info) { } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } /*** * Manage save / share / forward actions on a media file * @param menuAction the menu action ACTION_VECTOR__XXX * @param mediaUrl the media URL (must be not null) * @param mediaMimeType the mime type * @param filename the filename */ protected void onMediaAction(final int menuAction, final String mediaUrl, final String mediaMimeType, final String filename) { MXMediasCache mediasCache = Matrix.getInstance(getActivity()).getMediasCache(); File file = mediasCache.mediaCacheFile(mediaUrl, mediaMimeType); // check if the media has already been downloaded if (null != file) { // download if ((menuAction == ACTION_VECTOR_SAVE) || (menuAction == ACTION_VECTOR_OPEN)) { String savedMediaPath = CommonActivityUtils.saveMediaIntoDownloads(getActivity(), file, filename, mediaMimeType); if (null != savedMediaPath) { if (menuAction == ACTION_VECTOR_SAVE) { Toast.makeText(getActivity(), getText(R.string.media_slider_saved), Toast.LENGTH_LONG).show(); } else { CommonActivityUtils.openMedia(getActivity(), savedMediaPath, mediaMimeType); } } } else { // shared / forward Uri mediaUri = null; File renamedFile = file; if (!TextUtils.isEmpty(filename)) { try { InputStream fin = new FileInputStream(file); String tmpUrl = mediasCache.saveMedia(fin, filename, mediaMimeType); if (null != tmpUrl) { renamedFile = mediasCache.mediaCacheFile(tmpUrl, mediaMimeType); } } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction shared / forward failed : " + e.getLocalizedMessage()); } } if (null != renamedFile) { try { mediaUri = VectorContentProvider.absolutePathToUri(getActivity(), renamedFile.getAbsolutePath()); } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction VectorContentProvider.absolutePathToUri: " + e.getLocalizedMessage()); } } if (null != mediaUri) { final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.setType(mediaMimeType); sendIntent.putExtra(Intent.EXTRA_STREAM, mediaUri); if (menuAction == ACTION_VECTOR_FORWARD) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } } else { // else download it final String downloadId = mediasCache.downloadMedia(getActivity(), mSession.getHomeserverConfig(), mediaUrl, mediaMimeType); mAdapter.notifyDataSetChanged(); if (null != downloadId) { mediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() { @Override public void onDownloadError(String downloadId, JsonElement jsonElement) { MatrixError error = JsonUtils.toMatrixError(jsonElement); if ((null != error) && error.isSupportedErrorCode()) { Toast.makeText(VectorMessageListFragment.this.getActivity(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onDownloadComplete(String aDownloadId) { if (aDownloadId.equals(downloadId)) { VectorMessageListFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { onMediaAction(menuAction, mediaUrl, mediaMimeType, filename); } }); } } }); } } } /** * return true to display all the events. * else the unknown events will be hidden. */ @Override public boolean isDisplayAllEvents() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); return preferences.getBoolean(getString(R.string.settings_key_display_all_events), false); } private void setViewVisibility(View view, int visibility) { if ((null != view) && (null != getActivity())) { view.setVisibility(visibility); } } @Override public void showLoadingBackProgress() { setViewVisibility(mBackProgressView, View.VISIBLE); } @Override public void hideLoadingBackProgress() { setViewVisibility(mBackProgressView, View.GONE); } @Override public void showLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.VISIBLE); } @Override public void hideLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.GONE); } @Override public void showInitLoading() { setViewVisibility(mMainProgressView, View.VISIBLE); } @Override public void hideInitLoading() { setViewVisibility(mMainProgressView, View.GONE); } public boolean onRowLongClick(int position) { return false; } /** * @return the image and video messages list */ protected ArrayList<SlidableMediaInfo> listSlidableMessages() { ArrayList<SlidableMediaInfo> res = new ArrayList<>(); for(int position = 0; position < mAdapter.getCount(); position++) { MessageRow row = mAdapter.getItem(position); Message message = JsonUtils.toMessage(row.getEvent().content); if (Message.MSGTYPE_IMAGE.equals(message.msgtype)) { ImageMessage imageMessage = (ImageMessage)message; SlidableMediaInfo info = new SlidableMediaInfo(); info.mMessageType = Message.MSGTYPE_IMAGE; info.mFileName = imageMessage.body; info.mMediaUrl = imageMessage.url; info.mRotationAngle = imageMessage.getRotation(); info.mOrientation = imageMessage.getOrientation(); info.mMimeType = imageMessage.getMimeType(); info.mIdentifier = row.getEvent().eventId; res.add(info); } else if (Message.MSGTYPE_VIDEO.equals(message.msgtype)) { SlidableMediaInfo info = new SlidableMediaInfo(); VideoMessage videoMessage = (VideoMessage)message; info.mMessageType = Message.MSGTYPE_VIDEO; info.mFileName = videoMessage.body; info.mMediaUrl = videoMessage.url; info.mThumbnailUrl = (null != videoMessage.info) ? videoMessage.info.thumbnail_url : null; info.mMimeType = videoMessage.getVideoMimeType(); res.add(info); } } return res; } /** * Returns the mediaMessage position in listMediaMessages. * @param mediaMessagesList the media messages list * @param mediaMessage the imageMessage * @return the imageMessage position. -1 if not found. */ protected int getMediaMessagePosition(ArrayList<SlidableMediaInfo> mediaMessagesList, Message mediaMessage) { String url = null; if (mediaMessage instanceof ImageMessage) { url = ((ImageMessage)mediaMessage).url; } else if (mediaMessage instanceof VideoMessage) { url = ((VideoMessage)mediaMessage).url; } // sanity check if (null == url) { return -1; } for(int index = 0; index < mediaMessagesList.size(); index++) { if (mediaMessagesList.get(index).mMediaUrl.equals(url)) { return index; } } return -1; } @Override public void onRowClick(int position) { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); // switch in section mode ((VectorMessagesAdapter)mAdapter).onEventTap(event.eventId); } @Override public void onContentClick(int position) { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); VectorMessagesAdapter vectorMessagesAdapter = (VectorMessagesAdapter)mAdapter; if (vectorMessagesAdapter.isInSelectionMode()) { // cancel the selection mode. vectorMessagesAdapter.onEventTap(null); return; } Message message = JsonUtils.toMessage(event.content); // video and images are displayed inside a medias slider. if (Message.MSGTYPE_IMAGE.equals(message.msgtype) || (Message.MSGTYPE_VIDEO.equals(message.msgtype))) { ArrayList<SlidableMediaInfo> mediaMessagesList = listSlidableMessages(); int listPosition = getMediaMessagePosition(mediaMessagesList, message); if (listPosition >= 0) { Intent viewImageIntent = new Intent(getActivity(), VectorMediasViewerActivity.class); viewImageIntent.putExtra(VectorMediasViewerActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_WIDTH, mAdapter.getMaxThumbnailWith()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_HEIGHT, mAdapter.getMaxThumbnailHeight()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST, mediaMessagesList); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST_INDEX, listPosition); getActivity().startActivity(viewImageIntent); } } else if (Message.MSGTYPE_FILE.equals(message.msgtype)) { FileMessage fileMessage = JsonUtils.toFileMessage(event.content); if (null != fileMessage.url) { onMediaAction(ACTION_VECTOR_OPEN, fileMessage.url, fileMessage.getMimeType(), fileMessage.body); } } else { // switch in section mode vectorMessagesAdapter.onEventTap(event.eventId); } } @Override public boolean onContentLongClick(int position) { return onRowLongClick(position); } @Override public void onAvatarClick(String userId) { Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); // in preview mode // the room is stored in a temporary store // so provide an handle to retrieve it if (null != getRoomPreviewData()) { roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_STORE_ID, new Integer(Matrix.getInstance(getActivity()).addTmpStore(mEventTimeLine.getStore()))); } roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId()); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); getActivity().startActivityForResult(roomDetailsIntent, VectorRoomActivity.GET_MENTION_REQUEST_CODE); } @Override public boolean onAvatarLongClick(String userId) { if (getActivity() instanceof VectorRoomActivity) { RoomState state = mRoom.getLiveState(); if (null != state) { String displayName = state.getMemberName(userId); if (!TextUtils.isEmpty(displayName)) { ((VectorRoomActivity)getActivity()).insertInTextEditor(displayName); } } } return true; } @Override public void onSenderNameClick(String userId, String displayName) { if (getActivity() instanceof VectorRoomActivity) { ((VectorRoomActivity)getActivity()).insertInTextEditor(displayName); } } @Override public void onMediaDownloaded(int position) { } @Override public void onMoreReadReceiptClick(String eventId) { FragmentManager fm = getActivity().getSupportFragmentManager(); VectorReadReceiptsDialogFragment fragment = (VectorReadReceiptsDialogFragment) fm.findFragmentByTag(TAG_FRAGMENT_RECEIPTS_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } fragment = VectorReadReceiptsDialogFragment.newInstance(mSession, mRoom.getRoomId(), eventId); fragment.show(fm, TAG_FRAGMENT_RECEIPTS_DIALOG); } @Override public void onURLClick(Uri uri) { if (null != uri) { if (null != VectorUniversalLinkReceiver.parseUniversalLink(uri)) { // pop to the home activity Intent intent = new Intent(getActivity(), VectorHomeActivity.class); intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(VectorHomeActivity.EXTRA_JUMP_TO_UNIVERSAL_LINK, uri); getActivity().startActivity(intent); } else { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, getActivity().getPackageName()); getActivity().startActivity(intent); } } } @Override public void onMatrixUserIdClick(final String userId) { showInitLoading(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { CommonActivityUtils.goToOneToOneRoom(mSession, userId, getActivity(), new ApiCallback<Void>() { @Override public void onSuccess(Void info) { // nothing to do here } private void onError(String errorMessage) { hideInitLoading(); CommonActivityUtils.displayToast(getActivity(), errorMessage); } @Override public void onNetworkError(Exception e) { onError(e.getLocalizedMessage()); } @Override public void onMatrixError(MatrixError e) { onError(e.getLocalizedMessage()); } @Override public void onUnexpectedError(Exception e) { onError(e.getLocalizedMessage()); } }); } }); } @Override public void onRoomAliasClick(String roomAlias) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomAlias, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomAliasClick failed " + e.getLocalizedMessage()); } } @Override public void onRoomIdClick(String roomId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomId, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } @Override public void onMessageIdClick(String messageId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(mRoom.getRoomId(), messageId))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } }
vector/src/main/java/im/vector/fragments/VectorMessageListFragment.java
/* * Copyright 2015 OpenMarket Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.fragments; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Browser; import android.support.v4.app.FragmentManager; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import org.matrix.androidsdk.MXSession; import org.matrix.androidsdk.adapters.MessageRow; import org.matrix.androidsdk.adapters.MessagesAdapter; import org.matrix.androidsdk.data.RoomState; import org.matrix.androidsdk.db.MXMediasCache; import org.matrix.androidsdk.fragments.MatrixMessageListFragment; import org.matrix.androidsdk.listeners.MXMediaDownloadListener; import org.matrix.androidsdk.rest.callback.ApiCallback; import org.matrix.androidsdk.rest.callback.SimpleApiCallback; import org.matrix.androidsdk.rest.model.Event; import org.matrix.androidsdk.rest.model.FileMessage; import org.matrix.androidsdk.rest.model.ImageMessage; import org.matrix.androidsdk.rest.model.MatrixError; import org.matrix.androidsdk.rest.model.Message; import org.matrix.androidsdk.rest.model.VideoMessage; import org.matrix.androidsdk.util.JsonUtils; import im.vector.Matrix; import im.vector.R; import im.vector.VectorApp; import im.vector.activity.CommonActivityUtils; import im.vector.activity.MXCActionBarActivity; import im.vector.activity.VectorHomeActivity; import im.vector.activity.VectorMemberDetailsActivity; import im.vector.activity.VectorRoomActivity; import im.vector.activity.VectorMediasViewerActivity; import im.vector.adapters.VectorMessagesAdapter; import im.vector.db.VectorContentProvider; import im.vector.receiver.VectorUniversalLinkReceiver; import im.vector.util.BugReporter; import im.vector.util.SlidableMediaInfo; import im.vector.util.VectorUtils; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; public class VectorMessageListFragment extends MatrixMessageListFragment implements VectorMessagesAdapter.VectorMessagesAdapterActionsListener { private static final String LOG_TAG = "VectorMessageListFrg"; public interface IListFragmentEventListener{ void onListTouch(); } private static final String TAG_FRAGMENT_RECEIPTS_DIALOG = "TAG_FRAGMENT_RECEIPTS_DIALOG"; private IListFragmentEventListener mHostActivityListener; // onMediaAction actions // private static final int ACTION_VECTOR_SHARE = R.id.ic_action_vector_share; private static final int ACTION_VECTOR_FORWARD = R.id.ic_action_vector_forward; private static final int ACTION_VECTOR_SAVE = R.id.ic_action_vector_save; public static final int ACTION_VECTOR_OPEN = 123456; // spinners private View mBackProgressView; private View mForwardProgressView; private View mMainProgressView; public static VectorMessageListFragment newInstance(String matrixId, String roomId, String eventId, String previewMode, int layoutResId) { VectorMessageListFragment f = new VectorMessageListFragment(); Bundle args = new Bundle(); args.putInt(ARG_LAYOUT_ID, layoutResId); args.putString(ARG_MATRIX_ID, matrixId); args.putString(ARG_ROOM_ID, roomId); if (null != eventId) { args.putString(ARG_EVENT_ID, eventId); } if (null != previewMode) { args.putString(ARG_PREVIEW_MODE_ID, previewMode); } f.setArguments(args); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.d(LOG_TAG, "onCreateView"); View v = super.onCreateView(inflater, container, savedInstanceState); Bundle args = getArguments(); // when an event id is defined, display a thick green line to its left if (args.containsKey(ARG_EVENT_ID) && (mAdapter instanceof VectorMessagesAdapter)) { ((VectorMessagesAdapter) mAdapter).setSearchedEventId(args.getString(ARG_EVENT_ID, "")); } return v; } /** * @return the fragment tag to use to restore the matrix messages fragment */ protected String getMatrixMessagesFragmentTag() { return getClass().getName() + ".MATRIX_MESSAGE_FRAGMENT_TAG"; } /** * Called when a fragment is first attached to its activity. * {@link #onCreate(Bundle)} will be called after this. * * @param aHostActivity parent activity */ @Override public void onAttach(Activity aHostActivity) { super.onAttach(aHostActivity); try { mHostActivityListener = (IListFragmentEventListener) aHostActivity; } catch(ClassCastException e) { // if host activity does not provide the implementation, just ignore it Log.w(LOG_TAG,"## onAttach(): host activity does not implement IListFragmentEventListener " + aHostActivity); mHostActivityListener = null; } mBackProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_back_progress); mForwardProgressView = aHostActivity.findViewById(R.id.loading_room_paginate_forward_progress); mMainProgressView = aHostActivity.findViewById(R.id.main_progress_layout); } @Override public void onPause() { super.onPause(); if (mAdapter instanceof VectorMessagesAdapter) { ((VectorMessagesAdapter)mAdapter).onPause(); } } /** * Called when the fragment is no longer attached to its activity. This * is called after {@link #onDestroy()}. */ @Override public void onDetach() { super.onDetach(); mHostActivityListener = null; } @Override public MXSession getSession(String matrixId) { return Matrix.getMXSession(getActivity(), matrixId); } @Override public MXMediasCache getMXMediasCache() { return Matrix.getInstance(getActivity()).getMediasCache(); } @Override public MessagesAdapter createMessagesAdapter() { VectorMessagesAdapter vectorMessagesAdapter = new VectorMessagesAdapter(mSession, getActivity(), getMXMediasCache()); vectorMessagesAdapter.setVectorMessagesAdapterActionsListener(this); return vectorMessagesAdapter; } /** * The user scrolls the list. * Apply an expected behaviour * @param event the scroll event */ @Override public void onListTouch(MotionEvent event) { // the user scroll over the keyboard // hides the keyboard if (mCheckSlideToHide && (event.getY() > mMessageListView.getHeight())) { mCheckSlideToHide = false; MXCActionBarActivity.dismissKeyboard(getActivity()); } // notify host activity if(null != mHostActivityListener) mHostActivityListener.onListTouch(); } /** * Cancel the messages selection mode. */ public void cancelSelectionMode() { ((VectorMessagesAdapter)mAdapter).cancelSelectionMode(); } /** * An action has been triggered on an event. * @param event the event. * @param textMsg the event text * @param action an action ic_action_vector_XXX */ public void onEventAction(final Event event, final String textMsg, final int action) { if (action == R.id.ic_action_vector_resend_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { resend(event); } }); } else if (action == R.id.ic_action_vector_redact_message) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { if (event.isUndeliverable()) { // delete from the store mSession.getDataHandler().getStore().deleteEvent(event); mSession.getDataHandler().getStore().commit(); // remove from the adapter mAdapter.removeEventById(event.eventId); mAdapter.notifyDataSetChanged(); mEventSendingListener.onMessageRedacted(event); } else { redactEvent(event.eventId); } } }); } else if (action == R.id.ic_action_vector_copy) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { VectorUtils.copyToClipboard(getActivity(), textMsg); } }); } else if ((action == R.id.ic_action_vector_cancel_upload) || (action == R.id.ic_action_vector_cancel_download)) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { // The user is trying to leave with unsaved changes. Warn about that new AlertDialog.Builder(VectorApp.getCurrentActivity()) .setMessage((action == R.id.ic_action_vector_cancel_upload) ? R.string.attachment_cancel_upload : R.string.attachment_cancel_download) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mRoom.cancelEventSending(event); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mAdapter.notifyDataSetChanged(); } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward) || (action == R.id.ic_action_vector_save)) { // Message message = JsonUtils.toMessage(event.content); String mediaUrl = null; String mediaMimeType = null; if (message instanceof ImageMessage) { ImageMessage imageMessage = (ImageMessage) message; mediaUrl = imageMessage.url; mediaMimeType = imageMessage.getMimeType(); } else if (message instanceof VideoMessage) { VideoMessage videoMessage = (VideoMessage) message; mediaUrl = videoMessage.url; if (null != videoMessage.info) { mediaMimeType = videoMessage.info.mimetype; } } else if (message instanceof FileMessage) { FileMessage fileMessage = (FileMessage) message; mediaUrl = fileMessage.url; mediaMimeType = fileMessage.getMimeType(); } // media file ? if (null != mediaUrl) { onMediaAction(action, mediaUrl, mediaMimeType, message.body); } else if ((action == R.id.ic_action_vector_share) || (action == R.id.ic_action_vector_forward)) { // use the body final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, message.body); sendIntent.setType("text/plain"); if (action == R.id.ic_action_vector_forward) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } else if (action == R.id.ic_action_vector_permalink) { VectorUtils.copyToClipboard(getActivity(), VectorUtils.getPermalink(event.roomId, event.eventId)); } else if (action == R.id.ic_action_vector_report) { onMessageReport(event); } else if (action == R.id.ic_action_view_source) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); View view= getActivity().getLayoutInflater().inflate(R.layout.dialog_event_content, null); TextView textview = (TextView)view.findViewById(R.id.event_content_text_view); Gson gson = new GsonBuilder().setPrettyPrinting().create(); textview.setText(gson.toJson(JsonUtils.toJson(event))); builder.setView(view); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.create().show(); } }); } } /** * The user reports a content problem to the server * @param event the event to report */ private void onMessageReport(final Event event) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.room_event_action_report_prompt_reason); // add a text input final EditText input = new EditText(getActivity()); builder.setView(input); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String reason = input.getText().toString(); mRoom.report(event.eventId, -100, reason, new SimpleApiCallback<Void>(getActivity()) { @Override public void onSuccess(Void info) { // The user is trying to leave with unsaved changes. Warn about that new AlertDialog.Builder(VectorApp.getCurrentActivity()) .setMessage(R.string.room_event_action_report_prompt_ignore_user) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); ArrayList<String> userIdsList = new ArrayList<>(); userIdsList.add(event.sender); mSession.ignoreUsers(userIdsList, new SimpleApiCallback<Void>() { @Override public void onSuccess(Void info) { } }); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create() .show(); } }); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } /*** * Manage save / share / forward actions on a media file * @param menuAction the menu action ACTION_VECTOR__XXX * @param mediaUrl the media URL (must be not null) * @param mediaMimeType the mime type * @param filename the filename */ protected void onMediaAction(final int menuAction, final String mediaUrl, final String mediaMimeType, final String filename) { MXMediasCache mediasCache = Matrix.getInstance(getActivity()).getMediasCache(); File file = mediasCache.mediaCacheFile(mediaUrl, mediaMimeType); // check if the media has already been downloaded if (null != file) { // download if ((menuAction == ACTION_VECTOR_SAVE) || (menuAction == ACTION_VECTOR_OPEN)) { String savedMediaPath = CommonActivityUtils.saveMediaIntoDownloads(getActivity(), file, filename, mediaMimeType); if (null != savedMediaPath) { if (menuAction == ACTION_VECTOR_SAVE) { Toast.makeText(getActivity(), getText(R.string.media_slider_saved), Toast.LENGTH_LONG).show(); } else { CommonActivityUtils.openMedia(getActivity(), savedMediaPath, mediaMimeType); } } } else { // shared / forward Uri mediaUri = null; File renamedFile = file; if (!TextUtils.isEmpty(filename)) { try { InputStream fin = new FileInputStream(file); String tmpUrl = mediasCache.saveMedia(fin, filename, mediaMimeType); if (null != tmpUrl) { renamedFile = mediasCache.mediaCacheFile(tmpUrl, mediaMimeType); } } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction shared / forward failed : " + e.getLocalizedMessage()); } } if (null != renamedFile) { try { mediaUri = VectorContentProvider.absolutePathToUri(getActivity(), renamedFile.getAbsolutePath()); } catch (Exception e) { Log.e(LOG_TAG, "onMediaAction VectorContentProvider.absolutePathToUri: " + e.getLocalizedMessage()); } } if (null != mediaUri) { final Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.setType(mediaMimeType); sendIntent.putExtra(Intent.EXTRA_STREAM, mediaUri); if (menuAction == ACTION_VECTOR_FORWARD) { CommonActivityUtils.sendFilesTo(getActivity(), sendIntent); } else { startActivity(sendIntent); } } } } else { // else download it final String downloadId = mediasCache.downloadMedia(getActivity(), mSession.getHomeserverConfig(), mediaUrl, mediaMimeType); mAdapter.notifyDataSetChanged(); if (null != downloadId) { mediasCache.addDownloadListener(downloadId, new MXMediaDownloadListener() { @Override public void onDownloadError(String downloadId, JsonElement jsonElement) { MatrixError error = JsonUtils.toMatrixError(jsonElement); if ((null != error) && error.isSupportedErrorCode()) { Toast.makeText(VectorMessageListFragment.this.getActivity(), error.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } } @Override public void onDownloadComplete(String aDownloadId) { if (aDownloadId.equals(downloadId)) { VectorMessageListFragment.this.getActivity().runOnUiThread(new Runnable() { @Override public void run() { onMediaAction(menuAction, mediaUrl, mediaMimeType, filename); } }); } } }); } } } /** * return true to display all the events. * else the unknown events will be hidden. */ @Override public boolean isDisplayAllEvents() { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); return preferences.getBoolean(getString(R.string.settings_key_display_all_events), false); } private void setViewVisibility(View view, int visibility) { if ((null != view) && (null != getActivity())) { view.setVisibility(visibility); } } @Override public void showLoadingBackProgress() { setViewVisibility(mBackProgressView, View.VISIBLE); } @Override public void hideLoadingBackProgress() { setViewVisibility(mBackProgressView, View.GONE); } @Override public void showLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.VISIBLE); } @Override public void hideLoadingForwardProgress() { setViewVisibility(mForwardProgressView, View.GONE); } @Override public void showInitLoading() { setViewVisibility(mMainProgressView, View.VISIBLE); } @Override public void hideInitLoading() { setViewVisibility(mMainProgressView, View.GONE); } public boolean onRowLongClick(int position) { return false; } /** * @return the image and video messages list */ protected ArrayList<SlidableMediaInfo> listSlidableMessages() { ArrayList<SlidableMediaInfo> res = new ArrayList<>(); for(int position = 0; position < mAdapter.getCount(); position++) { MessageRow row = mAdapter.getItem(position); Message message = JsonUtils.toMessage(row.getEvent().content); if (Message.MSGTYPE_IMAGE.equals(message.msgtype)) { ImageMessage imageMessage = (ImageMessage)message; SlidableMediaInfo info = new SlidableMediaInfo(); info.mMessageType = Message.MSGTYPE_IMAGE; info.mFileName = imageMessage.body; info.mMediaUrl = imageMessage.url; info.mRotationAngle = imageMessage.getRotation(); info.mOrientation = imageMessage.getOrientation(); info.mMimeType = imageMessage.getMimeType(); info.mIdentifier = row.getEvent().eventId; res.add(info); } else if (Message.MSGTYPE_VIDEO.equals(message.msgtype)) { SlidableMediaInfo info = new SlidableMediaInfo(); VideoMessage videoMessage = (VideoMessage)message; info.mMessageType = Message.MSGTYPE_VIDEO; info.mFileName = videoMessage.body; info.mMediaUrl = videoMessage.url; info.mThumbnailUrl = (null != videoMessage.info) ? videoMessage.info.thumbnail_url : null; info.mMimeType = videoMessage.getVideoMimeType(); res.add(info); } } return res; } /** * Returns the mediaMessage position in listMediaMessages. * @param mediaMessagesList the media messages list * @param mediaMessage the imageMessage * @return the imageMessage position. -1 if not found. */ protected int getMediaMessagePosition(ArrayList<SlidableMediaInfo> mediaMessagesList, Message mediaMessage) { String url = null; if (mediaMessage instanceof ImageMessage) { url = ((ImageMessage)mediaMessage).url; } else if (mediaMessage instanceof VideoMessage) { url = ((VideoMessage)mediaMessage).url; } // sanity check if (null == url) { return -1; } for(int index = 0; index < mediaMessagesList.size(); index++) { if (mediaMessagesList.get(index).mMediaUrl.equals(url)) { return index; } } return -1; } @Override public void onRowClick(int position) { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); // switch in section mode ((VectorMessagesAdapter)mAdapter).onEventTap(event.eventId); } @Override public void onContentClick(int position) { MessageRow row = mAdapter.getItem(position); Event event = row.getEvent(); VectorMessagesAdapter vectorMessagesAdapter = (VectorMessagesAdapter)mAdapter; if (vectorMessagesAdapter.isInSelectionMode()) { // cancel the selection mode. vectorMessagesAdapter.onEventTap(null); return; } Message message = JsonUtils.toMessage(event.content); // video and images are displayed inside a medias slider. if (Message.MSGTYPE_IMAGE.equals(message.msgtype) || (Message.MSGTYPE_VIDEO.equals(message.msgtype))) { ArrayList<SlidableMediaInfo> mediaMessagesList = listSlidableMessages(); int listPosition = getMediaMessagePosition(mediaMessagesList, message); if (listPosition >= 0) { Intent viewImageIntent = new Intent(getActivity(), VectorMediasViewerActivity.class); viewImageIntent.putExtra(VectorMediasViewerActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_WIDTH, mAdapter.getMaxThumbnailWith()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_THUMBNAIL_HEIGHT, mAdapter.getMaxThumbnailHeight()); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST, mediaMessagesList); viewImageIntent.putExtra(VectorMediasViewerActivity.KEY_INFO_LIST_INDEX, listPosition); getActivity().startActivity(viewImageIntent); } } else if (Message.MSGTYPE_FILE.equals(message.msgtype)) { FileMessage fileMessage = JsonUtils.toFileMessage(event.content); if (null != fileMessage.url) { onMediaAction(ACTION_VECTOR_OPEN, fileMessage.url, fileMessage.getMimeType(), fileMessage.body); } } else { // switch in section mode vectorMessagesAdapter.onEventTap(event.eventId); } } @Override public boolean onContentLongClick(int position) { return onRowLongClick(position); } @Override public void onAvatarClick(String userId) { Intent roomDetailsIntent = new Intent(getActivity(), VectorMemberDetailsActivity.class); // in preview mode // the room is stored in a temporary store // so provide an handle to retrieve it if (null != getRoomPreviewData()) { roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_STORE_ID, new Integer(Matrix.getInstance(getActivity()).addTmpStore(mEventTimeLine.getStore()))); } roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_ROOM_ID, mRoom.getRoomId()); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MEMBER_ID, userId); roomDetailsIntent.putExtra(VectorMemberDetailsActivity.EXTRA_MATRIX_ID, mSession.getCredentials().userId); getActivity().startActivityForResult(roomDetailsIntent, VectorRoomActivity.GET_MENTION_REQUEST_CODE); } @Override public boolean onAvatarLongClick(String userId) { if (getActivity() instanceof VectorRoomActivity) { RoomState state = mRoom.getLiveState(); if (null != state) { String displayName = state.getMemberName(userId); if (!TextUtils.isEmpty(displayName)) { ((VectorRoomActivity)getActivity()).insertInTextEditor(displayName); } } } return true; } @Override public void onSenderNameClick(String userId, String displayName) { if (getActivity() instanceof VectorRoomActivity) { ((VectorRoomActivity)getActivity()).insertInTextEditor(displayName); } } @Override public void onMediaDownloaded(int position) { } @Override public void onMoreReadReceiptClick(String eventId) { FragmentManager fm = getActivity().getSupportFragmentManager(); VectorReadReceiptsDialogFragment fragment = (VectorReadReceiptsDialogFragment) fm.findFragmentByTag(TAG_FRAGMENT_RECEIPTS_DIALOG); if (fragment != null) { fragment.dismissAllowingStateLoss(); } fragment = VectorReadReceiptsDialogFragment.newInstance(mSession, mRoom.getRoomId(), eventId); fragment.show(fm, TAG_FRAGMENT_RECEIPTS_DIALOG); } @Override public void onURLClick(Uri uri) { if (null != uri) { if (null != VectorUniversalLinkReceiver.parseUniversalLink(uri)) { // pop to the home activity Intent intent = new Intent(getActivity(), VectorHomeActivity.class); intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(VectorHomeActivity.EXTRA_JUMP_TO_UNIVERSAL_LINK, uri); getActivity().startActivity(intent); } else { Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra(Browser.EXTRA_APPLICATION_ID, getActivity().getPackageName()); getActivity().startActivity(intent); } } } @Override public void onMatrixUserIdClick(final String userId) { showInitLoading(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { CommonActivityUtils.goToOneToOneRoom(mSession, userId, getActivity(), new ApiCallback<Void>() { @Override public void onSuccess(Void info) { // nothing to do here } private void onError(String errorMessage) { hideInitLoading(); CommonActivityUtils.displayToast(getActivity(), errorMessage); } @Override public void onNetworkError(Exception e) { onError(e.getLocalizedMessage()); } @Override public void onMatrixError(MatrixError e) { onError(e.getLocalizedMessage()); } @Override public void onUnexpectedError(Exception e) { onError(e.getLocalizedMessage()); } }); } }); } @Override public void onRoomAliasClick(String roomAlias) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomAlias, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomAliasClick failed " + e.getLocalizedMessage()); } } @Override public void onRoomIdClick(String roomId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(roomId, null))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } @Override public void onMessageIdClick(String messageId) { try { onURLClick(Uri.parse(VectorUtils.getPermalink(mRoom.getRoomId(), messageId))); } catch (Exception e) { Log.e(LOG_TAG, "onRoomIdClick failed " + e.getLocalizedMessage()); } } }
Fix an invalid comment
vector/src/main/java/im/vector/fragments/VectorMessageListFragment.java
Fix an invalid comment
<ide><path>ector/src/main/java/im/vector/fragments/VectorMessageListFragment.java <ide> getActivity().runOnUiThread(new Runnable() { <ide> @Override <ide> public void run() { <del> // The user is trying to leave with unsaved changes. Warn about that <ide> new AlertDialog.Builder(VectorApp.getCurrentActivity()) <ide> .setMessage((action == R.id.ic_action_vector_cancel_upload) ? R.string.attachment_cancel_upload : R.string.attachment_cancel_download) <ide> .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { <ide> mRoom.report(event.eventId, -100, reason, new SimpleApiCallback<Void>(getActivity()) { <ide> @Override <ide> public void onSuccess(Void info) { <del> // The user is trying to leave with unsaved changes. Warn about that <ide> new AlertDialog.Builder(VectorApp.getCurrentActivity()) <ide> .setMessage(R.string.room_event_action_report_prompt_ignore_user) <ide> .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
Java
apache-2.0
f5758c9870dc2c3c66758daeb506ab6b975a95fe
0
hsaputra/cdap,hsaputra/cdap,anthcp/cdap,caskdata/cdap,caskdata/cdap,chtyim/cdap,hsaputra/cdap,caskdata/cdap,hsaputra/cdap,anthcp/cdap,caskdata/cdap,anthcp/cdap,mpouttuclarke/cdap,chtyim/cdap,mpouttuclarke/cdap,chtyim/cdap,caskdata/cdap,anthcp/cdap,mpouttuclarke/cdap,caskdata/cdap,chtyim/cdap,anthcp/cdap,mpouttuclarke/cdap,mpouttuclarke/cdap,chtyim/cdap,chtyim/cdap,hsaputra/cdap
package com.continuuity.data2.dataset2.user; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.guice.ConfigModule; import com.continuuity.common.guice.DiscoveryRuntimeModule; import com.continuuity.common.guice.IOModule; import com.continuuity.common.guice.KafkaClientModule; import com.continuuity.common.guice.LocationRuntimeModule; import com.continuuity.common.guice.ZKClientModule; import com.continuuity.common.metrics.MetricsCollectionService; import com.continuuity.common.metrics.NoOpMetricsCollectionService; import com.continuuity.common.utils.Networks; import com.continuuity.data.runtime.DataFabricModules; import com.continuuity.data.runtime.DataSetServiceModules; import com.continuuity.data2.datafabric.dataset.DataFabricDatasetManager; import com.continuuity.data2.datafabric.dataset.client.DatasetManagerServiceClient; import com.continuuity.data2.datafabric.dataset.service.DatasetManagerService; import com.continuuity.data2.dataset2.manager.DatasetManagementException; import com.continuuity.data2.dataset2.manager.inmemory.InMemoryDatasetDefinitionRegistry; import com.continuuity.data2.transaction.inmemory.InMemoryTransactionManager; import com.continuuity.gateway.auth.AuthModule; import com.continuuity.internal.data.dataset.DatasetInstanceProperties; import com.google.common.base.Optional; import com.google.gson.Gson; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import junit.framework.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.twill.discovery.Discoverable; import org.apache.twill.discovery.DiscoveryServiceClient; import org.apache.twill.discovery.ServiceDiscovered; import org.apache.twill.filesystem.LocationFactory; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; /** * Test for {@link DatasetUserService}. */ public class DatasetUserServiceTest { private static final Gson GSON = new Gson(); private static final Logger LOG = LoggerFactory.getLogger(DatasetUserServiceTest.class); @ClassRule public static TemporaryFolder tmpFolder = new TemporaryFolder(); private DatasetManagerService managerService; private InetSocketAddress userServiceAddress; private DataFabricDatasetManager managerClient; @Before public void setUp() throws IOException { Configuration hConf = new Configuration(); CConfiguration cConf = CConfiguration.create(); File datasetDir = new File(tmpFolder.newFolder(), "datasetUser"); datasetDir.mkdirs(); cConf.set(Constants.Dataset.Manager.OUTPUT_DIR, datasetDir.getAbsolutePath()); cConf.set(Constants.Dataset.Manager.ADDRESS, "localhost"); cConf.setInt(Constants.Dataset.Manager.PORT, Networks.getRandomPort()); cConf.set(Constants.Dataset.User.ADDRESS, "localhost"); cConf.setInt(Constants.Dataset.User.PORT, Networks.getRandomPort()); Injector injector = Guice.createInjector( new ConfigModule(cConf, hConf), new IOModule(), new ZKClientModule(), new KafkaClientModule(), new DiscoveryRuntimeModule().getInMemoryModules(), new LocationRuntimeModule().getInMemoryModules(), new DataFabricModules(cConf, hConf).getInMemoryModules(), new DataSetServiceModules().getInMemoryModule(), new AuthModule(), new AbstractModule() { @Override protected void configure() { bind(MetricsCollectionService.class).to(NoOpMetricsCollectionService.class); } }); InMemoryTransactionManager transactionManager = injector.getInstance(InMemoryTransactionManager.class); transactionManager.startAndWait(); managerService = injector.getInstance(DatasetManagerService.class); managerService.startAndWait(); DiscoveryServiceClient discoveryServiceClient = injector.getInstance(DiscoveryServiceClient.class); ServiceDiscovered discover = discoveryServiceClient.discover(Constants.Service.DATASET_USER); Discoverable userServiceDiscoverable = discover.iterator().next(); userServiceAddress = userServiceDiscoverable.getSocketAddress(); // initialize client DatasetManagerServiceClient serviceClient = new DatasetManagerServiceClient( injector.getInstance(DiscoveryServiceClient.class)); managerClient = new DataFabricDatasetManager( serviceClient, cConf, injector.getInstance(LocationFactory.class), new InMemoryDatasetDefinitionRegistry()); } @After public void tearDown() { managerClient = null; managerService.stopAndWait(); managerService = null; userServiceAddress = null; } @Test public void testRest() throws IOException, URISyntaxException, DatasetManagementException { // check non-existence with 404 testAdminOp("bob", "exists", 404, null); // add instance and check non-existence with 200 managerClient.addInstance("table", "bob", DatasetInstanceProperties.EMPTY); testAdminOp("bob", "exists", 200, false); testAdminOp("joe", "exists", 404, null); // create and check existence testAdminOp("bob", "create", 200, null); testAdminOp("bob", "exists", 200, true); // check various operations testAdminOp("bob", "truncate", 200, null); testAdminOp("bob", "upgrade", 200, null); // drop and check non-existence testAdminOp("bob", "drop", 200, null); testAdminOp("bob", "exists", 200, false); } private void testAdminOp(String instanceName, String opName, int expectedStatus, Object expectedBody) throws URISyntaxException, IOException { URI baseUri = new URI("http://" + userServiceAddress.getHostName() + ":" + userServiceAddress.getPort()); String template = Constants.Gateway.GATEWAY_VERSION + "/data/instances/%s/admin/%s"; URI targetUri = baseUri.resolve(String.format(template, instanceName, opName)); Response<AdminOpResponse> response = doPost(targetUri, AdminOpResponse.class); Assert.assertEquals(expectedStatus, response.getStatusCode()); Assert.assertEquals(expectedBody, response.getBody().or(new AdminOpResponse(null, null)).getResult()); } private <T> Response<T> doPost(URI uri, Class<T> cls) throws IOException { try { LOG.info("doPost({}, {})", uri.toASCIIString(), cls); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); connection.setRequestMethod("POST"); InputStream response = connection.getInputStream(); T body = GSON.fromJson(new InputStreamReader(response), cls); return new Response(connection.getResponseCode(), body); } catch (FileNotFoundException e) { return new Response(404, null); } } private static final class Response<T> { private final int statusCode; private final Optional<T> body; private Response(int statusCode, T body) { this.statusCode = statusCode; this.body = Optional.fromNullable(body); } public int getStatusCode() { return statusCode; } public Optional<T> getBody() { return body; } } }
data-fabric/src/test/java/com/continuuity/data2/dataset2/user/DatasetUserServiceTest.java
package com.continuuity.data2.dataset2.user; import com.continuuity.common.conf.CConfiguration; import com.continuuity.common.conf.Constants; import com.continuuity.common.guice.ConfigModule; import com.continuuity.common.guice.DiscoveryRuntimeModule; import com.continuuity.common.guice.IOModule; import com.continuuity.common.guice.KafkaClientModule; import com.continuuity.common.guice.LocationRuntimeModule; import com.continuuity.common.guice.ZKClientModule; import com.continuuity.common.metrics.MetricsCollectionService; import com.continuuity.common.metrics.NoOpMetricsCollectionService; import com.continuuity.common.utils.Networks; import com.continuuity.data.runtime.DataFabricModules; import com.continuuity.data2.datafabric.dataset.DataFabricDatasetManager; import com.continuuity.data2.datafabric.dataset.client.DatasetManagerServiceClient; import com.continuuity.data2.datafabric.dataset.service.DatasetManagerService; import com.continuuity.data2.dataset2.manager.DatasetManagementException; import com.continuuity.data2.dataset2.manager.inmemory.InMemoryDatasetDefinitionRegistry; import com.continuuity.data2.transaction.inmemory.InMemoryTransactionManager; import com.continuuity.gateway.auth.AuthModule; import com.continuuity.internal.data.dataset.DatasetInstanceProperties; import com.google.common.base.Optional; import com.google.gson.Gson; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import junit.framework.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.twill.discovery.Discoverable; import org.apache.twill.discovery.DiscoveryServiceClient; import org.apache.twill.discovery.ServiceDiscovered; import org.apache.twill.filesystem.LocationFactory; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; /** * Test for {@link DatasetUserService}. */ public class DatasetUserServiceTest { private static final Gson GSON = new Gson(); private static final Logger LOG = LoggerFactory.getLogger(DatasetUserServiceTest.class); @ClassRule public static TemporaryFolder tmpFolder = new TemporaryFolder(); private DatasetManagerService managerService; private InetSocketAddress userServiceAddress; private DataFabricDatasetManager managerClient; @Before public void setUp() throws IOException { Configuration hConf = new Configuration(); CConfiguration cConf = CConfiguration.create(); File datasetDir = new File(tmpFolder.newFolder(), "datasetUser"); datasetDir.mkdirs(); cConf.set(Constants.Dataset.Manager.OUTPUT_DIR, datasetDir.getAbsolutePath()); cConf.set(Constants.Dataset.Manager.ADDRESS, "localhost"); cConf.setInt(Constants.Dataset.Manager.PORT, Networks.getRandomPort()); cConf.set(Constants.Dataset.User.ADDRESS, "localhost"); cConf.setInt(Constants.Dataset.User.PORT, Networks.getRandomPort()); Injector injector = Guice.createInjector( new ConfigModule(cConf, hConf), new IOModule(), new ZKClientModule(), new KafkaClientModule(), new DiscoveryRuntimeModule().getInMemoryModules(), new LocationRuntimeModule().getInMemoryModules(), new DataFabricModules(cConf, hConf).getInMemoryModules(), new AuthModule(), new AbstractModule() { @Override protected void configure() { bind(MetricsCollectionService.class).to(NoOpMetricsCollectionService.class); } }); InMemoryTransactionManager transactionManager = injector.getInstance(InMemoryTransactionManager.class); transactionManager.startAndWait(); managerService = injector.getInstance(DatasetManagerService.class); managerService.startAndWait(); DiscoveryServiceClient discoveryServiceClient = injector.getInstance(DiscoveryServiceClient.class); ServiceDiscovered discover = discoveryServiceClient.discover(Constants.Service.DATASET_USER); Discoverable userServiceDiscoverable = discover.iterator().next(); userServiceAddress = userServiceDiscoverable.getSocketAddress(); // initialize client DatasetManagerServiceClient serviceClient = new DatasetManagerServiceClient( injector.getInstance(DiscoveryServiceClient.class)); managerClient = new DataFabricDatasetManager( serviceClient, cConf, injector.getInstance(LocationFactory.class), new InMemoryDatasetDefinitionRegistry()); } @After public void tearDown() { managerClient = null; managerService.stopAndWait(); managerService = null; userServiceAddress = null; } @Test public void testRest() throws IOException, URISyntaxException, DatasetManagementException { // check non-existence with 404 testAdminOp("bob", "exists", 404, null); // add instance and check non-existence with 200 managerClient.addInstance("table", "bob", DatasetInstanceProperties.EMPTY); testAdminOp("bob", "exists", 200, false); testAdminOp("joe", "exists", 404, null); // create and check existence testAdminOp("bob", "create", 200, null); testAdminOp("bob", "exists", 200, true); // check various operations testAdminOp("bob", "truncate", 200, null); testAdminOp("bob", "upgrade", 200, null); // drop and check non-existence testAdminOp("bob", "drop", 200, null); testAdminOp("bob", "exists", 200, false); } private void testAdminOp(String instanceName, String opName, int expectedStatus, Object expectedBody) throws URISyntaxException, IOException { URI baseUri = new URI("http://" + userServiceAddress.getHostName() + ":" + userServiceAddress.getPort()); String template = Constants.Gateway.GATEWAY_VERSION + "/data/instances/%s/admin/%s"; URI targetUri = baseUri.resolve(String.format(template, instanceName, opName)); Response<AdminOpResponse> response = doPost(targetUri, AdminOpResponse.class); Assert.assertEquals(expectedStatus, response.getStatusCode()); Assert.assertEquals(expectedBody, response.getBody().or(new AdminOpResponse(null, null)).getResult()); } private <T> Response<T> doPost(URI uri, Class<T> cls) throws IOException { try { LOG.info("doPost({}, {})", uri.toASCIIString(), cls); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); connection.setRequestMethod("POST"); InputStream response = connection.getInputStream(); T body = GSON.fromJson(new InputStreamReader(response), cls); return new Response(connection.getResponseCode(), body); } catch (FileNotFoundException e) { return new Response(404, null); } } private static final class Response<T> { private final int statusCode; private final Optional<T> body; private Response(int statusCode, T body) { this.statusCode = statusCode; this.body = Optional.fromNullable(body); } public int getStatusCode() { return statusCode; } public Optional<T> getBody() { return body; } } }
fix unit-test guice bindings
data-fabric/src/test/java/com/continuuity/data2/dataset2/user/DatasetUserServiceTest.java
fix unit-test guice bindings
<ide><path>ata-fabric/src/test/java/com/continuuity/data2/dataset2/user/DatasetUserServiceTest.java <ide> import com.continuuity.common.metrics.NoOpMetricsCollectionService; <ide> import com.continuuity.common.utils.Networks; <ide> import com.continuuity.data.runtime.DataFabricModules; <add>import com.continuuity.data.runtime.DataSetServiceModules; <ide> import com.continuuity.data2.datafabric.dataset.DataFabricDatasetManager; <ide> import com.continuuity.data2.datafabric.dataset.client.DatasetManagerServiceClient; <ide> import com.continuuity.data2.datafabric.dataset.service.DatasetManagerService; <ide> new DiscoveryRuntimeModule().getInMemoryModules(), <ide> new LocationRuntimeModule().getInMemoryModules(), <ide> new DataFabricModules(cConf, hConf).getInMemoryModules(), <add> new DataSetServiceModules().getInMemoryModule(), <ide> new AuthModule(), new AbstractModule() { <ide> @Override <ide> protected void configure() {
Java
mit
c358f26d16f625b7a4aedca1b106529e16e95aff
0
ohhopi/six-couleurs
package edu.isep.sixcolors.controller; import edu.isep.sixcolors.model.*; import edu.isep.sixcolors.model.AI.AIInterface; import edu.isep.sixcolors.model.AI.DumbAI; import edu.isep.sixcolors.model.entity.Board; import edu.isep.sixcolors.model.entity.Player; import edu.isep.sixcolors.model.entity.Players; import edu.isep.sixcolors.model.entity.TileColor; import edu.isep.sixcolors.view.WarningPopup; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Play implements ActionListener { Game game; public Play(Game game){ this.game = game; } public void actionPerformed(ActionEvent e) { // Fetch the text of the button : String sourceText = ((JButton) e.getSource()).getText(); // Fetch the content pane of the window that triggered the JPanel contentPane = (JPanel) ((JFrame) SwingUtilities.getRoot((Component) e.getSource())).getContentPane(); switch(game.getState()) { case Menu: // TODO break; case GridConfig: switch(sourceText) { case Config.RANDOM_BOARD_BUTTON_TEXT: // check inputs, init the grid and set game state to NameConfig initGrid(contentPane); break; case Config.CUSTOM_BOARD_BUTTON_TEXT: break; } break; case NameConfig: initPlayers(contentPane); break; case CustomGrid: break; case Game: colorButtonPressed(e); break; case End: break; } } public void initGrid(JPanel contentPane){ // Try parsing the number input try { // If the order of the texts fields is changed, this could break : int boardSize = Integer.parseInt(((JTextField) ((JPanel) contentPane.getComponent(0)).getComponent(1)).getText()); int playerNb = Integer.parseInt(((JTextField) ((JPanel) contentPane.getComponent(0)).getComponent(3)).getText()); // Check if the inputs are within boundaries : if (boardSize >= Config.GRID_MIN && boardSize <= Config.GRID_MAX && playerNb >= Config.PLAYER_NB_MIN && playerNb <= Config.PLAYER_NB_MAX){ game.setBoard(new Board(boardSize)); Players players = new Players(playerNb); players.setPlayerNumber(playerNb); game.setPlayers(players); // Set game state : game.setState(GameState.NameConfig); } else { // input out of bounds new WarningPopup( Config.OUT_OF_BOUNDS_GRID_CONFIG_MESSAGE + Config.newLine + Config.OUT_OF_BOUNDS_PLAYER_NB_CONFIG_MESSAGE, Config.INVALID_ENTRY_TITLE ); } } catch (NumberFormatException x) { new WarningPopup ( Config.NUMBER_FORMAT_CONFIG_MESSAGE, Config.INVALID_ENTRY_TITLE ); } } public void initPlayers(JPanel contentPane){ int playerNb = game.getPlayers().getPlayerNumber(); Players players = game.getPlayers(); boolean emptyName = false; for (int i = 0; i < playerNb; i++) { String playerName = ((JTextField) ((JPanel) contentPane.getComponent(0)).getComponent(4 * i + 1)).getText(); boolean playersAi = ((JCheckBox) ((JPanel) contentPane.getComponent(0)).getComponent(4 * i + 2)).isSelected(); if (playerName == null || playerName.equals("")) { emptyName = true; new WarningPopup(Config.EMPTY_PLAYER_NAME_MESSAGE, Config.INVALID_ENTRY_TITLE); break; } else { players.setPlayer(i, new Player(playerName)); players.getPlayer(i).setAi(playersAi); if (playersAi) { AIInterface AI = new DumbAI(); players.getPlayer(i).setAIInstance(AI); } } } if (!emptyName){ game.initGame(); game.setState(GameState.Game); } } /** * Returns the winner or null if there is none yet * * @return Player winner or null; */ private Player checkForWinner() { int winPoints = (int) Math.floor(Math.pow(game.getBoard().getWidth(), 2) / 2); int totalPoints = 0; int maxPoints = 0; int playerPoints; Player winner = game.getCurrentPlayer(); for (int i = 0; i < game.getPlayers().getPlayerNumber(); i++) { playerPoints = game.getPlayers().getPlayer(i).getPoints(); if (playerPoints > maxPoints) { maxPoints = playerPoints; winner = game.getPlayers().getPlayer(i); } totalPoints += game.getPlayers().getPlayer(i).getPoints(); } if (game.getCurrentPlayer().getPoints() > winPoints || totalPoints == Math.pow(game.getBoard().getWidth(), 2)) { return winner; } return null; } public void colorButtonPressed(ActionEvent e){ // 1. Fetch the current player & declare choice to catch : Player currentPlayer = game.getCurrentPlayer(); TileColor chosenColor = null; // 2. Get what color the player has chosen : if(game.getCurrentPlayer().isAi()) { // If it's an AI, then we wait for the ai to send back a choice chosenColor = currentPlayer.getAIInstance().colorChoice(game); } else { // If it's not an AI, then we wait for the physical player to make a choice in the view String buttonText = ((JButton) e.getSource()).getText(); //Parse the color choice of the player : try { chosenColor = TileColor.parseTileColor(buttonText); } catch (Exception e1) { e1.printStackTrace(); } } // 3. Set the current player's color : currentPlayer.setTileColor(chosenColor); // 4. Update the board to apply the color choice : game.updateBoard( currentPlayer.getStartingTileCoords()[0], currentPlayer.getStartingTileCoords()[1], currentPlayer ); //5. Checks if a player has won : Player winner = checkForWinner(); if (winner != null) { game.setWinner(winner); game.setState(GameState.End); } game.nextPlayer(); } }
6Colors/src/edu/isep/sixcolors/controller/Play.java
package edu.isep.sixcolors.controller; import edu.isep.sixcolors.model.*; import edu.isep.sixcolors.model.AI.AIInterface; import edu.isep.sixcolors.model.AI.DumbAI; import edu.isep.sixcolors.model.entity.Board; import edu.isep.sixcolors.model.entity.Player; import edu.isep.sixcolors.model.entity.Players; import edu.isep.sixcolors.model.entity.TileColor; import edu.isep.sixcolors.view.WarningPopup; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Play implements ActionListener { Game game; public Play(Game game){ this.game = game; } public void actionPerformed(ActionEvent e) { // Fetch the text of the button : String sourceText = ((JButton) e.getSource()).getText(); // Fetch the content pane of the window that triggered the JPanel contentPane = (JPanel) ((JFrame) SwingUtilities.getRoot((Component) e.getSource())).getContentPane(); switch(game.getState()) { case Menu: // TODO break; case GridConfig: switch(sourceText) { case Config.RANDOM_BOARD_BUTTON_TEXT: // check inputs, init the grid and set game state to NameConfig initGrid(contentPane); break; case Config.CUSTOM_BOARD_BUTTON_TEXT: break; } break; case NameConfig: initPlayers(contentPane); break; case CustomGrid: break; case Game: colorButtonPressed(e); break; case End: break; } } public void initGrid(JPanel contentPane){ // Try parsing the number input try { // If the order of the texts fields is changed, this could break : int boardSize = Integer.parseInt(((JTextField) ((JPanel) contentPane.getComponent(0)).getComponent(1)).getText()); int playerNb = Integer.parseInt(((JTextField) ((JPanel) contentPane.getComponent(0)).getComponent(3)).getText()); // Check if the inputs are within boundaries : if (boardSize >= Config.GRID_MIN && boardSize <= Config.GRID_MAX && playerNb >= Config.PLAYER_NB_MIN && playerNb <= Config.PLAYER_NB_MAX){ game.setBoard(new Board(boardSize)); Players players = new Players(playerNb); players.setPlayerNumber(playerNb); game.setPlayers(players); // Set game state : game.setState(GameState.NameConfig); } else { // input out of bounds new WarningPopup( Config.OUT_OF_BOUNDS_GRID_CONFIG_MESSAGE + Config.newLine + Config.OUT_OF_BOUNDS_PLAYER_NB_CONFIG_MESSAGE, Config.INVALID_ENTRY_TITLE ); } } catch (NumberFormatException x) { new WarningPopup ( Config.NUMBER_FORMAT_CONFIG_MESSAGE, Config.INVALID_ENTRY_TITLE ); } } public void initPlayers(JPanel contentPane){ int playerNb = game.getPlayers().getPlayerNumber(); Players players = game.getPlayers(); boolean emptyName = false; for (int i = 0; i < playerNb; i++) { String playerName = ((JTextField) ((JPanel) contentPane.getComponent(0)).getComponent(4 * i + 1)).getText(); boolean playersAi = ((JCheckBox) ((JPanel) contentPane.getComponent(0)).getComponent(4 * i + 2)).isSelected(); if (playerName == null || playerName.equals("")) { emptyName = true; new WarningPopup(Config.EMPTY_PLAYER_NAME_MESSAGE, Config.INVALID_ENTRY_TITLE); break; } else { players.setPlayer(i, new Player(playerName)); players.getPlayer(i).setAi(playersAi); if (playersAi) { AIInterface AI = new DumbAI(); players.getPlayer(i).setAIInstance(AI); } } } if (!emptyName){ game.initGame(); game.setState(GameState.Game); } } /** * Returns the winner or null if there is none yet * * @return Player winner or null; */ private Player checkForWinner() { int winPoints = (int) Math.floor(Math.pow(game.getBoard().getWidth(), 2) / game.getPlayers().getPlayerNumber()); int totalPoints = 0; int maxPoints = 0; int playerPoints; Player winner = game.getCurrentPlayer(); for (int i = 0; i < game.getPlayers().getPlayerNumber(); i++) { playerPoints = game.getPlayers().getPlayer(i).getPoints(); if (playerPoints > maxPoints) { maxPoints = playerPoints; winner = game.getPlayers().getPlayer(i); } totalPoints += game.getPlayers().getPlayer(i).getPoints(); } if (game.getCurrentPlayer().getPoints() > winPoints || totalPoints == Math.pow(game.getBoard().getWidth(), 2)) { return winner; } return null; } public void colorButtonPressed(ActionEvent e){ // 1. Fetch the current player & declare choice to catch : Player currentPlayer = game.getCurrentPlayer(); TileColor chosenColor = null; // 2. Get what color the player has chosen : if(game.getCurrentPlayer().isAi()) { // If it's an AI, then we wait for the ai to send back a choice chosenColor = currentPlayer.getAIInstance().colorChoice(game); } else { // If it's not an AI, then we wait for the physical player to make a choice in the view String buttonText = ((JButton) e.getSource()).getText(); //Parse the color choice of the player : try { chosenColor = TileColor.parseTileColor(buttonText); } catch (Exception e1) { e1.printStackTrace(); } } // 3. Set the current player's color : currentPlayer.setTileColor(chosenColor); // 4. Update the board to apply the color choice : game.updateBoard( currentPlayer.getStartingTileCoords()[0], currentPlayer.getStartingTileCoords()[1], currentPlayer ); //5. Checks if a player has won : Player winner = checkForWinner(); if (winner != null) { game.setWinner(winner); game.setState(GameState.End); } game.nextPlayer(); } }
Fixes endgame
6Colors/src/edu/isep/sixcolors/controller/Play.java
Fixes endgame
<ide><path>Colors/src/edu/isep/sixcolors/controller/Play.java <ide> */ <ide> <ide> private Player checkForWinner() { <del> int winPoints = (int) Math.floor(Math.pow(game.getBoard().getWidth(), 2) / game.getPlayers().getPlayerNumber()); <add> int winPoints = (int) Math.floor(Math.pow(game.getBoard().getWidth(), 2) / 2); <ide> int totalPoints = 0; <ide> int maxPoints = 0; <ide> int playerPoints;
Java
apache-2.0
d7bb6e7235313dc74d9e5d3d72a48e412cacf8eb
0
amzn/exoplayer-amazon-port,amzn/exoplayer-amazon-port,google/ExoPlayer,androidx/media,ened/ExoPlayer,google/ExoPlayer,ened/ExoPlayer,androidx/media,amzn/exoplayer-amazon-port,androidx/media,google/ExoPlayer,ened/ExoPlayer
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2; import static com.google.android.exoplayer2.util.Util.castNonNull; import static java.lang.Math.max; import static java.lang.Math.min; import android.media.DeniedByServerException; import android.media.MediaDrm; import android.media.MediaDrmResetException; import android.media.NotProvisionedException; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.Process; import android.os.SystemClock; import android.system.ErrnoException; import android.system.OsConstants; import android.util.Pair; import androidx.annotation.CheckResult; import androidx.annotation.DoNotInline; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.google.android.exoplayer2.DefaultMediaClock.PlaybackParametersListener; import com.google.android.exoplayer2.PlaybackException.ErrorCode; import com.google.android.exoplayer2.Player.DiscontinuityReason; import com.google.android.exoplayer2.Player.PlayWhenReadyChangeReason; import com.google.android.exoplayer2.Player.PlaybackSuppressionReason; import com.google.android.exoplayer2.Player.RepeatMode; import com.google.android.exoplayer2.analytics.AnalyticsCollector; import com.google.android.exoplayer2.drm.DefaultDrmSessionManager; import com.google.android.exoplayer2.drm.DrmSession; import com.google.android.exoplayer2.drm.UnsupportedDrmException; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.source.BehindLiveWindowException; import com.google.android.exoplayer2.source.MediaPeriod; import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId; import com.google.android.exoplayer2.source.SampleStream; import com.google.android.exoplayer2.source.ShuffleOrder; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.text.TextRenderer; import com.google.android.exoplayer2.trackselection.ExoTrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelectorResult; import com.google.android.exoplayer2.upstream.BandwidthMeter; import com.google.android.exoplayer2.upstream.FileDataSource; import com.google.android.exoplayer2.upstream.HttpDataSource; import com.google.android.exoplayer2.upstream.UdpDataSource; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Clock; import com.google.android.exoplayer2.util.HandlerWrapper; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.util.TraceUtil; import com.google.android.exoplayer2.util.Util; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import java.io.FileNotFoundException; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** Implements the internal behavior of {@link ExoPlayerImpl}. */ /* package */ final class ExoPlayerImplInternal implements Handler.Callback, MediaPeriod.Callback, TrackSelector.InvalidationListener, MediaSourceList.MediaSourceListInfoRefreshListener, PlaybackParametersListener, PlayerMessage.Sender { private static final String TAG = "ExoPlayerImplInternal"; public static final class PlaybackInfoUpdate { private boolean hasPendingChange; public PlaybackInfo playbackInfo; public int operationAcks; public boolean positionDiscontinuity; @DiscontinuityReason public int discontinuityReason; public boolean hasPlayWhenReadyChangeReason; @PlayWhenReadyChangeReason public int playWhenReadyChangeReason; public PlaybackInfoUpdate(PlaybackInfo playbackInfo) { this.playbackInfo = playbackInfo; } public void incrementPendingOperationAcks(int operationAcks) { hasPendingChange |= operationAcks > 0; this.operationAcks += operationAcks; } public void setPlaybackInfo(PlaybackInfo playbackInfo) { hasPendingChange |= this.playbackInfo != playbackInfo; this.playbackInfo = playbackInfo; } public void setPositionDiscontinuity(@DiscontinuityReason int discontinuityReason) { if (positionDiscontinuity && this.discontinuityReason != Player.DISCONTINUITY_REASON_INTERNAL) { // We always prefer non-internal discontinuity reasons. We also assume that we won't report // more than one non-internal discontinuity per message iteration. Assertions.checkArgument(discontinuityReason == Player.DISCONTINUITY_REASON_INTERNAL); return; } hasPendingChange = true; positionDiscontinuity = true; this.discontinuityReason = discontinuityReason; } public void setPlayWhenReadyChangeReason( @PlayWhenReadyChangeReason int playWhenReadyChangeReason) { hasPendingChange = true; this.hasPlayWhenReadyChangeReason = true; this.playWhenReadyChangeReason = playWhenReadyChangeReason; } } public interface PlaybackInfoUpdateListener { void onPlaybackInfoUpdate(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfo); } // Internal messages private static final int MSG_PREPARE = 0; private static final int MSG_SET_PLAY_WHEN_READY = 1; private static final int MSG_DO_SOME_WORK = 2; private static final int MSG_SEEK_TO = 3; private static final int MSG_SET_PLAYBACK_PARAMETERS = 4; private static final int MSG_SET_SEEK_PARAMETERS = 5; private static final int MSG_STOP = 6; private static final int MSG_RELEASE = 7; private static final int MSG_PERIOD_PREPARED = 8; private static final int MSG_SOURCE_CONTINUE_LOADING_REQUESTED = 9; private static final int MSG_TRACK_SELECTION_INVALIDATED = 10; private static final int MSG_SET_REPEAT_MODE = 11; private static final int MSG_SET_SHUFFLE_ENABLED = 12; private static final int MSG_SET_FOREGROUND_MODE = 13; private static final int MSG_SEND_MESSAGE = 14; private static final int MSG_SEND_MESSAGE_TO_TARGET_THREAD = 15; private static final int MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL = 16; private static final int MSG_SET_MEDIA_SOURCES = 17; private static final int MSG_ADD_MEDIA_SOURCES = 18; private static final int MSG_MOVE_MEDIA_SOURCES = 19; private static final int MSG_REMOVE_MEDIA_SOURCES = 20; private static final int MSG_SET_SHUFFLE_ORDER = 21; private static final int MSG_PLAYLIST_UPDATE_REQUESTED = 22; private static final int MSG_SET_PAUSE_AT_END_OF_WINDOW = 23; private static final int MSG_SET_OFFLOAD_SCHEDULING_ENABLED = 24; private static final int MSG_ATTEMPT_RENDERER_ERROR_RECOVERY = 25; private static final int ACTIVE_INTERVAL_MS = 10; private static final int IDLE_INTERVAL_MS = 1000; /** * Duration under which pausing the main DO_SOME_WORK loop is not expected to yield significant * power saving. * * <p>This value is probably too high, power measurements are needed adjust it, but as renderer * sleep is currently only implemented for audio offload, which uses buffer much bigger than 2s, * this does not matter for now. */ private static final long MIN_RENDERER_SLEEP_DURATION_MS = 2000; private final Renderer[] renderers; private final RendererCapabilities[] rendererCapabilities; private final TrackSelector trackSelector; private final TrackSelectorResult emptyTrackSelectorResult; private final LoadControl loadControl; private final BandwidthMeter bandwidthMeter; private final HandlerWrapper handler; private final HandlerThread internalPlaybackThread; private final Looper playbackLooper; private final Timeline.Window window; private final Timeline.Period period; private final long backBufferDurationUs; private final boolean retainBackBufferFromKeyframe; private final DefaultMediaClock mediaClock; private final ArrayList<PendingMessageInfo> pendingMessages; private final Clock clock; private final PlaybackInfoUpdateListener playbackInfoUpdateListener; private final MediaPeriodQueue queue; private final MediaSourceList mediaSourceList; private final LivePlaybackSpeedControl livePlaybackSpeedControl; private final long releaseTimeoutMs; @SuppressWarnings("unused") private SeekParameters seekParameters; private PlaybackInfo playbackInfo; private PlaybackInfoUpdate playbackInfoUpdate; private boolean released; private boolean pauseAtEndOfWindow; private boolean pendingPauseAtEndOfPeriod; private boolean isRebuffering; private boolean shouldContinueLoading; @Player.RepeatMode private int repeatMode; private boolean shuffleModeEnabled; private boolean foregroundMode; private boolean requestForRendererSleep; private boolean offloadSchedulingEnabled; private int enabledRendererCount; @Nullable private SeekPosition pendingInitialSeekPosition; private long rendererPositionUs; private int nextPendingMessageIndexHint; private boolean deliverPendingMessageAtStartPositionRequired; @Nullable private ExoPlaybackException pendingRecoverableRendererError; private long setForegroundModeTimeoutMs; public ExoPlayerImplInternal( Renderer[] renderers, TrackSelector trackSelector, TrackSelectorResult emptyTrackSelectorResult, LoadControl loadControl, BandwidthMeter bandwidthMeter, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled, @Nullable AnalyticsCollector analyticsCollector, SeekParameters seekParameters, LivePlaybackSpeedControl livePlaybackSpeedControl, long releaseTimeoutMs, boolean pauseAtEndOfWindow, Looper applicationLooper, Clock clock, PlaybackInfoUpdateListener playbackInfoUpdateListener) { this.playbackInfoUpdateListener = playbackInfoUpdateListener; this.renderers = renderers; this.trackSelector = trackSelector; this.emptyTrackSelectorResult = emptyTrackSelectorResult; this.loadControl = loadControl; this.bandwidthMeter = bandwidthMeter; this.repeatMode = repeatMode; this.shuffleModeEnabled = shuffleModeEnabled; this.seekParameters = seekParameters; this.livePlaybackSpeedControl = livePlaybackSpeedControl; this.releaseTimeoutMs = releaseTimeoutMs; this.setForegroundModeTimeoutMs = releaseTimeoutMs; this.pauseAtEndOfWindow = pauseAtEndOfWindow; this.clock = clock; backBufferDurationUs = loadControl.getBackBufferDurationUs(); retainBackBufferFromKeyframe = loadControl.retainBackBufferFromKeyframe(); playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult); playbackInfoUpdate = new PlaybackInfoUpdate(playbackInfo); rendererCapabilities = new RendererCapabilities[renderers.length]; for (int i = 0; i < renderers.length; i++) { renderers[i].setIndex(i); rendererCapabilities[i] = renderers[i].getCapabilities(); } mediaClock = new DefaultMediaClock(this, clock); pendingMessages = new ArrayList<>(); window = new Timeline.Window(); period = new Timeline.Period(); trackSelector.init(/* listener= */ this, bandwidthMeter); deliverPendingMessageAtStartPositionRequired = true; Handler eventHandler = new Handler(applicationLooper); queue = new MediaPeriodQueue(analyticsCollector, eventHandler); mediaSourceList = new MediaSourceList(/* listener= */ this, analyticsCollector, eventHandler); // Note: The documentation for Process.THREAD_PRIORITY_AUDIO that states "Applications can // not normally change to this priority" is incorrect. internalPlaybackThread = new HandlerThread("ExoPlayer:Playback", Process.THREAD_PRIORITY_AUDIO); internalPlaybackThread.start(); playbackLooper = internalPlaybackThread.getLooper(); handler = clock.createHandler(playbackLooper, this); } public void experimentalSetForegroundModeTimeoutMs(long setForegroundModeTimeoutMs) { this.setForegroundModeTimeoutMs = setForegroundModeTimeoutMs; } public void experimentalSetOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) { handler .obtainMessage( MSG_SET_OFFLOAD_SCHEDULING_ENABLED, offloadSchedulingEnabled ? 1 : 0, /* unused */ 0) .sendToTarget(); } public void prepare() { handler.obtainMessage(MSG_PREPARE).sendToTarget(); } public void setPlayWhenReady( boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason) { handler .obtainMessage(MSG_SET_PLAY_WHEN_READY, playWhenReady ? 1 : 0, playbackSuppressionReason) .sendToTarget(); } public void setPauseAtEndOfWindow(boolean pauseAtEndOfWindow) { handler .obtainMessage(MSG_SET_PAUSE_AT_END_OF_WINDOW, pauseAtEndOfWindow ? 1 : 0, /* ignored */ 0) .sendToTarget(); } public void setRepeatMode(@Player.RepeatMode int repeatMode) { handler.obtainMessage(MSG_SET_REPEAT_MODE, repeatMode, 0).sendToTarget(); } public void setShuffleModeEnabled(boolean shuffleModeEnabled) { handler.obtainMessage(MSG_SET_SHUFFLE_ENABLED, shuffleModeEnabled ? 1 : 0, 0).sendToTarget(); } public void seekTo(Timeline timeline, int windowIndex, long positionUs) { handler .obtainMessage(MSG_SEEK_TO, new SeekPosition(timeline, windowIndex, positionUs)) .sendToTarget(); } public void setPlaybackParameters(PlaybackParameters playbackParameters) { handler.obtainMessage(MSG_SET_PLAYBACK_PARAMETERS, playbackParameters).sendToTarget(); } public void setSeekParameters(SeekParameters seekParameters) { handler.obtainMessage(MSG_SET_SEEK_PARAMETERS, seekParameters).sendToTarget(); } public void stop() { handler.obtainMessage(MSG_STOP).sendToTarget(); } public void setMediaSources( List<MediaSourceList.MediaSourceHolder> mediaSources, int windowIndex, long positionUs, ShuffleOrder shuffleOrder) { handler .obtainMessage( MSG_SET_MEDIA_SOURCES, new MediaSourceListUpdateMessage(mediaSources, shuffleOrder, windowIndex, positionUs)) .sendToTarget(); } public void addMediaSources( int index, List<MediaSourceList.MediaSourceHolder> mediaSources, ShuffleOrder shuffleOrder) { handler .obtainMessage( MSG_ADD_MEDIA_SOURCES, index, /* ignored */ 0, new MediaSourceListUpdateMessage( mediaSources, shuffleOrder, /* windowIndex= */ C.INDEX_UNSET, /* positionUs= */ C.TIME_UNSET)) .sendToTarget(); } public void removeMediaSources(int fromIndex, int toIndex, ShuffleOrder shuffleOrder) { handler .obtainMessage(MSG_REMOVE_MEDIA_SOURCES, fromIndex, toIndex, shuffleOrder) .sendToTarget(); } public void moveMediaSources( int fromIndex, int toIndex, int newFromIndex, ShuffleOrder shuffleOrder) { MoveMediaItemsMessage moveMediaItemsMessage = new MoveMediaItemsMessage(fromIndex, toIndex, newFromIndex, shuffleOrder); handler.obtainMessage(MSG_MOVE_MEDIA_SOURCES, moveMediaItemsMessage).sendToTarget(); } public void setShuffleOrder(ShuffleOrder shuffleOrder) { handler.obtainMessage(MSG_SET_SHUFFLE_ORDER, shuffleOrder).sendToTarget(); } @Override public synchronized void sendMessage(PlayerMessage message) { if (released || !internalPlaybackThread.isAlive()) { Log.w(TAG, "Ignoring messages sent after release."); message.markAsProcessed(/* isDelivered= */ false); return; } handler.obtainMessage(MSG_SEND_MESSAGE, message).sendToTarget(); } /** * Sets the foreground mode. * * @param foregroundMode Whether foreground mode should be enabled. * @return Whether the operations succeeded. If false, the operation timed out. */ public synchronized boolean setForegroundMode(boolean foregroundMode) { if (released || !internalPlaybackThread.isAlive()) { return true; } if (foregroundMode) { handler.obtainMessage(MSG_SET_FOREGROUND_MODE, /* foregroundMode */ 1, 0).sendToTarget(); return true; } else { AtomicBoolean processedFlag = new AtomicBoolean(); handler .obtainMessage(MSG_SET_FOREGROUND_MODE, /* foregroundMode */ 0, 0, processedFlag) .sendToTarget(); waitUninterruptibly(/* condition= */ processedFlag::get, setForegroundModeTimeoutMs); return processedFlag.get(); } } /** * Releases the player. * * @return Whether the release succeeded. If false, the release timed out. */ public synchronized boolean release() { if (released || !internalPlaybackThread.isAlive()) { return true; } handler.sendEmptyMessage(MSG_RELEASE); waitUninterruptibly(/* condition= */ () -> released, releaseTimeoutMs); return released; } public Looper getPlaybackLooper() { return playbackLooper; } // Playlist.PlaylistInfoRefreshListener implementation. @Override public void onPlaylistUpdateRequested() { handler.sendEmptyMessage(MSG_PLAYLIST_UPDATE_REQUESTED); } // MediaPeriod.Callback implementation. @Override public void onPrepared(MediaPeriod source) { handler.obtainMessage(MSG_PERIOD_PREPARED, source).sendToTarget(); } @Override public void onContinueLoadingRequested(MediaPeriod source) { handler.obtainMessage(MSG_SOURCE_CONTINUE_LOADING_REQUESTED, source).sendToTarget(); } // TrackSelector.InvalidationListener implementation. @Override public void onTrackSelectionsInvalidated() { handler.sendEmptyMessage(MSG_TRACK_SELECTION_INVALIDATED); } // DefaultMediaClock.PlaybackParametersListener implementation. @Override public void onPlaybackParametersChanged(PlaybackParameters newPlaybackParameters) { handler .obtainMessage(MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL, newPlaybackParameters) .sendToTarget(); } // Handler.Callback implementation. @Override public boolean handleMessage(Message msg) { try { switch (msg.what) { case MSG_PREPARE: prepareInternal(); break; case MSG_SET_PLAY_WHEN_READY: setPlayWhenReadyInternal( /* playWhenReady= */ msg.arg1 != 0, /* playbackSuppressionReason= */ msg.arg2, /* operationAck= */ true, Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST); break; case MSG_SET_REPEAT_MODE: setRepeatModeInternal(msg.arg1); break; case MSG_SET_SHUFFLE_ENABLED: setShuffleModeEnabledInternal(msg.arg1 != 0); break; case MSG_DO_SOME_WORK: doSomeWork(); break; case MSG_SEEK_TO: seekToInternal((SeekPosition) msg.obj); break; case MSG_SET_PLAYBACK_PARAMETERS: setPlaybackParametersInternal((PlaybackParameters) msg.obj); break; case MSG_SET_SEEK_PARAMETERS: setSeekParametersInternal((SeekParameters) msg.obj); break; case MSG_SET_FOREGROUND_MODE: setForegroundModeInternal( /* foregroundMode= */ msg.arg1 != 0, /* processedFlag= */ (AtomicBoolean) msg.obj); break; case MSG_STOP: stopInternal(/* forceResetRenderers= */ false, /* acknowledgeStop= */ true); break; case MSG_PERIOD_PREPARED: handlePeriodPrepared((MediaPeriod) msg.obj); break; case MSG_SOURCE_CONTINUE_LOADING_REQUESTED: handleContinueLoadingRequested((MediaPeriod) msg.obj); break; case MSG_TRACK_SELECTION_INVALIDATED: reselectTracksInternal(); break; case MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL: handlePlaybackParameters((PlaybackParameters) msg.obj, /* acknowledgeCommand= */ false); break; case MSG_SEND_MESSAGE: sendMessageInternal((PlayerMessage) msg.obj); break; case MSG_SEND_MESSAGE_TO_TARGET_THREAD: sendMessageToTargetThread((PlayerMessage) msg.obj); break; case MSG_SET_MEDIA_SOURCES: setMediaItemsInternal((MediaSourceListUpdateMessage) msg.obj); break; case MSG_ADD_MEDIA_SOURCES: addMediaItemsInternal((MediaSourceListUpdateMessage) msg.obj, msg.arg1); break; case MSG_MOVE_MEDIA_SOURCES: moveMediaItemsInternal((MoveMediaItemsMessage) msg.obj); break; case MSG_REMOVE_MEDIA_SOURCES: removeMediaItemsInternal(msg.arg1, msg.arg2, (ShuffleOrder) msg.obj); break; case MSG_SET_SHUFFLE_ORDER: setShuffleOrderInternal((ShuffleOrder) msg.obj); break; case MSG_PLAYLIST_UPDATE_REQUESTED: mediaSourceListUpdateRequestedInternal(); break; case MSG_SET_PAUSE_AT_END_OF_WINDOW: setPauseAtEndOfWindowInternal(msg.arg1 != 0); break; case MSG_SET_OFFLOAD_SCHEDULING_ENABLED: setOffloadSchedulingEnabledInternal(msg.arg1 == 1); break; case MSG_ATTEMPT_RENDERER_ERROR_RECOVERY: attemptRendererErrorRecovery(); break; case MSG_RELEASE: releaseInternal(); // Return immediately to not send playback info updates after release. return true; default: return false; } } catch (ExoPlaybackException e) { if (e.type == ExoPlaybackException.TYPE_RENDERER) { @Nullable MediaPeriodHolder readingPeriod = queue.getReadingPeriod(); if (readingPeriod != null) { // We can assume that all renderer errors happen in the context of the reading period. See // [internal: b/150584930#comment4] for exceptions that aren't covered by this assumption. e = e.copyWithMediaPeriodId(readingPeriod.info.id); } } if (e.isRecoverable && pendingRecoverableRendererError == null) { Log.w(TAG, "Recoverable renderer error", e); pendingRecoverableRendererError = e; // Given that the player is now in an unhandled exception state, the error needs to be // recovered or the player stopped before any other message is handled. handler.sendMessageAtFrontOfQueue( handler.obtainMessage(MSG_ATTEMPT_RENDERER_ERROR_RECOVERY, e)); } else { if (pendingRecoverableRendererError != null) { pendingRecoverableRendererError.addSuppressed(e); e = pendingRecoverableRendererError; } Log.e(TAG, "Playback error", e); stopInternal(/* forceResetRenderers= */ true, /* acknowledgeStop= */ false); playbackInfo = playbackInfo.copyWithPlaybackError(e); } } catch (DrmSession.DrmSessionException e) { @Nullable Throwable cause = e.getCause(); @ErrorCode int errorCode; if (Util.SDK_INT >= 21 && PlatformOperationsWrapperV21.isMediaDrmStateException(cause)) { errorCode = PlatformOperationsWrapperV21.mediaDrmStateExceptionToErrorCode(cause); } else if (Util.SDK_INT >= 23 && PlatformOperationsWrapperV23.isMediaDrmResetException(cause)) { errorCode = PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR; } else if (Util.SDK_INT >= 18 && PlatformOperationsWrapperV18.isNotProvisionedException(cause)) { errorCode = PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED; } else if (Util.SDK_INT >= 18 && PlatformOperationsWrapperV18.isDeniedByServerException(cause)) { errorCode = PlaybackException.ERROR_CODE_DRM_DEVICE_REVOKED; } else if (cause instanceof UnsupportedDrmException) { errorCode = PlaybackException.ERROR_CODE_DRM_SCHEME_UNSUPPORTED; } else if (cause instanceof DefaultDrmSessionManager.MissingSchemeDataException) { errorCode = PlaybackException.ERROR_CODE_DRM_CONTENT_ERROR; } else { errorCode = PlaybackException.ERROR_CODE_DRM_UNSPECIFIED; } handleIoException(e, errorCode); } catch (FileDataSource.FileDataSourceException e) { @Nullable Throwable cause = e.getCause(); @ErrorCode int errorCode; if (cause instanceof FileNotFoundException) { if (Util.SDK_INT >= 21 && PlatformOperationsWrapperV21.isPermissionError(cause.getCause())) { errorCode = PlaybackException.ERROR_CODE_IO_NO_PERMISSION; } else { errorCode = PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND; } } else if (cause instanceof SecurityException) { errorCode = PlaybackException.ERROR_CODE_IO_NO_PERMISSION; } else { errorCode = PlaybackException.ERROR_CODE_IO_UNSPECIFIED; } handleIoException(e, errorCode); } catch (ParserException e) { @ErrorCode int errorCode; if (e.dataType == C.DATA_TYPE_MEDIA) { errorCode = e.contentIsMalformed ? PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED : PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED; } else if (e.dataType == C.DATA_TYPE_MANIFEST) { errorCode = e.contentIsMalformed ? PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED : PlaybackException.ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED; } else { errorCode = PlaybackException.ERROR_CODE_UNSPECIFIED; } handleIoException(e, errorCode); } catch (HttpDataSource.CleartextNotPermittedException e) { handleIoException(e, PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED); } catch (HttpDataSource.InvalidResponseCodeException e) { handleIoException(e, PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS); } catch (HttpDataSource.HttpDataSourceException | UdpDataSource.UdpDataSourceException e) { @ErrorCode int errorCode; @Nullable Throwable cause = e.getCause(); if (cause instanceof UnknownHostException) { errorCode = PlaybackException.ERROR_CODE_IO_DNS_FAILED; } else if (cause instanceof SocketTimeoutException) { errorCode = PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT; } else if (e instanceof HttpDataSource.HttpDataSourceException) { int type = ((HttpDataSource.HttpDataSourceException) e).type; errorCode = type == HttpDataSource.HttpDataSourceException.TYPE_OPEN ? PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED : PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_CLOSED; } else { errorCode = PlaybackException.ERROR_CODE_IO_UNSPECIFIED; } handleIoException(e, errorCode); } catch (BehindLiveWindowException e) { handleIoException(e, PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW); } catch (IOException e) { handleIoException(e, PlaybackException.ERROR_CODE_UNSPECIFIED); } catch (RuntimeException e) { ExoPlaybackException error = ExoPlaybackException.createForUnexpected(e); Log.e(TAG, "Playback error", error); stopInternal(/* forceResetRenderers= */ true, /* acknowledgeStop= */ false); playbackInfo = playbackInfo.copyWithPlaybackError(error); } maybeNotifyPlaybackInfoChanged(); return true; } // Private methods. private void handleIoException(IOException e, @ErrorCode int errorCode) { ExoPlaybackException error = ExoPlaybackException.createForSource(e, errorCode); @Nullable MediaPeriodHolder playingPeriod = queue.getPlayingPeriod(); if (playingPeriod != null) { // We ensure that all IOException throwing methods are only executed for the playing period. error = error.copyWithMediaPeriodId(playingPeriod.info.id); } Log.e(TAG, "Playback error", error); stopInternal(/* forceResetRenderers= */ false, /* acknowledgeStop= */ false); playbackInfo = playbackInfo.copyWithPlaybackError(error); } /** * Blocks the current thread until a condition becomes true or the specified amount of time has * elapsed. * * <p>If the current thread is interrupted while waiting for the condition to become true, this * method will restore the interrupt <b>after</b> the condition became true or the operation times * out. * * @param condition The condition. * @param timeoutMs The time in milliseconds to wait for the condition to become true. */ private synchronized void waitUninterruptibly(Supplier<Boolean> condition, long timeoutMs) { long deadlineMs = clock.elapsedRealtime() + timeoutMs; long remainingMs = timeoutMs; boolean wasInterrupted = false; while (!condition.get() && remainingMs > 0) { try { clock.onThreadBlocked(); wait(remainingMs); } catch (InterruptedException e) { wasInterrupted = true; } remainingMs = deadlineMs - clock.elapsedRealtime(); } if (wasInterrupted) { // Restore the interrupted status. Thread.currentThread().interrupt(); } } private void setState(int state) { if (playbackInfo.playbackState != state) { playbackInfo = playbackInfo.copyWithPlaybackState(state); } } private void maybeNotifyPlaybackInfoChanged() { playbackInfoUpdate.setPlaybackInfo(playbackInfo); if (playbackInfoUpdate.hasPendingChange) { playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate); playbackInfoUpdate = new PlaybackInfoUpdate(playbackInfo); } } private void prepareInternal() { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); resetInternal( /* resetRenderers= */ false, /* resetPosition= */ false, /* releaseMediaSourceList= */ false, /* resetError= */ true); loadControl.onPrepared(); setState(playbackInfo.timeline.isEmpty() ? Player.STATE_ENDED : Player.STATE_BUFFERING); mediaSourceList.prepare(bandwidthMeter.getTransferListener()); handler.sendEmptyMessage(MSG_DO_SOME_WORK); } private void setMediaItemsInternal(MediaSourceListUpdateMessage mediaSourceListUpdateMessage) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); if (mediaSourceListUpdateMessage.windowIndex != C.INDEX_UNSET) { pendingInitialSeekPosition = new SeekPosition( new PlaylistTimeline( mediaSourceListUpdateMessage.mediaSourceHolders, mediaSourceListUpdateMessage.shuffleOrder), mediaSourceListUpdateMessage.windowIndex, mediaSourceListUpdateMessage.positionUs); } Timeline timeline = mediaSourceList.setMediaSources( mediaSourceListUpdateMessage.mediaSourceHolders, mediaSourceListUpdateMessage.shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void addMediaItemsInternal(MediaSourceListUpdateMessage addMessage, int insertionIndex) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.addMediaSources( insertionIndex == C.INDEX_UNSET ? mediaSourceList.getSize() : insertionIndex, addMessage.mediaSourceHolders, addMessage.shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void moveMediaItemsInternal(MoveMediaItemsMessage moveMediaItemsMessage) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.moveMediaSourceRange( moveMediaItemsMessage.fromIndex, moveMediaItemsMessage.toIndex, moveMediaItemsMessage.newFromIndex, moveMediaItemsMessage.shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void removeMediaItemsInternal(int fromIndex, int toIndex, ShuffleOrder shuffleOrder) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.removeMediaSourceRange(fromIndex, toIndex, shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void mediaSourceListUpdateRequestedInternal() throws ExoPlaybackException { handleMediaSourceListInfoRefreshed( mediaSourceList.createTimeline(), /* isSourceRefresh= */ true); } private void setShuffleOrderInternal(ShuffleOrder shuffleOrder) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.setShuffleOrder(shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void notifyTrackSelectionPlayWhenReadyChanged(boolean playWhenReady) { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onPlayWhenReadyChanged(playWhenReady); } } periodHolder = periodHolder.getNext(); } } private void setPlayWhenReadyInternal( boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason, boolean operationAck, @Player.PlayWhenReadyChangeReason int reason) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(operationAck ? 1 : 0); playbackInfoUpdate.setPlayWhenReadyChangeReason(reason); playbackInfo = playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason); isRebuffering = false; notifyTrackSelectionPlayWhenReadyChanged(playWhenReady); if (!shouldPlayWhenReady()) { stopRenderers(); updatePlaybackPositions(); } else { if (playbackInfo.playbackState == Player.STATE_READY) { startRenderers(); handler.sendEmptyMessage(MSG_DO_SOME_WORK); } else if (playbackInfo.playbackState == Player.STATE_BUFFERING) { handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } } private void setPauseAtEndOfWindowInternal(boolean pauseAtEndOfWindow) throws ExoPlaybackException { this.pauseAtEndOfWindow = pauseAtEndOfWindow; resetPendingPauseAtEndOfPeriod(); if (pendingPauseAtEndOfPeriod && queue.getReadingPeriod() != queue.getPlayingPeriod()) { // When pausing is required, we need to set the streams of the playing period final. If we // already started reading the next period, we need to flush the renderers. seekToCurrentPosition(/* sendDiscontinuity= */ true); handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } } private void setOffloadSchedulingEnabledInternal(boolean offloadSchedulingEnabled) { if (offloadSchedulingEnabled == this.offloadSchedulingEnabled) { return; } this.offloadSchedulingEnabled = offloadSchedulingEnabled; @Player.State int state = playbackInfo.playbackState; if (offloadSchedulingEnabled || state == Player.STATE_ENDED || state == Player.STATE_IDLE) { playbackInfo = playbackInfo.copyWithOffloadSchedulingEnabled(offloadSchedulingEnabled); } else { handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } private void setRepeatModeInternal(@Player.RepeatMode int repeatMode) throws ExoPlaybackException { this.repeatMode = repeatMode; if (!queue.updateRepeatMode(playbackInfo.timeline, repeatMode)) { seekToCurrentPosition(/* sendDiscontinuity= */ true); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } private void setShuffleModeEnabledInternal(boolean shuffleModeEnabled) throws ExoPlaybackException { this.shuffleModeEnabled = shuffleModeEnabled; if (!queue.updateShuffleModeEnabled(playbackInfo.timeline, shuffleModeEnabled)) { seekToCurrentPosition(/* sendDiscontinuity= */ true); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } private void seekToCurrentPosition(boolean sendDiscontinuity) throws ExoPlaybackException { // Renderers may have read from a period that's been removed. Seek back to the current // position of the playing period to make sure none of the removed period is played. MediaPeriodId periodId = queue.getPlayingPeriod().info.id; long newPositionUs = seekToPeriodPosition( periodId, playbackInfo.positionUs, /* forceDisableRenderers= */ true, /* forceBufferingState= */ false); if (newPositionUs != playbackInfo.positionUs) { playbackInfo = handlePositionDiscontinuity( periodId, newPositionUs, playbackInfo.requestedContentPositionUs, playbackInfo.discontinuityStartPositionUs, sendDiscontinuity, Player.DISCONTINUITY_REASON_INTERNAL); } } private void startRenderers() throws ExoPlaybackException { isRebuffering = false; mediaClock.start(); for (Renderer renderer : renderers) { if (isRendererEnabled(renderer)) { renderer.start(); } } } private void stopRenderers() throws ExoPlaybackException { mediaClock.stop(); for (Renderer renderer : renderers) { if (isRendererEnabled(renderer)) { ensureStopped(renderer); } } } private void attemptRendererErrorRecovery() throws ExoPlaybackException { seekToCurrentPosition(/* sendDiscontinuity= */ true); } private void updatePlaybackPositions() throws ExoPlaybackException { MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder == null) { return; } // Update the playback position. long discontinuityPositionUs = playingPeriodHolder.prepared ? playingPeriodHolder.mediaPeriod.readDiscontinuity() : C.TIME_UNSET; if (discontinuityPositionUs != C.TIME_UNSET) { resetRendererPosition(discontinuityPositionUs); // A MediaPeriod may report a discontinuity at the current playback position to ensure the // renderers are flushed. Only report the discontinuity externally if the position changed. if (discontinuityPositionUs != playbackInfo.positionUs) { playbackInfo = handlePositionDiscontinuity( playbackInfo.periodId, /* positionUs= */ discontinuityPositionUs, playbackInfo.requestedContentPositionUs, /* discontinuityStartPositionUs= */ discontinuityPositionUs, /* reportDiscontinuity= */ true, Player.DISCONTINUITY_REASON_INTERNAL); } } else { rendererPositionUs = mediaClock.syncAndGetPositionUs( /* isReadingAhead= */ playingPeriodHolder != queue.getReadingPeriod()); long periodPositionUs = playingPeriodHolder.toPeriodTime(rendererPositionUs); maybeTriggerPendingMessages(playbackInfo.positionUs, periodPositionUs); playbackInfo.positionUs = periodPositionUs; } // Update the buffered position and total buffered duration. MediaPeriodHolder loadingPeriod = queue.getLoadingPeriod(); playbackInfo.bufferedPositionUs = loadingPeriod.getBufferedPositionUs(); playbackInfo.totalBufferedDurationUs = getTotalBufferedDurationUs(); // Adjust live playback speed to new position. if (playbackInfo.playWhenReady && playbackInfo.playbackState == Player.STATE_READY && shouldUseLivePlaybackSpeedControl(playbackInfo.timeline, playbackInfo.periodId) && playbackInfo.playbackParameters.speed == 1f) { float adjustedSpeed = livePlaybackSpeedControl.getAdjustedPlaybackSpeed( getCurrentLiveOffsetUs(), getTotalBufferedDurationUs()); if (mediaClock.getPlaybackParameters().speed != adjustedSpeed) { mediaClock.setPlaybackParameters(playbackInfo.playbackParameters.withSpeed(adjustedSpeed)); handlePlaybackParameters( playbackInfo.playbackParameters, /* currentPlaybackSpeed= */ mediaClock.getPlaybackParameters().speed, /* updatePlaybackInfo= */ false, /* acknowledgeCommand= */ false); } } } private void notifyTrackSelectionRebuffer() { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onRebuffer(); } } periodHolder = periodHolder.getNext(); } } private void doSomeWork() throws ExoPlaybackException, IOException { long operationStartTimeMs = clock.uptimeMillis(); updatePeriods(); if (playbackInfo.playbackState == Player.STATE_IDLE || playbackInfo.playbackState == Player.STATE_ENDED) { // Remove all messages. Prepare (in case of IDLE) or seek (in case of ENDED) will resume. handler.removeMessages(MSG_DO_SOME_WORK); return; } @Nullable MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder == null) { // We're still waiting until the playing period is available. scheduleNextWork(operationStartTimeMs, ACTIVE_INTERVAL_MS); return; } TraceUtil.beginSection("doSomeWork"); updatePlaybackPositions(); boolean renderersEnded = true; boolean renderersAllowPlayback = true; if (playingPeriodHolder.prepared) { long rendererPositionElapsedRealtimeUs = SystemClock.elapsedRealtime() * 1000; playingPeriodHolder.mediaPeriod.discardBuffer( playbackInfo.positionUs - backBufferDurationUs, retainBackBufferFromKeyframe); for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; if (!isRendererEnabled(renderer)) { continue; } // TODO: Each renderer should return the maximum delay before which it wishes to be called // again. The minimum of these values should then be used as the delay before the next // invocation of this method. renderer.render(rendererPositionUs, rendererPositionElapsedRealtimeUs); renderersEnded = renderersEnded && renderer.isEnded(); // Determine whether the renderer allows playback to continue. Playback can continue if the // renderer is ready or ended. Also continue playback if the renderer is reading ahead into // the next stream or is waiting for the next stream. This is to avoid getting stuck if // tracks in the current period have uneven durations and are still being read by another // renderer. See: https://github.com/google/ExoPlayer/issues/1874. boolean isReadingAhead = playingPeriodHolder.sampleStreams[i] != renderer.getStream(); boolean isWaitingForNextStream = !isReadingAhead && renderer.hasReadStreamToEnd(); boolean allowsPlayback = isReadingAhead || isWaitingForNextStream || renderer.isReady() || renderer.isEnded(); renderersAllowPlayback = renderersAllowPlayback && allowsPlayback; if (!allowsPlayback) { renderer.maybeThrowStreamError(); } } } else { playingPeriodHolder.mediaPeriod.maybeThrowPrepareError(); } long playingPeriodDurationUs = playingPeriodHolder.info.durationUs; boolean finishedRendering = renderersEnded && playingPeriodHolder.prepared && (playingPeriodDurationUs == C.TIME_UNSET || playingPeriodDurationUs <= playbackInfo.positionUs); if (finishedRendering && pendingPauseAtEndOfPeriod) { pendingPauseAtEndOfPeriod = false; setPlayWhenReadyInternal( /* playWhenReady= */ false, playbackInfo.playbackSuppressionReason, /* operationAck= */ false, Player.PLAY_WHEN_READY_CHANGE_REASON_END_OF_MEDIA_ITEM); } if (finishedRendering && playingPeriodHolder.info.isFinal) { setState(Player.STATE_ENDED); stopRenderers(); } else if (playbackInfo.playbackState == Player.STATE_BUFFERING && shouldTransitionToReadyState(renderersAllowPlayback)) { setState(Player.STATE_READY); pendingRecoverableRendererError = null; // Any pending error was successfully recovered from. if (shouldPlayWhenReady()) { startRenderers(); } } else if (playbackInfo.playbackState == Player.STATE_READY && !(enabledRendererCount == 0 ? isTimelineReady() : renderersAllowPlayback)) { isRebuffering = shouldPlayWhenReady(); setState(Player.STATE_BUFFERING); if (isRebuffering) { notifyTrackSelectionRebuffer(); livePlaybackSpeedControl.notifyRebuffer(); } stopRenderers(); } if (playbackInfo.playbackState == Player.STATE_BUFFERING) { for (int i = 0; i < renderers.length; i++) { if (isRendererEnabled(renderers[i]) && renderers[i].getStream() == playingPeriodHolder.sampleStreams[i]) { renderers[i].maybeThrowStreamError(); } } if (!playbackInfo.isLoading && playbackInfo.totalBufferedDurationUs < 500_000 && isLoadingPossible()) { // Throw if the LoadControl prevents loading even if the buffer is empty or almost empty. We // can't compare against 0 to account for small differences between the renderer position // and buffered position in the media at the point where playback gets stuck. throw new IllegalStateException("Playback stuck buffering and not loading"); } } if (offloadSchedulingEnabled != playbackInfo.offloadSchedulingEnabled) { playbackInfo = playbackInfo.copyWithOffloadSchedulingEnabled(offloadSchedulingEnabled); } boolean sleepingForOffload = false; if ((shouldPlayWhenReady() && playbackInfo.playbackState == Player.STATE_READY) || playbackInfo.playbackState == Player.STATE_BUFFERING) { sleepingForOffload = !maybeScheduleWakeup(operationStartTimeMs, ACTIVE_INTERVAL_MS); } else if (enabledRendererCount != 0 && playbackInfo.playbackState != Player.STATE_ENDED) { scheduleNextWork(operationStartTimeMs, IDLE_INTERVAL_MS); } else { handler.removeMessages(MSG_DO_SOME_WORK); } if (playbackInfo.sleepingForOffload != sleepingForOffload) { playbackInfo = playbackInfo.copyWithSleepingForOffload(sleepingForOffload); } requestForRendererSleep = false; // A sleep request is only valid for the current doSomeWork. TraceUtil.endSection(); } private long getCurrentLiveOffsetUs() { return getLiveOffsetUs( playbackInfo.timeline, playbackInfo.periodId.periodUid, playbackInfo.positionUs); } private long getLiveOffsetUs(Timeline timeline, Object periodUid, long periodPositionUs) { int windowIndex = timeline.getPeriodByUid(periodUid, period).windowIndex; timeline.getWindow(windowIndex, window); if (window.windowStartTimeMs == C.TIME_UNSET || !window.isLive() || !window.isDynamic) { return C.TIME_UNSET; } return C.msToUs(window.getCurrentUnixTimeMs() - window.windowStartTimeMs) - (periodPositionUs + period.getPositionInWindowUs()); } private boolean shouldUseLivePlaybackSpeedControl( Timeline timeline, MediaPeriodId mediaPeriodId) { if (mediaPeriodId.isAd() || timeline.isEmpty()) { return false; } int windowIndex = timeline.getPeriodByUid(mediaPeriodId.periodUid, period).windowIndex; timeline.getWindow(windowIndex, window); return window.isLive() && window.isDynamic && window.windowStartTimeMs != C.TIME_UNSET; } private void scheduleNextWork(long thisOperationStartTimeMs, long intervalMs) { handler.removeMessages(MSG_DO_SOME_WORK); handler.sendEmptyMessageAtTime(MSG_DO_SOME_WORK, thisOperationStartTimeMs + intervalMs); } private boolean maybeScheduleWakeup(long operationStartTimeMs, long intervalMs) { if (offloadSchedulingEnabled && requestForRendererSleep) { return false; } scheduleNextWork(operationStartTimeMs, intervalMs); return true; } private void seekToInternal(SeekPosition seekPosition) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); MediaPeriodId periodId; long periodPositionUs; long requestedContentPositionUs; boolean seekPositionAdjusted; @Nullable Pair<Object, Long> resolvedSeekPosition = resolveSeekPosition( playbackInfo.timeline, seekPosition, /* trySubsequentPeriods= */ true, repeatMode, shuffleModeEnabled, window, period); if (resolvedSeekPosition == null) { // The seek position was valid for the timeline that it was performed into, but the // timeline has changed or is not ready and a suitable seek position could not be resolved. Pair<MediaPeriodId, Long> firstPeriodAndPosition = getPlaceholderFirstMediaPeriodPosition(playbackInfo.timeline); periodId = firstPeriodAndPosition.first; periodPositionUs = firstPeriodAndPosition.second; requestedContentPositionUs = C.TIME_UNSET; seekPositionAdjusted = !playbackInfo.timeline.isEmpty(); } else { // Update the resolved seek position to take ads into account. Object periodUid = resolvedSeekPosition.first; long resolvedContentPositionUs = resolvedSeekPosition.second; requestedContentPositionUs = seekPosition.windowPositionUs == C.TIME_UNSET ? C.TIME_UNSET : resolvedContentPositionUs; periodId = queue.resolveMediaPeriodIdForAds( playbackInfo.timeline, periodUid, resolvedContentPositionUs); if (periodId.isAd()) { playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period); periodPositionUs = period.getFirstAdIndexToPlay(periodId.adGroupIndex) == periodId.adIndexInAdGroup ? period.getAdResumePositionUs() : 0; seekPositionAdjusted = true; } else { periodPositionUs = resolvedContentPositionUs; seekPositionAdjusted = seekPosition.windowPositionUs == C.TIME_UNSET; } } try { if (playbackInfo.timeline.isEmpty()) { // Save seek position for later, as we are still waiting for a prepared source. pendingInitialSeekPosition = seekPosition; } else if (resolvedSeekPosition == null) { // End playback, as we didn't manage to find a valid seek position. if (playbackInfo.playbackState != Player.STATE_IDLE) { setState(Player.STATE_ENDED); } resetInternal( /* resetRenderers= */ false, /* resetPosition= */ true, /* releaseMediaSourceList= */ false, /* resetError= */ true); } else { // Execute the seek in the current media periods. long newPeriodPositionUs = periodPositionUs; if (periodId.equals(playbackInfo.periodId)) { MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder != null && playingPeriodHolder.prepared && newPeriodPositionUs != 0) { newPeriodPositionUs = playingPeriodHolder.mediaPeriod.getAdjustedSeekPositionUs( newPeriodPositionUs, seekParameters); } if (C.usToMs(newPeriodPositionUs) == C.usToMs(playbackInfo.positionUs) && (playbackInfo.playbackState == Player.STATE_BUFFERING || playbackInfo.playbackState == Player.STATE_READY)) { // Seek will be performed to the current position. Do nothing. periodPositionUs = playbackInfo.positionUs; return; } } newPeriodPositionUs = seekToPeriodPosition( periodId, newPeriodPositionUs, /* forceBufferingState= */ playbackInfo.playbackState == Player.STATE_ENDED); seekPositionAdjusted |= periodPositionUs != newPeriodPositionUs; periodPositionUs = newPeriodPositionUs; updateLivePlaybackSpeedControl( /* newTimeline= */ playbackInfo.timeline, /* newPeriodId= */ periodId, /* oldTimeline= */ playbackInfo.timeline, /* oldPeriodId= */ playbackInfo.periodId, /* positionForTargetOffsetOverrideUs= */ requestedContentPositionUs); } } finally { playbackInfo = handlePositionDiscontinuity( periodId, periodPositionUs, requestedContentPositionUs, /* discontinuityStartPositionUs= */ periodPositionUs, /* reportDiscontinuity= */ seekPositionAdjusted, Player.DISCONTINUITY_REASON_SEEK_ADJUSTMENT); } } private long seekToPeriodPosition( MediaPeriodId periodId, long periodPositionUs, boolean forceBufferingState) throws ExoPlaybackException { // Force disable renderers if they are reading from a period other than the one being played. return seekToPeriodPosition( periodId, periodPositionUs, queue.getPlayingPeriod() != queue.getReadingPeriod(), forceBufferingState); } private long seekToPeriodPosition( MediaPeriodId periodId, long periodPositionUs, boolean forceDisableRenderers, boolean forceBufferingState) throws ExoPlaybackException { stopRenderers(); isRebuffering = false; if (forceBufferingState || playbackInfo.playbackState == Player.STATE_READY) { setState(Player.STATE_BUFFERING); } // Find the requested period if it already exists. @Nullable MediaPeriodHolder oldPlayingPeriodHolder = queue.getPlayingPeriod(); @Nullable MediaPeriodHolder newPlayingPeriodHolder = oldPlayingPeriodHolder; while (newPlayingPeriodHolder != null) { if (periodId.equals(newPlayingPeriodHolder.info.id)) { break; } newPlayingPeriodHolder = newPlayingPeriodHolder.getNext(); } // Disable all renderers if the period being played is changing, if the seek results in negative // renderer timestamps, or if forced. if (forceDisableRenderers || oldPlayingPeriodHolder != newPlayingPeriodHolder || (newPlayingPeriodHolder != null && newPlayingPeriodHolder.toRendererTime(periodPositionUs) < 0)) { for (Renderer renderer : renderers) { disableRenderer(renderer); } if (newPlayingPeriodHolder != null) { // Update the queue and reenable renderers if the requested media period already exists. while (queue.getPlayingPeriod() != newPlayingPeriodHolder) { queue.advancePlayingPeriod(); } queue.removeAfter(newPlayingPeriodHolder); newPlayingPeriodHolder.setRendererOffset(/* rendererPositionOffsetUs= */ 0); enableRenderers(); } } // Do the actual seeking. if (newPlayingPeriodHolder != null) { queue.removeAfter(newPlayingPeriodHolder); if (!newPlayingPeriodHolder.prepared) { newPlayingPeriodHolder.info = newPlayingPeriodHolder.info.copyWithStartPositionUs(periodPositionUs); } else { if (newPlayingPeriodHolder.info.durationUs != C.TIME_UNSET && periodPositionUs >= newPlayingPeriodHolder.info.durationUs) { // Make sure seek position doesn't exceed period duration. periodPositionUs = max(0, newPlayingPeriodHolder.info.durationUs - 1); } if (newPlayingPeriodHolder.hasEnabledTracks) { periodPositionUs = newPlayingPeriodHolder.mediaPeriod.seekToUs(periodPositionUs); newPlayingPeriodHolder.mediaPeriod.discardBuffer( periodPositionUs - backBufferDurationUs, retainBackBufferFromKeyframe); } } resetRendererPosition(periodPositionUs); maybeContinueLoading(); } else { // New period has not been prepared. queue.clear(); resetRendererPosition(periodPositionUs); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); handler.sendEmptyMessage(MSG_DO_SOME_WORK); return periodPositionUs; } private void resetRendererPosition(long periodPositionUs) throws ExoPlaybackException { MediaPeriodHolder playingMediaPeriod = queue.getPlayingPeriod(); rendererPositionUs = playingMediaPeriod == null ? periodPositionUs : playingMediaPeriod.toRendererTime(periodPositionUs); mediaClock.resetPosition(rendererPositionUs); for (Renderer renderer : renderers) { if (isRendererEnabled(renderer)) { renderer.resetPosition(rendererPositionUs); } } notifyTrackSelectionDiscontinuity(); } private void setPlaybackParametersInternal(PlaybackParameters playbackParameters) throws ExoPlaybackException { mediaClock.setPlaybackParameters(playbackParameters); handlePlaybackParameters(mediaClock.getPlaybackParameters(), /* acknowledgeCommand= */ true); } private void setSeekParametersInternal(SeekParameters seekParameters) { this.seekParameters = seekParameters; } private void setForegroundModeInternal( boolean foregroundMode, @Nullable AtomicBoolean processedFlag) { if (this.foregroundMode != foregroundMode) { this.foregroundMode = foregroundMode; if (!foregroundMode) { for (Renderer renderer : renderers) { if (!isRendererEnabled(renderer)) { renderer.reset(); } } } } if (processedFlag != null) { synchronized (this) { processedFlag.set(true); notifyAll(); } } } private void stopInternal(boolean forceResetRenderers, boolean acknowledgeStop) { resetInternal( /* resetRenderers= */ forceResetRenderers || !foregroundMode, /* resetPosition= */ false, /* releaseMediaSourceList= */ true, /* resetError= */ false); playbackInfoUpdate.incrementPendingOperationAcks(acknowledgeStop ? 1 : 0); loadControl.onStopped(); setState(Player.STATE_IDLE); } private void releaseInternal() { resetInternal( /* resetRenderers= */ true, /* resetPosition= */ false, /* releaseMediaSourceList= */ true, /* resetError= */ false); loadControl.onReleased(); setState(Player.STATE_IDLE); internalPlaybackThread.quit(); synchronized (this) { released = true; notifyAll(); } } private void resetInternal( boolean resetRenderers, boolean resetPosition, boolean releaseMediaSourceList, boolean resetError) { handler.removeMessages(MSG_DO_SOME_WORK); pendingRecoverableRendererError = null; isRebuffering = false; mediaClock.stop(); rendererPositionUs = 0; for (Renderer renderer : renderers) { try { disableRenderer(renderer); } catch (ExoPlaybackException | RuntimeException e) { // There's nothing we can do. Log.e(TAG, "Disable failed.", e); } } if (resetRenderers) { for (Renderer renderer : renderers) { try { renderer.reset(); } catch (RuntimeException e) { // There's nothing we can do. Log.e(TAG, "Reset failed.", e); } } } enabledRendererCount = 0; MediaPeriodId mediaPeriodId = playbackInfo.periodId; long startPositionUs = playbackInfo.positionUs; long requestedContentPositionUs = playbackInfo.periodId.isAd() || isUsingPlaceholderPeriod(playbackInfo, period) ? playbackInfo.requestedContentPositionUs : playbackInfo.positionUs; boolean resetTrackInfo = false; if (resetPosition) { pendingInitialSeekPosition = null; Pair<MediaPeriodId, Long> firstPeriodAndPosition = getPlaceholderFirstMediaPeriodPosition(playbackInfo.timeline); mediaPeriodId = firstPeriodAndPosition.first; startPositionUs = firstPeriodAndPosition.second; requestedContentPositionUs = C.TIME_UNSET; if (!mediaPeriodId.equals(playbackInfo.periodId)) { resetTrackInfo = true; } } queue.clear(); shouldContinueLoading = false; playbackInfo = new PlaybackInfo( playbackInfo.timeline, mediaPeriodId, requestedContentPositionUs, /* discontinuityStartPositionUs= */ startPositionUs, playbackInfo.playbackState, resetError ? null : playbackInfo.playbackError, /* isLoading= */ false, resetTrackInfo ? TrackGroupArray.EMPTY : playbackInfo.trackGroups, resetTrackInfo ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult, resetTrackInfo ? ImmutableList.of() : playbackInfo.staticMetadata, mediaPeriodId, playbackInfo.playWhenReady, playbackInfo.playbackSuppressionReason, playbackInfo.playbackParameters, /* bufferedPositionUs= */ startPositionUs, /* totalBufferedDurationUs= */ 0, /* positionUs= */ startPositionUs, offloadSchedulingEnabled, /* sleepingForOffload= */ false); if (releaseMediaSourceList) { mediaSourceList.release(); } } private Pair<MediaPeriodId, Long> getPlaceholderFirstMediaPeriodPosition(Timeline timeline) { if (timeline.isEmpty()) { return Pair.create(PlaybackInfo.getDummyPeriodForEmptyTimeline(), 0L); } int firstWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); Pair<Object, Long> firstPeriodAndPosition = timeline.getPeriodPosition( window, period, firstWindowIndex, /* windowPositionUs= */ C.TIME_UNSET); // Add ad metadata if any and propagate the window sequence number to new period id. MediaPeriodId firstPeriodId = queue.resolveMediaPeriodIdForAds( timeline, firstPeriodAndPosition.first, /* positionUs= */ 0); long positionUs = firstPeriodAndPosition.second; if (firstPeriodId.isAd()) { timeline.getPeriodByUid(firstPeriodId.periodUid, period); positionUs = firstPeriodId.adIndexInAdGroup == period.getFirstAdIndexToPlay(firstPeriodId.adGroupIndex) ? period.getAdResumePositionUs() : 0; } return Pair.create(firstPeriodId, positionUs); } private void sendMessageInternal(PlayerMessage message) throws ExoPlaybackException { if (message.getPositionMs() == C.TIME_UNSET) { // If no delivery time is specified, trigger immediate message delivery. sendMessageToTarget(message); } else if (playbackInfo.timeline.isEmpty()) { // Still waiting for initial timeline to resolve position. pendingMessages.add(new PendingMessageInfo(message)); } else { PendingMessageInfo pendingMessageInfo = new PendingMessageInfo(message); if (resolvePendingMessagePosition( pendingMessageInfo, /* newTimeline= */ playbackInfo.timeline, /* previousTimeline= */ playbackInfo.timeline, repeatMode, shuffleModeEnabled, window, period)) { pendingMessages.add(pendingMessageInfo); // Ensure new message is inserted according to playback order. Collections.sort(pendingMessages); } else { message.markAsProcessed(/* isDelivered= */ false); } } } private void sendMessageToTarget(PlayerMessage message) throws ExoPlaybackException { if (message.getLooper() == playbackLooper) { deliverMessage(message); if (playbackInfo.playbackState == Player.STATE_READY || playbackInfo.playbackState == Player.STATE_BUFFERING) { // The message may have caused something to change that now requires us to do work. handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } else { handler.obtainMessage(MSG_SEND_MESSAGE_TO_TARGET_THREAD, message).sendToTarget(); } } private void sendMessageToTargetThread(final PlayerMessage message) { Looper looper = message.getLooper(); if (!looper.getThread().isAlive()) { Log.w("TAG", "Trying to send message on a dead thread."); message.markAsProcessed(/* isDelivered= */ false); return; } clock .createHandler(looper, /* callback= */ null) .post( () -> { try { deliverMessage(message); } catch (ExoPlaybackException e) { Log.e(TAG, "Unexpected error delivering message on external thread.", e); throw new RuntimeException(e); } }); } private void deliverMessage(PlayerMessage message) throws ExoPlaybackException { if (message.isCanceled()) { return; } try { message.getTarget().handleMessage(message.getType(), message.getPayload()); } finally { message.markAsProcessed(/* isDelivered= */ true); } } private void resolvePendingMessagePositions(Timeline newTimeline, Timeline previousTimeline) { if (newTimeline.isEmpty() && previousTimeline.isEmpty()) { // Keep all messages unresolved until we have a non-empty timeline. return; } for (int i = pendingMessages.size() - 1; i >= 0; i--) { if (!resolvePendingMessagePosition( pendingMessages.get(i), newTimeline, previousTimeline, repeatMode, shuffleModeEnabled, window, period)) { // Unable to resolve a new position for the message. Remove it. pendingMessages.get(i).message.markAsProcessed(/* isDelivered= */ false); pendingMessages.remove(i); } } // Re-sort messages by playback order. Collections.sort(pendingMessages); } private void maybeTriggerPendingMessages(long oldPeriodPositionUs, long newPeriodPositionUs) throws ExoPlaybackException { if (pendingMessages.isEmpty() || playbackInfo.periodId.isAd()) { return; } // If this is the first call after resetting the renderer position, include oldPeriodPositionUs // in potential trigger positions, but make sure we deliver it only once. if (deliverPendingMessageAtStartPositionRequired) { oldPeriodPositionUs--; deliverPendingMessageAtStartPositionRequired = false; } // Correct next index if necessary (e.g. after seeking, timeline changes, or new messages) int currentPeriodIndex = playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid); int nextPendingMessageIndex = min(nextPendingMessageIndexHint, pendingMessages.size()); PendingMessageInfo previousInfo = nextPendingMessageIndex > 0 ? pendingMessages.get(nextPendingMessageIndex - 1) : null; while (previousInfo != null && (previousInfo.resolvedPeriodIndex > currentPeriodIndex || (previousInfo.resolvedPeriodIndex == currentPeriodIndex && previousInfo.resolvedPeriodTimeUs > oldPeriodPositionUs))) { nextPendingMessageIndex--; previousInfo = nextPendingMessageIndex > 0 ? pendingMessages.get(nextPendingMessageIndex - 1) : null; } PendingMessageInfo nextInfo = nextPendingMessageIndex < pendingMessages.size() ? pendingMessages.get(nextPendingMessageIndex) : null; while (nextInfo != null && nextInfo.resolvedPeriodUid != null && (nextInfo.resolvedPeriodIndex < currentPeriodIndex || (nextInfo.resolvedPeriodIndex == currentPeriodIndex && nextInfo.resolvedPeriodTimeUs <= oldPeriodPositionUs))) { nextPendingMessageIndex++; nextInfo = nextPendingMessageIndex < pendingMessages.size() ? pendingMessages.get(nextPendingMessageIndex) : null; } // Check if any message falls within the covered time span. while (nextInfo != null && nextInfo.resolvedPeriodUid != null && nextInfo.resolvedPeriodIndex == currentPeriodIndex && nextInfo.resolvedPeriodTimeUs > oldPeriodPositionUs && nextInfo.resolvedPeriodTimeUs <= newPeriodPositionUs) { try { sendMessageToTarget(nextInfo.message); } finally { if (nextInfo.message.getDeleteAfterDelivery() || nextInfo.message.isCanceled()) { pendingMessages.remove(nextPendingMessageIndex); } else { nextPendingMessageIndex++; } } nextInfo = nextPendingMessageIndex < pendingMessages.size() ? pendingMessages.get(nextPendingMessageIndex) : null; } nextPendingMessageIndexHint = nextPendingMessageIndex; } private void ensureStopped(Renderer renderer) throws ExoPlaybackException { if (renderer.getState() == Renderer.STATE_STARTED) { renderer.stop(); } } private void disableRenderer(Renderer renderer) throws ExoPlaybackException { if (!isRendererEnabled(renderer)) { return; } mediaClock.onRendererDisabled(renderer); ensureStopped(renderer); renderer.disable(); enabledRendererCount--; } private void reselectTracksInternal() throws ExoPlaybackException { float playbackSpeed = mediaClock.getPlaybackParameters().speed; // Reselect tracks on each period in turn, until the selection changes. MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); boolean selectionsChangedForReadPeriod = true; TrackSelectorResult newTrackSelectorResult; while (true) { if (periodHolder == null || !periodHolder.prepared) { // The reselection did not change any prepared periods. return; } newTrackSelectorResult = periodHolder.selectTracks(playbackSpeed, playbackInfo.timeline); if (!newTrackSelectorResult.isEquivalent(periodHolder.getTrackSelectorResult())) { // Selected tracks have changed for this period. break; } if (periodHolder == readingPeriodHolder) { // The track reselection didn't affect any period that has been read. selectionsChangedForReadPeriod = false; } periodHolder = periodHolder.getNext(); } if (selectionsChangedForReadPeriod) { // Update streams and rebuffer for the new selection, recreating all streams if reading ahead. MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); boolean recreateStreams = queue.removeAfter(playingPeriodHolder); boolean[] streamResetFlags = new boolean[renderers.length]; long periodPositionUs = playingPeriodHolder.applyTrackSelection( newTrackSelectorResult, playbackInfo.positionUs, recreateStreams, streamResetFlags); boolean hasDiscontinuity = playbackInfo.playbackState != Player.STATE_ENDED && periodPositionUs != playbackInfo.positionUs; playbackInfo = handlePositionDiscontinuity( playbackInfo.periodId, periodPositionUs, playbackInfo.requestedContentPositionUs, playbackInfo.discontinuityStartPositionUs, hasDiscontinuity, Player.DISCONTINUITY_REASON_INTERNAL); if (hasDiscontinuity) { resetRendererPosition(periodPositionUs); } boolean[] rendererWasEnabledFlags = new boolean[renderers.length]; for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; rendererWasEnabledFlags[i] = isRendererEnabled(renderer); SampleStream sampleStream = playingPeriodHolder.sampleStreams[i]; if (rendererWasEnabledFlags[i]) { if (sampleStream != renderer.getStream()) { // We need to disable the renderer. disableRenderer(renderer); } else if (streamResetFlags[i]) { // The renderer will continue to consume from its current stream, but needs to be reset. renderer.resetPosition(rendererPositionUs); } } } enableRenderers(rendererWasEnabledFlags); } else { // Release and re-prepare/buffer periods after the one whose selection changed. queue.removeAfter(periodHolder); if (periodHolder.prepared) { long loadingPeriodPositionUs = max(periodHolder.info.startPositionUs, periodHolder.toPeriodTime(rendererPositionUs)); periodHolder.applyTrackSelection(newTrackSelectorResult, loadingPeriodPositionUs, false); } } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ true); if (playbackInfo.playbackState != Player.STATE_ENDED) { maybeContinueLoading(); updatePlaybackPositions(); handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } private void updateTrackSelectionPlaybackSpeed(float playbackSpeed) { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onPlaybackSpeed(playbackSpeed); } } periodHolder = periodHolder.getNext(); } } private void notifyTrackSelectionDiscontinuity() { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onDiscontinuity(); } } periodHolder = periodHolder.getNext(); } } private boolean shouldTransitionToReadyState(boolean renderersReadyOrEnded) { if (enabledRendererCount == 0) { // If there are no enabled renderers, determine whether we're ready based on the timeline. return isTimelineReady(); } if (!renderersReadyOrEnded) { return false; } if (!playbackInfo.isLoading) { // Renderers are ready and we're not loading. Transition to ready, since the alternative is // getting stuck waiting for additional media that's not being loaded. return true; } // Renderers are ready and we're loading. Ask the LoadControl whether to transition. long targetLiveOffsetUs = shouldUseLivePlaybackSpeedControl(playbackInfo.timeline, queue.getPlayingPeriod().info.id) ? livePlaybackSpeedControl.getTargetLiveOffsetUs() : C.TIME_UNSET; MediaPeriodHolder loadingHolder = queue.getLoadingPeriod(); boolean isBufferedToEnd = loadingHolder.isFullyBuffered() && loadingHolder.info.isFinal; // Ad loader implementations may only load ad media once playback has nearly reached the ad, but // it is possible for playback to be stuck buffering waiting for this. Therefore, we start // playback regardless of buffered duration if we are waiting for an ad media period to prepare. boolean isAdPendingPreparation = loadingHolder.info.id.isAd() && !loadingHolder.prepared; return isBufferedToEnd || isAdPendingPreparation || loadControl.shouldStartPlayback( getTotalBufferedDurationUs(), mediaClock.getPlaybackParameters().speed, isRebuffering, targetLiveOffsetUs); } private boolean isTimelineReady() { MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); long playingPeriodDurationUs = playingPeriodHolder.info.durationUs; return playingPeriodHolder.prepared && (playingPeriodDurationUs == C.TIME_UNSET || playbackInfo.positionUs < playingPeriodDurationUs || !shouldPlayWhenReady()); } private void handleMediaSourceListInfoRefreshed(Timeline timeline, boolean isSourceRefresh) throws ExoPlaybackException { PositionUpdateForPlaylistChange positionUpdate = resolvePositionForPlaylistChange( timeline, playbackInfo, pendingInitialSeekPosition, queue, repeatMode, shuffleModeEnabled, window, period); MediaPeriodId newPeriodId = positionUpdate.periodId; long newRequestedContentPositionUs = positionUpdate.requestedContentPositionUs; boolean forceBufferingState = positionUpdate.forceBufferingState; long newPositionUs = positionUpdate.periodPositionUs; boolean periodPositionChanged = !playbackInfo.periodId.equals(newPeriodId) || newPositionUs != playbackInfo.positionUs; try { if (positionUpdate.endPlayback) { if (playbackInfo.playbackState != Player.STATE_IDLE) { setState(Player.STATE_ENDED); } resetInternal( /* resetRenderers= */ false, /* resetPosition= */ false, /* releaseMediaSourceList= */ false, /* resetError= */ true); } if (!periodPositionChanged) { // We can keep the current playing period. Update the rest of the queued periods. if (!queue.updateQueuedPeriods( timeline, rendererPositionUs, getMaxRendererReadPositionUs())) { seekToCurrentPosition(/* sendDiscontinuity= */ false); } } else if (!timeline.isEmpty()) { // Something changed. Seek to new start position. @Nullable MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { // Update the new playing media period info if it already exists. if (periodHolder.info.id.equals(newPeriodId)) { periodHolder.info = queue.getUpdatedMediaPeriodInfo(timeline, periodHolder.info); periodHolder.updateClipping(); } periodHolder = periodHolder.getNext(); } newPositionUs = seekToPeriodPosition(newPeriodId, newPositionUs, forceBufferingState); } } finally { updateLivePlaybackSpeedControl( /* newTimeline= */ timeline, newPeriodId, /* oldTimeline= */ playbackInfo.timeline, /* oldPeriodId= */ playbackInfo.periodId, /* positionForTargetOffsetOverrideUs */ positionUpdate.setTargetLiveOffset ? newPositionUs : C.TIME_UNSET); if (periodPositionChanged || newRequestedContentPositionUs != playbackInfo.requestedContentPositionUs) { Object oldPeriodUid = playbackInfo.periodId.periodUid; Timeline oldTimeline = playbackInfo.timeline; boolean reportDiscontinuity = periodPositionChanged && isSourceRefresh && !oldTimeline.isEmpty() && !oldTimeline.getPeriodByUid(oldPeriodUid, period).isPlaceholder; playbackInfo = handlePositionDiscontinuity( newPeriodId, newPositionUs, newRequestedContentPositionUs, playbackInfo.discontinuityStartPositionUs, reportDiscontinuity, timeline.getIndexOfPeriod(oldPeriodUid) == C.INDEX_UNSET ? Player.DISCONTINUITY_REASON_REMOVE : Player.DISCONTINUITY_REASON_SKIP); } resetPendingPauseAtEndOfPeriod(); resolvePendingMessagePositions( /* newTimeline= */ timeline, /* previousTimeline= */ playbackInfo.timeline); playbackInfo = playbackInfo.copyWithTimeline(timeline); if (!timeline.isEmpty()) { // Retain pending seek position only while the timeline is still empty. pendingInitialSeekPosition = null; } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } } private void updateLivePlaybackSpeedControl( Timeline newTimeline, MediaPeriodId newPeriodId, Timeline oldTimeline, MediaPeriodId oldPeriodId, long positionForTargetOffsetOverrideUs) { if (newTimeline.isEmpty() || !shouldUseLivePlaybackSpeedControl(newTimeline, newPeriodId)) { // Live playback speed control is unused for the current period, reset speed if adjusted. if (mediaClock.getPlaybackParameters().speed != playbackInfo.playbackParameters.speed) { mediaClock.setPlaybackParameters(playbackInfo.playbackParameters); } return; } int windowIndex = newTimeline.getPeriodByUid(newPeriodId.periodUid, period).windowIndex; newTimeline.getWindow(windowIndex, window); livePlaybackSpeedControl.setLiveConfiguration(castNonNull(window.liveConfiguration)); if (positionForTargetOffsetOverrideUs != C.TIME_UNSET) { livePlaybackSpeedControl.setTargetLiveOffsetOverrideUs( getLiveOffsetUs(newTimeline, newPeriodId.periodUid, positionForTargetOffsetOverrideUs)); } else { Object windowUid = window.uid; @Nullable Object oldWindowUid = null; if (!oldTimeline.isEmpty()) { int oldWindowIndex = oldTimeline.getPeriodByUid(oldPeriodId.periodUid, period).windowIndex; oldWindowUid = oldTimeline.getWindow(oldWindowIndex, window).uid; } if (!Util.areEqual(oldWindowUid, windowUid)) { // Reset overridden target live offset to media values if window changes. livePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(C.TIME_UNSET); } } } private long getMaxRendererReadPositionUs() { MediaPeriodHolder readingHolder = queue.getReadingPeriod(); if (readingHolder == null) { return 0; } long maxReadPositionUs = readingHolder.getRendererOffset(); if (!readingHolder.prepared) { return maxReadPositionUs; } for (int i = 0; i < renderers.length; i++) { if (!isRendererEnabled(renderers[i]) || renderers[i].getStream() != readingHolder.sampleStreams[i]) { // Ignore disabled renderers and renderers with sample streams from previous periods. continue; } long readingPositionUs = renderers[i].getReadingPositionUs(); if (readingPositionUs == C.TIME_END_OF_SOURCE) { return C.TIME_END_OF_SOURCE; } else { maxReadPositionUs = max(readingPositionUs, maxReadPositionUs); } } return maxReadPositionUs; } private void updatePeriods() throws ExoPlaybackException, IOException { if (playbackInfo.timeline.isEmpty() || !mediaSourceList.isPrepared()) { // No periods available. return; } maybeUpdateLoadingPeriod(); maybeUpdateReadingPeriod(); maybeUpdateReadingRenderers(); maybeUpdatePlayingPeriod(); } private void maybeUpdateLoadingPeriod() throws ExoPlaybackException { queue.reevaluateBuffer(rendererPositionUs); if (queue.shouldLoadNextMediaPeriod()) { @Nullable MediaPeriodInfo info = queue.getNextMediaPeriodInfo(rendererPositionUs, playbackInfo); if (info != null) { MediaPeriodHolder mediaPeriodHolder = queue.enqueueNextMediaPeriodHolder( rendererCapabilities, trackSelector, loadControl.getAllocator(), mediaSourceList, info, emptyTrackSelectorResult); mediaPeriodHolder.mediaPeriod.prepare(this, info.startPositionUs); if (queue.getPlayingPeriod() == mediaPeriodHolder) { resetRendererPosition(mediaPeriodHolder.getStartPositionRendererTime()); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } } if (shouldContinueLoading) { // We should still be loading, except when there is nothing to load or we have fully loaded // the current period. shouldContinueLoading = isLoadingPossible(); updateIsLoading(); } else { maybeContinueLoading(); } } private void maybeUpdateReadingPeriod() { @Nullable MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); if (readingPeriodHolder == null) { return; } if (readingPeriodHolder.getNext() == null || pendingPauseAtEndOfPeriod) { // We don't have a successor to advance the reading period to or we want to let them end // intentionally to pause at the end of the period. if (readingPeriodHolder.info.isFinal || pendingPauseAtEndOfPeriod) { for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; SampleStream sampleStream = readingPeriodHolder.sampleStreams[i]; // Defer setting the stream as final until the renderer has actually consumed the whole // stream in case of playlist changes that cause the stream to be no longer final. if (sampleStream != null && renderer.getStream() == sampleStream && renderer.hasReadStreamToEnd()) { long streamEndPositionUs = readingPeriodHolder.info.durationUs != C.TIME_UNSET && readingPeriodHolder.info.durationUs != C.TIME_END_OF_SOURCE ? readingPeriodHolder.getRendererOffset() + readingPeriodHolder.info.durationUs : C.TIME_UNSET; setCurrentStreamFinal(renderer, streamEndPositionUs); } } } return; } if (!hasReadingPeriodFinishedReading()) { return; } if (!readingPeriodHolder.getNext().prepared && rendererPositionUs < readingPeriodHolder.getNext().getStartPositionRendererTime()) { // The successor is not prepared yet and playback hasn't reached the transition point. return; } TrackSelectorResult oldTrackSelectorResult = readingPeriodHolder.getTrackSelectorResult(); readingPeriodHolder = queue.advanceReadingPeriod(); TrackSelectorResult newTrackSelectorResult = readingPeriodHolder.getTrackSelectorResult(); if (readingPeriodHolder.prepared && readingPeriodHolder.mediaPeriod.readDiscontinuity() != C.TIME_UNSET) { // The new period starts with a discontinuity, so the renderers will play out all data, then // be disabled and re-enabled when they start playing the next period. setAllRendererStreamsFinal( /* streamEndPositionUs= */ readingPeriodHolder.getStartPositionRendererTime()); return; } for (int i = 0; i < renderers.length; i++) { boolean oldRendererEnabled = oldTrackSelectorResult.isRendererEnabled(i); boolean newRendererEnabled = newTrackSelectorResult.isRendererEnabled(i); if (oldRendererEnabled && !renderers[i].isCurrentStreamFinal()) { boolean isNoSampleRenderer = rendererCapabilities[i].getTrackType() == C.TRACK_TYPE_NONE; RendererConfiguration oldConfig = oldTrackSelectorResult.rendererConfigurations[i]; RendererConfiguration newConfig = newTrackSelectorResult.rendererConfigurations[i]; if (!newRendererEnabled || !newConfig.equals(oldConfig) || isNoSampleRenderer) { // The renderer will be disabled when transitioning to playing the next period, because // there's no new selection, or because a configuration change is required, or because // it's a no-sample renderer for which rendererOffsetUs should be updated only when // starting to play the next period. Mark the SampleStream as final to play out any // remaining data. setCurrentStreamFinal( renderers[i], /* streamEndPositionUs= */ readingPeriodHolder.getStartPositionRendererTime()); } } } } private void maybeUpdateReadingRenderers() throws ExoPlaybackException { @Nullable MediaPeriodHolder readingPeriod = queue.getReadingPeriod(); if (readingPeriod == null || queue.getPlayingPeriod() == readingPeriod || readingPeriod.allRenderersInCorrectState) { // Not reading ahead or all renderers updated. return; } if (replaceStreamsOrDisableRendererForTransition()) { enableRenderers(); } } private boolean replaceStreamsOrDisableRendererForTransition() throws ExoPlaybackException { MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); TrackSelectorResult newTrackSelectorResult = readingPeriodHolder.getTrackSelectorResult(); boolean needsToWaitForRendererToEnd = false; for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; if (!isRendererEnabled(renderer)) { continue; } boolean rendererIsReadingOldStream = renderer.getStream() != readingPeriodHolder.sampleStreams[i]; boolean rendererShouldBeEnabled = newTrackSelectorResult.isRendererEnabled(i); if (rendererShouldBeEnabled && !rendererIsReadingOldStream) { // All done. continue; } if (!renderer.isCurrentStreamFinal()) { // The renderer stream is not final, so we can replace the sample streams immediately. Format[] formats = getFormats(newTrackSelectorResult.selections[i]); renderer.replaceStream( formats, readingPeriodHolder.sampleStreams[i], readingPeriodHolder.getStartPositionRendererTime(), readingPeriodHolder.getRendererOffset()); } else if (renderer.isEnded()) { // The renderer has finished playback, so we can disable it now. disableRenderer(renderer); } else { // We need to wait until rendering finished before disabling the renderer. needsToWaitForRendererToEnd = true; } } return !needsToWaitForRendererToEnd; } private void maybeUpdatePlayingPeriod() throws ExoPlaybackException { boolean advancedPlayingPeriod = false; while (shouldAdvancePlayingPeriod()) { if (advancedPlayingPeriod) { // If we advance more than one period at a time, notify listeners after each update. maybeNotifyPlaybackInfoChanged(); } MediaPeriodHolder oldPlayingPeriodHolder = queue.getPlayingPeriod(); MediaPeriodHolder newPlayingPeriodHolder = queue.advancePlayingPeriod(); playbackInfo = handlePositionDiscontinuity( newPlayingPeriodHolder.info.id, newPlayingPeriodHolder.info.startPositionUs, newPlayingPeriodHolder.info.requestedContentPositionUs, /* discontinuityStartPositionUs= */ newPlayingPeriodHolder.info.startPositionUs, /* reportDiscontinuity= */ true, Player.DISCONTINUITY_REASON_AUTO_TRANSITION); updateLivePlaybackSpeedControl( /* newTimeline= */ playbackInfo.timeline, /* newPeriodId= */ newPlayingPeriodHolder.info.id, /* oldTimeline= */ playbackInfo.timeline, /* oldPeriodId= */ oldPlayingPeriodHolder.info.id, /* positionForTargetOffsetOverrideUs= */ C.TIME_UNSET); resetPendingPauseAtEndOfPeriod(); updatePlaybackPositions(); advancedPlayingPeriod = true; } } private void resetPendingPauseAtEndOfPeriod() { @Nullable MediaPeriodHolder playingPeriod = queue.getPlayingPeriod(); pendingPauseAtEndOfPeriod = playingPeriod != null && playingPeriod.info.isLastInTimelineWindow && pauseAtEndOfWindow; } private boolean shouldAdvancePlayingPeriod() { if (!shouldPlayWhenReady()) { return false; } if (pendingPauseAtEndOfPeriod) { return false; } MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder == null) { return false; } MediaPeriodHolder nextPlayingPeriodHolder = playingPeriodHolder.getNext(); return nextPlayingPeriodHolder != null && rendererPositionUs >= nextPlayingPeriodHolder.getStartPositionRendererTime() && nextPlayingPeriodHolder.allRenderersInCorrectState; } private boolean hasReadingPeriodFinishedReading() { MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); if (!readingPeriodHolder.prepared) { return false; } for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; SampleStream sampleStream = readingPeriodHolder.sampleStreams[i]; if (renderer.getStream() != sampleStream || (sampleStream != null && !renderer.hasReadStreamToEnd() && !hasReachedServerSideInsertedAdsTransition(renderer, readingPeriodHolder))) { // The current reading period is still being read by at least one renderer. return false; } } return true; } private boolean hasReachedServerSideInsertedAdsTransition( Renderer renderer, MediaPeriodHolder reading) { MediaPeriodHolder nextPeriod = reading.getNext(); // We can advance the reading period early once we read beyond the transition point in a // server-side inserted ads stream because we know the samples are read from the same underlying // stream. This shortcut is helpful in case the transition point moved and renderers already // read beyond the new transition point. But wait until the next period is actually prepared to // allow a seamless transition. return reading.info.isFollowedByTransitionToSameStream && nextPeriod.prepared && (renderer instanceof TextRenderer // [internal: b/181312195] || renderer.getReadingPositionUs() >= nextPeriod.getStartPositionRendererTime()); } private void setAllRendererStreamsFinal(long streamEndPositionUs) { for (Renderer renderer : renderers) { if (renderer.getStream() != null) { setCurrentStreamFinal(renderer, streamEndPositionUs); } } } private void setCurrentStreamFinal(Renderer renderer, long streamEndPositionUs) { renderer.setCurrentStreamFinal(); if (renderer instanceof TextRenderer) { ((TextRenderer) renderer).setFinalStreamEndPositionUs(streamEndPositionUs); } } private void handlePeriodPrepared(MediaPeriod mediaPeriod) throws ExoPlaybackException { if (!queue.isLoading(mediaPeriod)) { // Stale event. return; } MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); loadingPeriodHolder.handlePrepared( mediaClock.getPlaybackParameters().speed, playbackInfo.timeline); updateLoadControlTrackSelection( loadingPeriodHolder.getTrackGroups(), loadingPeriodHolder.getTrackSelectorResult()); if (loadingPeriodHolder == queue.getPlayingPeriod()) { // This is the first prepared period, so update the position and the renderers. resetRendererPosition(loadingPeriodHolder.info.startPositionUs); enableRenderers(); playbackInfo = handlePositionDiscontinuity( playbackInfo.periodId, loadingPeriodHolder.info.startPositionUs, playbackInfo.requestedContentPositionUs, loadingPeriodHolder.info.startPositionUs, /* reportDiscontinuity= */ false, /* ignored */ Player.DISCONTINUITY_REASON_INTERNAL); } maybeContinueLoading(); } private void handleContinueLoadingRequested(MediaPeriod mediaPeriod) { if (!queue.isLoading(mediaPeriod)) { // Stale event. return; } queue.reevaluateBuffer(rendererPositionUs); maybeContinueLoading(); } private void handlePlaybackParameters( PlaybackParameters playbackParameters, boolean acknowledgeCommand) throws ExoPlaybackException { handlePlaybackParameters( playbackParameters, playbackParameters.speed, /* updatePlaybackInfo= */ true, acknowledgeCommand); } private void handlePlaybackParameters( PlaybackParameters playbackParameters, float currentPlaybackSpeed, boolean updatePlaybackInfo, boolean acknowledgeCommand) throws ExoPlaybackException { if (updatePlaybackInfo) { if (acknowledgeCommand) { playbackInfoUpdate.incrementPendingOperationAcks(1); } playbackInfo = playbackInfo.copyWithPlaybackParameters(playbackParameters); } updateTrackSelectionPlaybackSpeed(playbackParameters.speed); for (Renderer renderer : renderers) { if (renderer != null) { renderer.setPlaybackSpeed( currentPlaybackSpeed, /* targetPlaybackSpeed= */ playbackParameters.speed); } } } private void maybeContinueLoading() { shouldContinueLoading = shouldContinueLoading(); if (shouldContinueLoading) { queue.getLoadingPeriod().continueLoading(rendererPositionUs); } updateIsLoading(); } private boolean shouldContinueLoading() { if (!isLoadingPossible()) { return false; } MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); long bufferedDurationUs = getTotalBufferedDurationUs(loadingPeriodHolder.getNextLoadPositionUs()); long playbackPositionUs = loadingPeriodHolder == queue.getPlayingPeriod() ? loadingPeriodHolder.toPeriodTime(rendererPositionUs) : loadingPeriodHolder.toPeriodTime(rendererPositionUs) - loadingPeriodHolder.info.startPositionUs; return loadControl.shouldContinueLoading( playbackPositionUs, bufferedDurationUs, mediaClock.getPlaybackParameters().speed); } private boolean isLoadingPossible() { MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); if (loadingPeriodHolder == null) { return false; } long nextLoadPositionUs = loadingPeriodHolder.getNextLoadPositionUs(); if (nextLoadPositionUs == C.TIME_END_OF_SOURCE) { return false; } return true; } private void updateIsLoading() { MediaPeriodHolder loadingPeriod = queue.getLoadingPeriod(); boolean isLoading = shouldContinueLoading || (loadingPeriod != null && loadingPeriod.mediaPeriod.isLoading()); if (isLoading != playbackInfo.isLoading) { playbackInfo = playbackInfo.copyWithIsLoading(isLoading); } } @CheckResult private PlaybackInfo handlePositionDiscontinuity( MediaPeriodId mediaPeriodId, long positionUs, long contentPositionUs, long discontinuityStartPositionUs, boolean reportDiscontinuity, @DiscontinuityReason int discontinuityReason) { deliverPendingMessageAtStartPositionRequired = deliverPendingMessageAtStartPositionRequired || positionUs != playbackInfo.positionUs || !mediaPeriodId.equals(playbackInfo.periodId); resetPendingPauseAtEndOfPeriod(); TrackGroupArray trackGroupArray = playbackInfo.trackGroups; TrackSelectorResult trackSelectorResult = playbackInfo.trackSelectorResult; List<Metadata> staticMetadata = playbackInfo.staticMetadata; if (mediaSourceList.isPrepared()) { @Nullable MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); trackGroupArray = playingPeriodHolder == null ? TrackGroupArray.EMPTY : playingPeriodHolder.getTrackGroups(); trackSelectorResult = playingPeriodHolder == null ? emptyTrackSelectorResult : playingPeriodHolder.getTrackSelectorResult(); staticMetadata = extractMetadataFromTrackSelectionArray(trackSelectorResult.selections); // Ensure the media period queue requested content position matches the new playback info. if (playingPeriodHolder != null && playingPeriodHolder.info.requestedContentPositionUs != contentPositionUs) { playingPeriodHolder.info = playingPeriodHolder.info.copyWithRequestedContentPositionUs(contentPositionUs); } } else if (!mediaPeriodId.equals(playbackInfo.periodId)) { // Reset previously kept track info if unprepared and the period changes. trackGroupArray = TrackGroupArray.EMPTY; trackSelectorResult = emptyTrackSelectorResult; staticMetadata = ImmutableList.of(); } if (reportDiscontinuity) { playbackInfoUpdate.setPositionDiscontinuity(discontinuityReason); } return playbackInfo.copyWithNewPosition( mediaPeriodId, positionUs, contentPositionUs, discontinuityStartPositionUs, getTotalBufferedDurationUs(), trackGroupArray, trackSelectorResult, staticMetadata); } private ImmutableList<Metadata> extractMetadataFromTrackSelectionArray( ExoTrackSelection[] trackSelections) { ImmutableList.Builder<Metadata> result = new ImmutableList.Builder<>(); boolean seenNonEmptyMetadata = false; for (ExoTrackSelection trackSelection : trackSelections) { if (trackSelection != null) { Format format = trackSelection.getFormat(/* index= */ 0); if (format.metadata == null) { result.add(new Metadata()); } else { result.add(format.metadata); seenNonEmptyMetadata = true; } } } return seenNonEmptyMetadata ? result.build() : ImmutableList.of(); } private void enableRenderers() throws ExoPlaybackException { enableRenderers(/* rendererWasEnabledFlags= */ new boolean[renderers.length]); } private void enableRenderers(boolean[] rendererWasEnabledFlags) throws ExoPlaybackException { MediaPeriodHolder readingMediaPeriod = queue.getReadingPeriod(); TrackSelectorResult trackSelectorResult = readingMediaPeriod.getTrackSelectorResult(); // Reset all disabled renderers before enabling any new ones. This makes sure resources released // by the disabled renderers will be available to renderers that are being enabled. for (int i = 0; i < renderers.length; i++) { if (!trackSelectorResult.isRendererEnabled(i)) { renderers[i].reset(); } } // Enable the renderers. for (int i = 0; i < renderers.length; i++) { if (trackSelectorResult.isRendererEnabled(i)) { enableRenderer(i, rendererWasEnabledFlags[i]); } } readingMediaPeriod.allRenderersInCorrectState = true; } private void enableRenderer(int rendererIndex, boolean wasRendererEnabled) throws ExoPlaybackException { Renderer renderer = renderers[rendererIndex]; if (isRendererEnabled(renderer)) { return; } MediaPeriodHolder periodHolder = queue.getReadingPeriod(); boolean mayRenderStartOfStream = periodHolder == queue.getPlayingPeriod(); TrackSelectorResult trackSelectorResult = periodHolder.getTrackSelectorResult(); RendererConfiguration rendererConfiguration = trackSelectorResult.rendererConfigurations[rendererIndex]; ExoTrackSelection newSelection = trackSelectorResult.selections[rendererIndex]; Format[] formats = getFormats(newSelection); // The renderer needs enabling with its new track selection. boolean playing = shouldPlayWhenReady() && playbackInfo.playbackState == Player.STATE_READY; // Consider as joining only if the renderer was previously disabled. boolean joining = !wasRendererEnabled && playing; // Enable the renderer. enabledRendererCount++; renderer.enable( rendererConfiguration, formats, periodHolder.sampleStreams[rendererIndex], rendererPositionUs, joining, mayRenderStartOfStream, periodHolder.getStartPositionRendererTime(), periodHolder.getRendererOffset()); renderer.handleMessage( Renderer.MSG_SET_WAKEUP_LISTENER, new Renderer.WakeupListener() { @Override public void onSleep(long wakeupDeadlineMs) { // Do not sleep if the expected sleep time is not long enough to save significant power. if (wakeupDeadlineMs >= MIN_RENDERER_SLEEP_DURATION_MS) { requestForRendererSleep = true; } } @Override public void onWakeup() { handler.sendEmptyMessage(MSG_DO_SOME_WORK); } }); mediaClock.onRendererEnabled(renderer); // Start the renderer if playing. if (playing) { renderer.start(); } } private void handleLoadingMediaPeriodChanged(boolean loadingTrackSelectionChanged) { MediaPeriodHolder loadingMediaPeriodHolder = queue.getLoadingPeriod(); MediaPeriodId loadingMediaPeriodId = loadingMediaPeriodHolder == null ? playbackInfo.periodId : loadingMediaPeriodHolder.info.id; boolean loadingMediaPeriodChanged = !playbackInfo.loadingMediaPeriodId.equals(loadingMediaPeriodId); if (loadingMediaPeriodChanged) { playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(loadingMediaPeriodId); } playbackInfo.bufferedPositionUs = loadingMediaPeriodHolder == null ? playbackInfo.positionUs : loadingMediaPeriodHolder.getBufferedPositionUs(); playbackInfo.totalBufferedDurationUs = getTotalBufferedDurationUs(); if ((loadingMediaPeriodChanged || loadingTrackSelectionChanged) && loadingMediaPeriodHolder != null && loadingMediaPeriodHolder.prepared) { updateLoadControlTrackSelection( loadingMediaPeriodHolder.getTrackGroups(), loadingMediaPeriodHolder.getTrackSelectorResult()); } } private long getTotalBufferedDurationUs() { return getTotalBufferedDurationUs(playbackInfo.bufferedPositionUs); } private long getTotalBufferedDurationUs(long bufferedPositionInLoadingPeriodUs) { MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); if (loadingPeriodHolder == null) { return 0; } long totalBufferedDurationUs = bufferedPositionInLoadingPeriodUs - loadingPeriodHolder.toPeriodTime(rendererPositionUs); return max(0, totalBufferedDurationUs); } private void updateLoadControlTrackSelection( TrackGroupArray trackGroups, TrackSelectorResult trackSelectorResult) { loadControl.onTracksSelected(renderers, trackGroups, trackSelectorResult.selections); } private boolean shouldPlayWhenReady() { return playbackInfo.playWhenReady && playbackInfo.playbackSuppressionReason == Player.PLAYBACK_SUPPRESSION_REASON_NONE; } private static PositionUpdateForPlaylistChange resolvePositionForPlaylistChange( Timeline timeline, PlaybackInfo playbackInfo, @Nullable SeekPosition pendingInitialSeekPosition, MediaPeriodQueue queue, @RepeatMode int repeatMode, boolean shuffleModeEnabled, Timeline.Window window, Timeline.Period period) { if (timeline.isEmpty()) { return new PositionUpdateForPlaylistChange( PlaybackInfo.getDummyPeriodForEmptyTimeline(), /* periodPositionUs= */ 0, /* requestedContentPositionUs= */ C.TIME_UNSET, /* forceBufferingState= */ false, /* endPlayback= */ true, /* setTargetLiveOffset= */ false); } MediaPeriodId oldPeriodId = playbackInfo.periodId; Object newPeriodUid = oldPeriodId.periodUid; boolean isUsingPlaceholderPeriod = isUsingPlaceholderPeriod(playbackInfo, period); long oldContentPositionUs = playbackInfo.periodId.isAd() || isUsingPlaceholderPeriod ? playbackInfo.requestedContentPositionUs : playbackInfo.positionUs; long newContentPositionUs = oldContentPositionUs; int startAtDefaultPositionWindowIndex = C.INDEX_UNSET; boolean forceBufferingState = false; boolean endPlayback = false; boolean setTargetLiveOffset = false; if (pendingInitialSeekPosition != null) { // Resolve initial seek position. @Nullable Pair<Object, Long> periodPosition = resolveSeekPosition( timeline, pendingInitialSeekPosition, /* trySubsequentPeriods= */ true, repeatMode, shuffleModeEnabled, window, period); if (periodPosition == null) { // The initial seek in the empty old timeline is invalid in the new timeline. endPlayback = true; startAtDefaultPositionWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); } else { // The pending seek has been resolved successfully in the new timeline. if (pendingInitialSeekPosition.windowPositionUs == C.TIME_UNSET) { startAtDefaultPositionWindowIndex = timeline.getPeriodByUid(periodPosition.first, period).windowIndex; } else { newPeriodUid = periodPosition.first; newContentPositionUs = periodPosition.second; // Use explicit initial seek as new target live offset. setTargetLiveOffset = true; } forceBufferingState = playbackInfo.playbackState == Player.STATE_ENDED; } } else if (playbackInfo.timeline.isEmpty()) { // Resolve to default position if the old timeline is empty and no seek is requested above. startAtDefaultPositionWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); } else if (timeline.getIndexOfPeriod(newPeriodUid) == C.INDEX_UNSET) { // The current period isn't in the new timeline. Attempt to resolve a subsequent period whose // window we can restart from. @Nullable Object subsequentPeriodUid = resolveSubsequentPeriod( window, period, repeatMode, shuffleModeEnabled, newPeriodUid, playbackInfo.timeline, timeline); if (subsequentPeriodUid == null) { // We failed to resolve a suitable restart position but the timeline is not empty. endPlayback = true; startAtDefaultPositionWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); } else { // We resolved a subsequent period. Start at the default position in the corresponding // window. startAtDefaultPositionWindowIndex = timeline.getPeriodByUid(subsequentPeriodUid, period).windowIndex; } } else if (oldContentPositionUs == C.TIME_UNSET) { // The content was requested to start from its default position and we haven't used the // resolved position yet. Re-resolve in case the default position changed. startAtDefaultPositionWindowIndex = timeline.getPeriodByUid(newPeriodUid, period).windowIndex; } else if (isUsingPlaceholderPeriod) { // We previously requested a content position for a placeholder period, but haven't used it // yet. Re-resolve the requested window position to the period position in case it changed. playbackInfo.timeline.getPeriodByUid(oldPeriodId.periodUid, period); if (playbackInfo.timeline.getWindow(period.windowIndex, window).firstPeriodIndex == playbackInfo.timeline.getIndexOfPeriod(oldPeriodId.periodUid)) { // Only need to resolve the first period in a window because subsequent periods must start // at position 0 and don't need to be resolved. long windowPositionUs = oldContentPositionUs + period.getPositionInWindowUs(); int windowIndex = timeline.getPeriodByUid(newPeriodUid, period).windowIndex; Pair<Object, Long> periodPosition = timeline.getPeriodPosition(window, period, windowIndex, windowPositionUs); newPeriodUid = periodPosition.first; newContentPositionUs = periodPosition.second; } // Use an explicitly requested content position as new target live offset. setTargetLiveOffset = true; } // Set period uid for default positions and resolve position for ad resolution. long contentPositionForAdResolutionUs = newContentPositionUs; if (startAtDefaultPositionWindowIndex != C.INDEX_UNSET) { Pair<Object, Long> defaultPosition = timeline.getPeriodPosition( window, period, startAtDefaultPositionWindowIndex, /* windowPositionUs= */ C.TIME_UNSET); newPeriodUid = defaultPosition.first; contentPositionForAdResolutionUs = defaultPosition.second; newContentPositionUs = C.TIME_UNSET; } // Ensure ad insertion metadata is up to date. MediaPeriodId periodIdWithAds = queue.resolveMediaPeriodIdForAds(timeline, newPeriodUid, contentPositionForAdResolutionUs); boolean earliestCuePointIsUnchangedOrLater = periodIdWithAds.nextAdGroupIndex == C.INDEX_UNSET || (oldPeriodId.nextAdGroupIndex != C.INDEX_UNSET && periodIdWithAds.adGroupIndex >= oldPeriodId.nextAdGroupIndex); // Drop update if we keep playing the same content (MediaPeriod.periodUid are identical) and // the only change is that MediaPeriodId.nextAdGroupIndex increased. This postpones a potential // discontinuity until we reach the former next ad group position. boolean sameOldAndNewPeriodUid = oldPeriodId.periodUid.equals(newPeriodUid); boolean onlyNextAdGroupIndexIncreased = sameOldAndNewPeriodUid && !oldPeriodId.isAd() && !periodIdWithAds.isAd() && earliestCuePointIsUnchangedOrLater; // Drop update if the change is from/to server-side inserted ads at the same content position to // avoid any unintentional renderer reset. timeline.getPeriodByUid(newPeriodUid, period); boolean isInStreamAdChange = sameOldAndNewPeriodUid && !isUsingPlaceholderPeriod && oldContentPositionUs == newContentPositionUs && ((periodIdWithAds.isAd() && period.isServerSideInsertedAdGroup(periodIdWithAds.adGroupIndex)) || (oldPeriodId.isAd() && period.isServerSideInsertedAdGroup(oldPeriodId.adGroupIndex))); MediaPeriodId newPeriodId = onlyNextAdGroupIndexIncreased || isInStreamAdChange ? oldPeriodId : periodIdWithAds; long periodPositionUs = contentPositionForAdResolutionUs; if (newPeriodId.isAd()) { if (newPeriodId.equals(oldPeriodId)) { periodPositionUs = playbackInfo.positionUs; } else { timeline.getPeriodByUid(newPeriodId.periodUid, period); periodPositionUs = newPeriodId.adIndexInAdGroup == period.getFirstAdIndexToPlay(newPeriodId.adGroupIndex) ? period.getAdResumePositionUs() : 0; } } return new PositionUpdateForPlaylistChange( newPeriodId, periodPositionUs, newContentPositionUs, forceBufferingState, endPlayback, setTargetLiveOffset); } private static boolean isUsingPlaceholderPeriod( PlaybackInfo playbackInfo, Timeline.Period period) { MediaPeriodId periodId = playbackInfo.periodId; Timeline timeline = playbackInfo.timeline; return timeline.isEmpty() || timeline.getPeriodByUid(periodId.periodUid, period).isPlaceholder; } /** * Updates pending message to a new timeline. * * @param pendingMessageInfo The pending message. * @param newTimeline The new timeline. * @param previousTimeline The previous timeline used to set the message positions. * @param repeatMode The current repeat mode. * @param shuffleModeEnabled The current shuffle mode. * @param window A scratch window. * @param period A scratch period. * @return Whether the message position could be resolved to the current timeline. */ private static boolean resolvePendingMessagePosition( PendingMessageInfo pendingMessageInfo, Timeline newTimeline, Timeline previousTimeline, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled, Timeline.Window window, Timeline.Period period) { if (pendingMessageInfo.resolvedPeriodUid == null) { // Position is still unresolved. Try to find window in new timeline. long requestPositionUs = pendingMessageInfo.message.getPositionMs() == C.TIME_END_OF_SOURCE ? C.TIME_UNSET : C.msToUs(pendingMessageInfo.message.getPositionMs()); @Nullable Pair<Object, Long> periodPosition = resolveSeekPosition( newTimeline, new SeekPosition( pendingMessageInfo.message.getTimeline(), pendingMessageInfo.message.getWindowIndex(), requestPositionUs), /* trySubsequentPeriods= */ false, repeatMode, shuffleModeEnabled, window, period); if (periodPosition == null) { return false; } pendingMessageInfo.setResolvedPosition( /* periodIndex= */ newTimeline.getIndexOfPeriod(periodPosition.first), /* periodTimeUs= */ periodPosition.second, /* periodUid= */ periodPosition.first); if (pendingMessageInfo.message.getPositionMs() == C.TIME_END_OF_SOURCE) { resolvePendingMessageEndOfStreamPosition(newTimeline, pendingMessageInfo, window, period); } return true; } // Position has been resolved for a previous timeline. Try to find the updated period index. int index = newTimeline.getIndexOfPeriod(pendingMessageInfo.resolvedPeriodUid); if (index == C.INDEX_UNSET) { return false; } if (pendingMessageInfo.message.getPositionMs() == C.TIME_END_OF_SOURCE) { // Re-resolve end of stream in case the duration changed. resolvePendingMessageEndOfStreamPosition(newTimeline, pendingMessageInfo, window, period); return true; } pendingMessageInfo.resolvedPeriodIndex = index; previousTimeline.getPeriodByUid(pendingMessageInfo.resolvedPeriodUid, period); if (period.isPlaceholder && previousTimeline.getWindow(period.windowIndex, window).firstPeriodIndex == previousTimeline.getIndexOfPeriod(pendingMessageInfo.resolvedPeriodUid)) { // The position needs to be re-resolved because the window in the previous timeline wasn't // fully prepared. Only resolve the first period in a window because subsequent periods must // start at position 0 and don't need to be resolved. long windowPositionUs = pendingMessageInfo.resolvedPeriodTimeUs + period.getPositionInWindowUs(); int windowIndex = newTimeline.getPeriodByUid(pendingMessageInfo.resolvedPeriodUid, period).windowIndex; Pair<Object, Long> periodPosition = newTimeline.getPeriodPosition(window, period, windowIndex, windowPositionUs); pendingMessageInfo.setResolvedPosition( /* periodIndex= */ newTimeline.getIndexOfPeriod(periodPosition.first), /* periodTimeUs= */ periodPosition.second, /* periodUid= */ periodPosition.first); } return true; } private static void resolvePendingMessageEndOfStreamPosition( Timeline timeline, PendingMessageInfo messageInfo, Timeline.Window window, Timeline.Period period) { int windowIndex = timeline.getPeriodByUid(messageInfo.resolvedPeriodUid, period).windowIndex; int lastPeriodIndex = timeline.getWindow(windowIndex, window).lastPeriodIndex; Object lastPeriodUid = timeline.getPeriod(lastPeriodIndex, period, /* setIds= */ true).uid; long positionUs = period.durationUs != C.TIME_UNSET ? period.durationUs - 1 : Long.MAX_VALUE; messageInfo.setResolvedPosition(lastPeriodIndex, positionUs, lastPeriodUid); } /** * Converts a {@link SeekPosition} into the corresponding (periodUid, periodPositionUs) for the * internal timeline. * * @param seekPosition The position to resolve. * @param trySubsequentPeriods Whether the position can be resolved to a subsequent matching * period if the original period is no longer available. * @return The resolved position, or null if resolution was not successful. * @throws IllegalSeekPositionException If the window index of the seek position is outside the * bounds of the timeline. */ @Nullable private static Pair<Object, Long> resolveSeekPosition( Timeline timeline, SeekPosition seekPosition, boolean trySubsequentPeriods, @RepeatMode int repeatMode, boolean shuffleModeEnabled, Timeline.Window window, Timeline.Period period) { Timeline seekTimeline = seekPosition.timeline; if (timeline.isEmpty()) { // We don't have a valid timeline yet, so we can't resolve the position. return null; } if (seekTimeline.isEmpty()) { // The application performed a blind seek with an empty timeline (most likely based on // knowledge of what the future timeline will be). Use the internal timeline. seekTimeline = timeline; } // Map the SeekPosition to a position in the corresponding timeline. Pair<Object, Long> periodPosition; try { periodPosition = seekTimeline.getPeriodPosition( window, period, seekPosition.windowIndex, seekPosition.windowPositionUs); } catch (IndexOutOfBoundsException e) { // The window index of the seek position was outside the bounds of the timeline. return null; } if (timeline.equals(seekTimeline)) { // Our internal timeline is the seek timeline, so the mapped position is correct. return periodPosition; } // Attempt to find the mapped period in the internal timeline. int periodIndex = timeline.getIndexOfPeriod(periodPosition.first); if (periodIndex != C.INDEX_UNSET) { // We successfully located the period in the internal timeline. if (seekTimeline.getPeriodByUid(periodPosition.first, period).isPlaceholder && seekTimeline.getWindow(period.windowIndex, window).firstPeriodIndex == seekTimeline.getIndexOfPeriod(periodPosition.first)) { // The seek timeline was using a placeholder, so we need to re-resolve using the updated // timeline in case the resolved position changed. Only resolve the first period in a window // because subsequent periods must start at position 0 and don't need to be resolved. int newWindowIndex = timeline.getPeriodByUid(periodPosition.first, period).windowIndex; periodPosition = timeline.getPeriodPosition( window, period, newWindowIndex, seekPosition.windowPositionUs); } return periodPosition; } if (trySubsequentPeriods) { // Try and find a subsequent period from the seek timeline in the internal timeline. @Nullable Object periodUid = resolveSubsequentPeriod( window, period, repeatMode, shuffleModeEnabled, periodPosition.first, seekTimeline, timeline); if (periodUid != null) { // We found one. Use the default position of the corresponding window. return timeline.getPeriodPosition( window, period, timeline.getPeriodByUid(periodUid, period).windowIndex, /* windowPositionUs= */ C.TIME_UNSET); } } // We didn't find one. Give up. return null; } /** * Given a period index into an old timeline, finds the first subsequent period that also exists * in a new timeline. The uid of this period in the new timeline is returned. * * @param window A {@link Timeline.Window} to be used internally. * @param period A {@link Timeline.Period} to be used internally. * @param repeatMode The repeat mode to use. * @param shuffleModeEnabled Whether the shuffle mode is enabled. * @param oldPeriodUid The index of the period in the old timeline. * @param oldTimeline The old timeline. * @param newTimeline The new timeline. * @return The uid in the new timeline of the first subsequent period, or null if no such period * was found. */ /* package */ static @Nullable Object resolveSubsequentPeriod( Timeline.Window window, Timeline.Period period, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled, Object oldPeriodUid, Timeline oldTimeline, Timeline newTimeline) { int oldPeriodIndex = oldTimeline.getIndexOfPeriod(oldPeriodUid); int newPeriodIndex = C.INDEX_UNSET; int maxIterations = oldTimeline.getPeriodCount(); for (int i = 0; i < maxIterations && newPeriodIndex == C.INDEX_UNSET; i++) { oldPeriodIndex = oldTimeline.getNextPeriodIndex( oldPeriodIndex, period, window, repeatMode, shuffleModeEnabled); if (oldPeriodIndex == C.INDEX_UNSET) { // We've reached the end of the old timeline. break; } newPeriodIndex = newTimeline.getIndexOfPeriod(oldTimeline.getUidOfPeriod(oldPeriodIndex)); } return newPeriodIndex == C.INDEX_UNSET ? null : newTimeline.getUidOfPeriod(newPeriodIndex); } private static Format[] getFormats(ExoTrackSelection newSelection) { // Build an array of formats contained by the selection. int length = newSelection != null ? newSelection.length() : 0; Format[] formats = new Format[length]; for (int i = 0; i < length; i++) { formats[i] = newSelection.getFormat(i); } return formats; } private static boolean isRendererEnabled(Renderer renderer) { return renderer.getState() != Renderer.STATE_DISABLED; } private static final class SeekPosition { public final Timeline timeline; public final int windowIndex; public final long windowPositionUs; public SeekPosition(Timeline timeline, int windowIndex, long windowPositionUs) { this.timeline = timeline; this.windowIndex = windowIndex; this.windowPositionUs = windowPositionUs; } } private static final class PositionUpdateForPlaylistChange { public final MediaPeriodId periodId; public final long periodPositionUs; public final long requestedContentPositionUs; public final boolean forceBufferingState; public final boolean endPlayback; public final boolean setTargetLiveOffset; public PositionUpdateForPlaylistChange( MediaPeriodId periodId, long periodPositionUs, long requestedContentPositionUs, boolean forceBufferingState, boolean endPlayback, boolean setTargetLiveOffset) { this.periodId = periodId; this.periodPositionUs = periodPositionUs; this.requestedContentPositionUs = requestedContentPositionUs; this.forceBufferingState = forceBufferingState; this.endPlayback = endPlayback; this.setTargetLiveOffset = setTargetLiveOffset; } } private static final class PendingMessageInfo implements Comparable<PendingMessageInfo> { public final PlayerMessage message; public int resolvedPeriodIndex; public long resolvedPeriodTimeUs; @Nullable public Object resolvedPeriodUid; public PendingMessageInfo(PlayerMessage message) { this.message = message; } public void setResolvedPosition(int periodIndex, long periodTimeUs, Object periodUid) { resolvedPeriodIndex = periodIndex; resolvedPeriodTimeUs = periodTimeUs; resolvedPeriodUid = periodUid; } @Override public int compareTo(PendingMessageInfo other) { if ((resolvedPeriodUid == null) != (other.resolvedPeriodUid == null)) { // PendingMessageInfos with a resolved period position are always smaller. return resolvedPeriodUid != null ? -1 : 1; } if (resolvedPeriodUid == null) { // Don't sort message with unresolved positions. return 0; } // Sort resolved media times by period index and then by period position. int comparePeriodIndex = resolvedPeriodIndex - other.resolvedPeriodIndex; if (comparePeriodIndex != 0) { return comparePeriodIndex; } return Util.compareLong(resolvedPeriodTimeUs, other.resolvedPeriodTimeUs); } } private static final class MediaSourceListUpdateMessage { private final List<MediaSourceList.MediaSourceHolder> mediaSourceHolders; private final ShuffleOrder shuffleOrder; private final int windowIndex; private final long positionUs; private MediaSourceListUpdateMessage( List<MediaSourceList.MediaSourceHolder> mediaSourceHolders, ShuffleOrder shuffleOrder, int windowIndex, long positionUs) { this.mediaSourceHolders = mediaSourceHolders; this.shuffleOrder = shuffleOrder; this.windowIndex = windowIndex; this.positionUs = positionUs; } } private static class MoveMediaItemsMessage { public final int fromIndex; public final int toIndex; public final int newFromIndex; public final ShuffleOrder shuffleOrder; public MoveMediaItemsMessage( int fromIndex, int toIndex, int newFromIndex, ShuffleOrder shuffleOrder) { this.fromIndex = fromIndex; this.toIndex = toIndex; this.newFromIndex = newFromIndex; this.shuffleOrder = shuffleOrder; } } @RequiresApi(18) private static final class PlatformOperationsWrapperV18 { @DoNotInline public static boolean isNotProvisionedException(@Nullable Throwable throwable) { return throwable instanceof NotProvisionedException; } @DoNotInline public static boolean isDeniedByServerException(@Nullable Throwable throwable) { return throwable instanceof DeniedByServerException; } } @RequiresApi(21) private static final class PlatformOperationsWrapperV21 { @DoNotInline public static boolean isPermissionError(@Nullable Throwable e) { return e instanceof ErrnoException && ((ErrnoException) e).errno == OsConstants.EACCES; } @DoNotInline public static boolean isMediaDrmStateException(@Nullable Throwable throwable) { return throwable instanceof MediaDrm.MediaDrmStateException; } @DoNotInline public static int mediaDrmStateExceptionToErrorCode(Throwable throwable) { @Nullable String diagnosticsInfo = ((MediaDrm.MediaDrmStateException) throwable).getDiagnosticInfo(); return Util.getErrorCodeFromPlatformDiagnosticsInfo(diagnosticsInfo); } } @RequiresApi(23) private static final class PlatformOperationsWrapperV23 { @DoNotInline public static boolean isMediaDrmResetException(@Nullable Throwable throwable) { return throwable instanceof MediaDrmResetException; } } }
library/core/src/main/java/com/google/android/exoplayer2/ExoPlayerImplInternal.java
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.exoplayer2; import static com.google.android.exoplayer2.util.Util.castNonNull; import static java.lang.Math.max; import static java.lang.Math.min; import android.media.DeniedByServerException; import android.media.MediaDrm; import android.media.MediaDrmResetException; import android.media.NotProvisionedException; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.os.Process; import android.os.SystemClock; import android.system.ErrnoException; import android.system.OsConstants; import android.util.Pair; import androidx.annotation.CheckResult; import androidx.annotation.DoNotInline; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import com.google.android.exoplayer2.DefaultMediaClock.PlaybackParametersListener; import com.google.android.exoplayer2.PlaybackException.ErrorCode; import com.google.android.exoplayer2.Player.DiscontinuityReason; import com.google.android.exoplayer2.Player.PlayWhenReadyChangeReason; import com.google.android.exoplayer2.Player.PlaybackSuppressionReason; import com.google.android.exoplayer2.Player.RepeatMode; import com.google.android.exoplayer2.analytics.AnalyticsCollector; import com.google.android.exoplayer2.drm.DefaultDrmSessionManager; import com.google.android.exoplayer2.drm.DrmSession; import com.google.android.exoplayer2.drm.UnsupportedDrmException; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.source.BehindLiveWindowException; import com.google.android.exoplayer2.source.MediaPeriod; import com.google.android.exoplayer2.source.MediaSource.MediaPeriodId; import com.google.android.exoplayer2.source.SampleStream; import com.google.android.exoplayer2.source.ShuffleOrder; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.text.TextRenderer; import com.google.android.exoplayer2.trackselection.ExoTrackSelection; import com.google.android.exoplayer2.trackselection.TrackSelector; import com.google.android.exoplayer2.trackselection.TrackSelectorResult; import com.google.android.exoplayer2.upstream.BandwidthMeter; import com.google.android.exoplayer2.upstream.FileDataSource; import com.google.android.exoplayer2.upstream.HttpDataSource; import com.google.android.exoplayer2.upstream.UdpDataSource; import com.google.android.exoplayer2.util.Assertions; import com.google.android.exoplayer2.util.Clock; import com.google.android.exoplayer2.util.HandlerWrapper; import com.google.android.exoplayer2.util.Log; import com.google.android.exoplayer2.util.TraceUtil; import com.google.android.exoplayer2.util.Util; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import java.io.FileNotFoundException; import java.io.IOException; import java.net.SocketTimeoutException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** Implements the internal behavior of {@link ExoPlayerImpl}. */ /* package */ final class ExoPlayerImplInternal implements Handler.Callback, MediaPeriod.Callback, TrackSelector.InvalidationListener, MediaSourceList.MediaSourceListInfoRefreshListener, PlaybackParametersListener, PlayerMessage.Sender { private static final String TAG = "ExoPlayerImplInternal"; public static final class PlaybackInfoUpdate { private boolean hasPendingChange; public PlaybackInfo playbackInfo; public int operationAcks; public boolean positionDiscontinuity; @DiscontinuityReason public int discontinuityReason; public boolean hasPlayWhenReadyChangeReason; @PlayWhenReadyChangeReason public int playWhenReadyChangeReason; public PlaybackInfoUpdate(PlaybackInfo playbackInfo) { this.playbackInfo = playbackInfo; } public void incrementPendingOperationAcks(int operationAcks) { hasPendingChange |= operationAcks > 0; this.operationAcks += operationAcks; } public void setPlaybackInfo(PlaybackInfo playbackInfo) { hasPendingChange |= this.playbackInfo != playbackInfo; this.playbackInfo = playbackInfo; } public void setPositionDiscontinuity(@DiscontinuityReason int discontinuityReason) { if (positionDiscontinuity && this.discontinuityReason != Player.DISCONTINUITY_REASON_INTERNAL) { // We always prefer non-internal discontinuity reasons. We also assume that we won't report // more than one non-internal discontinuity per message iteration. Assertions.checkArgument(discontinuityReason == Player.DISCONTINUITY_REASON_INTERNAL); return; } hasPendingChange = true; positionDiscontinuity = true; this.discontinuityReason = discontinuityReason; } public void setPlayWhenReadyChangeReason( @PlayWhenReadyChangeReason int playWhenReadyChangeReason) { hasPendingChange = true; this.hasPlayWhenReadyChangeReason = true; this.playWhenReadyChangeReason = playWhenReadyChangeReason; } } public interface PlaybackInfoUpdateListener { void onPlaybackInfoUpdate(ExoPlayerImplInternal.PlaybackInfoUpdate playbackInfo); } // Internal messages private static final int MSG_PREPARE = 0; private static final int MSG_SET_PLAY_WHEN_READY = 1; private static final int MSG_DO_SOME_WORK = 2; private static final int MSG_SEEK_TO = 3; private static final int MSG_SET_PLAYBACK_PARAMETERS = 4; private static final int MSG_SET_SEEK_PARAMETERS = 5; private static final int MSG_STOP = 6; private static final int MSG_RELEASE = 7; private static final int MSG_PERIOD_PREPARED = 8; private static final int MSG_SOURCE_CONTINUE_LOADING_REQUESTED = 9; private static final int MSG_TRACK_SELECTION_INVALIDATED = 10; private static final int MSG_SET_REPEAT_MODE = 11; private static final int MSG_SET_SHUFFLE_ENABLED = 12; private static final int MSG_SET_FOREGROUND_MODE = 13; private static final int MSG_SEND_MESSAGE = 14; private static final int MSG_SEND_MESSAGE_TO_TARGET_THREAD = 15; private static final int MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL = 16; private static final int MSG_SET_MEDIA_SOURCES = 17; private static final int MSG_ADD_MEDIA_SOURCES = 18; private static final int MSG_MOVE_MEDIA_SOURCES = 19; private static final int MSG_REMOVE_MEDIA_SOURCES = 20; private static final int MSG_SET_SHUFFLE_ORDER = 21; private static final int MSG_PLAYLIST_UPDATE_REQUESTED = 22; private static final int MSG_SET_PAUSE_AT_END_OF_WINDOW = 23; private static final int MSG_SET_OFFLOAD_SCHEDULING_ENABLED = 24; private static final int MSG_ATTEMPT_RENDERER_ERROR_RECOVERY = 25; private static final int ACTIVE_INTERVAL_MS = 10; private static final int IDLE_INTERVAL_MS = 1000; /** * Duration under which pausing the main DO_SOME_WORK loop is not expected to yield significant * power saving. * * <p>This value is probably too high, power measurements are needed adjust it, but as renderer * sleep is currently only implemented for audio offload, which uses buffer much bigger than 2s, * this does not matter for now. */ private static final long MIN_RENDERER_SLEEP_DURATION_MS = 2000; private final Renderer[] renderers; private final RendererCapabilities[] rendererCapabilities; private final TrackSelector trackSelector; private final TrackSelectorResult emptyTrackSelectorResult; private final LoadControl loadControl; private final BandwidthMeter bandwidthMeter; private final HandlerWrapper handler; private final HandlerThread internalPlaybackThread; private final Looper playbackLooper; private final Timeline.Window window; private final Timeline.Period period; private final long backBufferDurationUs; private final boolean retainBackBufferFromKeyframe; private final DefaultMediaClock mediaClock; private final ArrayList<PendingMessageInfo> pendingMessages; private final Clock clock; private final PlaybackInfoUpdateListener playbackInfoUpdateListener; private final MediaPeriodQueue queue; private final MediaSourceList mediaSourceList; private final LivePlaybackSpeedControl livePlaybackSpeedControl; private final long releaseTimeoutMs; @SuppressWarnings("unused") private SeekParameters seekParameters; private PlaybackInfo playbackInfo; private PlaybackInfoUpdate playbackInfoUpdate; private boolean released; private boolean pauseAtEndOfWindow; private boolean pendingPauseAtEndOfPeriod; private boolean isRebuffering; private boolean shouldContinueLoading; @Player.RepeatMode private int repeatMode; private boolean shuffleModeEnabled; private boolean foregroundMode; private boolean requestForRendererSleep; private boolean offloadSchedulingEnabled; private int enabledRendererCount; @Nullable private SeekPosition pendingInitialSeekPosition; private long rendererPositionUs; private int nextPendingMessageIndexHint; private boolean deliverPendingMessageAtStartPositionRequired; @Nullable private ExoPlaybackException pendingRecoverableRendererError; private long setForegroundModeTimeoutMs; public ExoPlayerImplInternal( Renderer[] renderers, TrackSelector trackSelector, TrackSelectorResult emptyTrackSelectorResult, LoadControl loadControl, BandwidthMeter bandwidthMeter, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled, @Nullable AnalyticsCollector analyticsCollector, SeekParameters seekParameters, LivePlaybackSpeedControl livePlaybackSpeedControl, long releaseTimeoutMs, boolean pauseAtEndOfWindow, Looper applicationLooper, Clock clock, PlaybackInfoUpdateListener playbackInfoUpdateListener) { this.playbackInfoUpdateListener = playbackInfoUpdateListener; this.renderers = renderers; this.trackSelector = trackSelector; this.emptyTrackSelectorResult = emptyTrackSelectorResult; this.loadControl = loadControl; this.bandwidthMeter = bandwidthMeter; this.repeatMode = repeatMode; this.shuffleModeEnabled = shuffleModeEnabled; this.seekParameters = seekParameters; this.livePlaybackSpeedControl = livePlaybackSpeedControl; this.releaseTimeoutMs = releaseTimeoutMs; this.setForegroundModeTimeoutMs = releaseTimeoutMs; this.pauseAtEndOfWindow = pauseAtEndOfWindow; this.clock = clock; backBufferDurationUs = loadControl.getBackBufferDurationUs(); retainBackBufferFromKeyframe = loadControl.retainBackBufferFromKeyframe(); playbackInfo = PlaybackInfo.createDummy(emptyTrackSelectorResult); playbackInfoUpdate = new PlaybackInfoUpdate(playbackInfo); rendererCapabilities = new RendererCapabilities[renderers.length]; for (int i = 0; i < renderers.length; i++) { renderers[i].setIndex(i); rendererCapabilities[i] = renderers[i].getCapabilities(); } mediaClock = new DefaultMediaClock(this, clock); pendingMessages = new ArrayList<>(); window = new Timeline.Window(); period = new Timeline.Period(); trackSelector.init(/* listener= */ this, bandwidthMeter); deliverPendingMessageAtStartPositionRequired = true; Handler eventHandler = new Handler(applicationLooper); queue = new MediaPeriodQueue(analyticsCollector, eventHandler); mediaSourceList = new MediaSourceList(/* listener= */ this, analyticsCollector, eventHandler); // Note: The documentation for Process.THREAD_PRIORITY_AUDIO that states "Applications can // not normally change to this priority" is incorrect. internalPlaybackThread = new HandlerThread("ExoPlayer:Playback", Process.THREAD_PRIORITY_AUDIO); internalPlaybackThread.start(); playbackLooper = internalPlaybackThread.getLooper(); handler = clock.createHandler(playbackLooper, this); } public void experimentalSetForegroundModeTimeoutMs(long setForegroundModeTimeoutMs) { this.setForegroundModeTimeoutMs = setForegroundModeTimeoutMs; } public void experimentalSetOffloadSchedulingEnabled(boolean offloadSchedulingEnabled) { handler .obtainMessage( MSG_SET_OFFLOAD_SCHEDULING_ENABLED, offloadSchedulingEnabled ? 1 : 0, /* unused */ 0) .sendToTarget(); } public void prepare() { handler.obtainMessage(MSG_PREPARE).sendToTarget(); } public void setPlayWhenReady( boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason) { handler .obtainMessage(MSG_SET_PLAY_WHEN_READY, playWhenReady ? 1 : 0, playbackSuppressionReason) .sendToTarget(); } public void setPauseAtEndOfWindow(boolean pauseAtEndOfWindow) { handler .obtainMessage(MSG_SET_PAUSE_AT_END_OF_WINDOW, pauseAtEndOfWindow ? 1 : 0, /* ignored */ 0) .sendToTarget(); } public void setRepeatMode(@Player.RepeatMode int repeatMode) { handler.obtainMessage(MSG_SET_REPEAT_MODE, repeatMode, 0).sendToTarget(); } public void setShuffleModeEnabled(boolean shuffleModeEnabled) { handler.obtainMessage(MSG_SET_SHUFFLE_ENABLED, shuffleModeEnabled ? 1 : 0, 0).sendToTarget(); } public void seekTo(Timeline timeline, int windowIndex, long positionUs) { handler .obtainMessage(MSG_SEEK_TO, new SeekPosition(timeline, windowIndex, positionUs)) .sendToTarget(); } public void setPlaybackParameters(PlaybackParameters playbackParameters) { handler.obtainMessage(MSG_SET_PLAYBACK_PARAMETERS, playbackParameters).sendToTarget(); } public void setSeekParameters(SeekParameters seekParameters) { handler.obtainMessage(MSG_SET_SEEK_PARAMETERS, seekParameters).sendToTarget(); } public void stop() { handler.obtainMessage(MSG_STOP).sendToTarget(); } public void setMediaSources( List<MediaSourceList.MediaSourceHolder> mediaSources, int windowIndex, long positionUs, ShuffleOrder shuffleOrder) { handler .obtainMessage( MSG_SET_MEDIA_SOURCES, new MediaSourceListUpdateMessage(mediaSources, shuffleOrder, windowIndex, positionUs)) .sendToTarget(); } public void addMediaSources( int index, List<MediaSourceList.MediaSourceHolder> mediaSources, ShuffleOrder shuffleOrder) { handler .obtainMessage( MSG_ADD_MEDIA_SOURCES, index, /* ignored */ 0, new MediaSourceListUpdateMessage( mediaSources, shuffleOrder, /* windowIndex= */ C.INDEX_UNSET, /* positionUs= */ C.TIME_UNSET)) .sendToTarget(); } public void removeMediaSources(int fromIndex, int toIndex, ShuffleOrder shuffleOrder) { handler .obtainMessage(MSG_REMOVE_MEDIA_SOURCES, fromIndex, toIndex, shuffleOrder) .sendToTarget(); } public void moveMediaSources( int fromIndex, int toIndex, int newFromIndex, ShuffleOrder shuffleOrder) { MoveMediaItemsMessage moveMediaItemsMessage = new MoveMediaItemsMessage(fromIndex, toIndex, newFromIndex, shuffleOrder); handler.obtainMessage(MSG_MOVE_MEDIA_SOURCES, moveMediaItemsMessage).sendToTarget(); } public void setShuffleOrder(ShuffleOrder shuffleOrder) { handler.obtainMessage(MSG_SET_SHUFFLE_ORDER, shuffleOrder).sendToTarget(); } @Override public synchronized void sendMessage(PlayerMessage message) { if (released || !internalPlaybackThread.isAlive()) { Log.w(TAG, "Ignoring messages sent after release."); message.markAsProcessed(/* isDelivered= */ false); return; } handler.obtainMessage(MSG_SEND_MESSAGE, message).sendToTarget(); } /** * Sets the foreground mode. * * @param foregroundMode Whether foreground mode should be enabled. * @return Whether the operations succeeded. If false, the operation timed out. */ public synchronized boolean setForegroundMode(boolean foregroundMode) { if (released || !internalPlaybackThread.isAlive()) { return true; } if (foregroundMode) { handler.obtainMessage(MSG_SET_FOREGROUND_MODE, /* foregroundMode */ 1, 0).sendToTarget(); return true; } else { AtomicBoolean processedFlag = new AtomicBoolean(); handler .obtainMessage(MSG_SET_FOREGROUND_MODE, /* foregroundMode */ 0, 0, processedFlag) .sendToTarget(); waitUninterruptibly(/* condition= */ processedFlag::get, setForegroundModeTimeoutMs); return processedFlag.get(); } } /** * Releases the player. * * @return Whether the release succeeded. If false, the release timed out. */ public synchronized boolean release() { if (released || !internalPlaybackThread.isAlive()) { return true; } handler.sendEmptyMessage(MSG_RELEASE); waitUninterruptibly(/* condition= */ () -> released, releaseTimeoutMs); return released; } public Looper getPlaybackLooper() { return playbackLooper; } // Playlist.PlaylistInfoRefreshListener implementation. @Override public void onPlaylistUpdateRequested() { handler.sendEmptyMessage(MSG_PLAYLIST_UPDATE_REQUESTED); } // MediaPeriod.Callback implementation. @Override public void onPrepared(MediaPeriod source) { handler.obtainMessage(MSG_PERIOD_PREPARED, source).sendToTarget(); } @Override public void onContinueLoadingRequested(MediaPeriod source) { handler.obtainMessage(MSG_SOURCE_CONTINUE_LOADING_REQUESTED, source).sendToTarget(); } // TrackSelector.InvalidationListener implementation. @Override public void onTrackSelectionsInvalidated() { handler.sendEmptyMessage(MSG_TRACK_SELECTION_INVALIDATED); } // DefaultMediaClock.PlaybackParametersListener implementation. @Override public void onPlaybackParametersChanged(PlaybackParameters newPlaybackParameters) { handler .obtainMessage(MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL, newPlaybackParameters) .sendToTarget(); } // Handler.Callback implementation. @Override public boolean handleMessage(Message msg) { try { switch (msg.what) { case MSG_PREPARE: prepareInternal(); break; case MSG_SET_PLAY_WHEN_READY: setPlayWhenReadyInternal( /* playWhenReady= */ msg.arg1 != 0, /* playbackSuppressionReason= */ msg.arg2, /* operationAck= */ true, Player.PLAY_WHEN_READY_CHANGE_REASON_USER_REQUEST); break; case MSG_SET_REPEAT_MODE: setRepeatModeInternal(msg.arg1); break; case MSG_SET_SHUFFLE_ENABLED: setShuffleModeEnabledInternal(msg.arg1 != 0); break; case MSG_DO_SOME_WORK: doSomeWork(); break; case MSG_SEEK_TO: seekToInternal((SeekPosition) msg.obj); break; case MSG_SET_PLAYBACK_PARAMETERS: setPlaybackParametersInternal((PlaybackParameters) msg.obj); break; case MSG_SET_SEEK_PARAMETERS: setSeekParametersInternal((SeekParameters) msg.obj); break; case MSG_SET_FOREGROUND_MODE: setForegroundModeInternal( /* foregroundMode= */ msg.arg1 != 0, /* processedFlag= */ (AtomicBoolean) msg.obj); break; case MSG_STOP: stopInternal(/* forceResetRenderers= */ false, /* acknowledgeStop= */ true); break; case MSG_PERIOD_PREPARED: handlePeriodPrepared((MediaPeriod) msg.obj); break; case MSG_SOURCE_CONTINUE_LOADING_REQUESTED: handleContinueLoadingRequested((MediaPeriod) msg.obj); break; case MSG_TRACK_SELECTION_INVALIDATED: reselectTracksInternal(); break; case MSG_PLAYBACK_PARAMETERS_CHANGED_INTERNAL: handlePlaybackParameters((PlaybackParameters) msg.obj, /* acknowledgeCommand= */ false); break; case MSG_SEND_MESSAGE: sendMessageInternal((PlayerMessage) msg.obj); break; case MSG_SEND_MESSAGE_TO_TARGET_THREAD: sendMessageToTargetThread((PlayerMessage) msg.obj); break; case MSG_SET_MEDIA_SOURCES: setMediaItemsInternal((MediaSourceListUpdateMessage) msg.obj); break; case MSG_ADD_MEDIA_SOURCES: addMediaItemsInternal((MediaSourceListUpdateMessage) msg.obj, msg.arg1); break; case MSG_MOVE_MEDIA_SOURCES: moveMediaItemsInternal((MoveMediaItemsMessage) msg.obj); break; case MSG_REMOVE_MEDIA_SOURCES: removeMediaItemsInternal(msg.arg1, msg.arg2, (ShuffleOrder) msg.obj); break; case MSG_SET_SHUFFLE_ORDER: setShuffleOrderInternal((ShuffleOrder) msg.obj); break; case MSG_PLAYLIST_UPDATE_REQUESTED: mediaSourceListUpdateRequestedInternal(); break; case MSG_SET_PAUSE_AT_END_OF_WINDOW: setPauseAtEndOfWindowInternal(msg.arg1 != 0); break; case MSG_SET_OFFLOAD_SCHEDULING_ENABLED: setOffloadSchedulingEnabledInternal(msg.arg1 == 1); break; case MSG_ATTEMPT_RENDERER_ERROR_RECOVERY: attemptRendererErrorRecovery(); break; case MSG_RELEASE: releaseInternal(); // Return immediately to not send playback info updates after release. return true; default: return false; } } catch (ExoPlaybackException e) { if (e.type == ExoPlaybackException.TYPE_RENDERER) { @Nullable MediaPeriodHolder readingPeriod = queue.getReadingPeriod(); if (readingPeriod != null) { // We can assume that all renderer errors happen in the context of the reading period. See // [internal: b/150584930#comment4] for exceptions that aren't covered by this assumption. e = e.copyWithMediaPeriodId(readingPeriod.info.id); } } if (e.isRecoverable && pendingRecoverableRendererError == null) { Log.w(TAG, "Recoverable renderer error", e); pendingRecoverableRendererError = e; // Given that the player is now in an unhandled exception state, the error needs to be // recovered or the player stopped before any other message is handled. handler.sendMessageAtFrontOfQueue( handler.obtainMessage(MSG_ATTEMPT_RENDERER_ERROR_RECOVERY, e)); } else { if (pendingRecoverableRendererError != null) { pendingRecoverableRendererError.addSuppressed(e); e = pendingRecoverableRendererError; } Log.e(TAG, "Playback error", e); stopInternal(/* forceResetRenderers= */ true, /* acknowledgeStop= */ false); playbackInfo = playbackInfo.copyWithPlaybackError(e); } } catch (DrmSession.DrmSessionException e) { @Nullable Throwable cause = e.getCause(); @ErrorCode int errorCode; if (Util.SDK_INT >= 21 && PlatformOperationsWrapperV21.isMediaDrmStateException(cause)) { errorCode = PlatformOperationsWrapperV21.mediaDrmStateExceptionToErrorCode(cause); } else if (Util.SDK_INT >= 23 && PlaformOperationsWrapperV23.isMediaDrmResetException(cause)) { errorCode = PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR; } else if (Util.SDK_INT >= 18 && PlaformOperationsWrapperV18.isNotProvisionedException(cause)) { errorCode = PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED; } else if (Util.SDK_INT >= 18 && PlaformOperationsWrapperV18.isDeniedByServerException(cause)) { errorCode = PlaybackException.ERROR_CODE_DRM_DEVICE_REVOKED; } else if (cause instanceof UnsupportedDrmException) { errorCode = PlaybackException.ERROR_CODE_DRM_SCHEME_UNSUPPORTED; } else if (cause instanceof DefaultDrmSessionManager.MissingSchemeDataException) { errorCode = PlaybackException.ERROR_CODE_DRM_CONTENT_ERROR; } else { errorCode = PlaybackException.ERROR_CODE_DRM_UNSPECIFIED; } handleIoException(e, errorCode); } catch (FileDataSource.FileDataSourceException e) { @Nullable Throwable cause = e.getCause(); @ErrorCode int errorCode; if (cause instanceof FileNotFoundException) { if (Util.SDK_INT >= 21 && PlatformOperationsWrapperV21.isPermissionError(cause.getCause())) { errorCode = PlaybackException.ERROR_CODE_IO_NO_PERMISSION; } else { errorCode = PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND; } } else if (cause instanceof SecurityException) { errorCode = PlaybackException.ERROR_CODE_IO_NO_PERMISSION; } else { errorCode = PlaybackException.ERROR_CODE_IO_UNSPECIFIED; } handleIoException(e, errorCode); } catch (ParserException e) { @ErrorCode int errorCode; if (e.dataType == C.DATA_TYPE_MEDIA) { errorCode = e.contentIsMalformed ? PlaybackException.ERROR_CODE_PARSING_CONTAINER_MALFORMED : PlaybackException.ERROR_CODE_PARSING_CONTAINER_UNSUPPORTED; } else if (e.dataType == C.DATA_TYPE_MANIFEST) { errorCode = e.contentIsMalformed ? PlaybackException.ERROR_CODE_PARSING_MANIFEST_MALFORMED : PlaybackException.ERROR_CODE_PARSING_MANIFEST_UNSUPPORTED; } else { errorCode = PlaybackException.ERROR_CODE_UNSPECIFIED; } handleIoException(e, errorCode); } catch (HttpDataSource.CleartextNotPermittedException e) { handleIoException(e, PlaybackException.ERROR_CODE_IO_CLEARTEXT_NOT_PERMITTED); } catch (HttpDataSource.InvalidResponseCodeException e) { handleIoException(e, PlaybackException.ERROR_CODE_IO_BAD_HTTP_STATUS); } catch (HttpDataSource.HttpDataSourceException | UdpDataSource.UdpDataSourceException e) { @ErrorCode int errorCode; @Nullable Throwable cause = e.getCause(); if (cause instanceof UnknownHostException) { errorCode = PlaybackException.ERROR_CODE_IO_DNS_FAILED; } else if (cause instanceof SocketTimeoutException) { errorCode = PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_TIMEOUT; } else if (e instanceof HttpDataSource.HttpDataSourceException) { int type = ((HttpDataSource.HttpDataSourceException) e).type; errorCode = type == HttpDataSource.HttpDataSourceException.TYPE_OPEN ? PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED : PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_CLOSED; } else { errorCode = PlaybackException.ERROR_CODE_IO_UNSPECIFIED; } handleIoException(e, errorCode); } catch (BehindLiveWindowException e) { handleIoException(e, PlaybackException.ERROR_CODE_BEHIND_LIVE_WINDOW); } catch (IOException e) { handleIoException(e, PlaybackException.ERROR_CODE_UNSPECIFIED); } catch (RuntimeException e) { ExoPlaybackException error = ExoPlaybackException.createForUnexpected(e); Log.e(TAG, "Playback error", error); stopInternal(/* forceResetRenderers= */ true, /* acknowledgeStop= */ false); playbackInfo = playbackInfo.copyWithPlaybackError(error); } maybeNotifyPlaybackInfoChanged(); return true; } // Private methods. private void handleIoException(IOException e, @ErrorCode int errorCode) { ExoPlaybackException error = ExoPlaybackException.createForSource(e, errorCode); @Nullable MediaPeriodHolder playingPeriod = queue.getPlayingPeriod(); if (playingPeriod != null) { // We ensure that all IOException throwing methods are only executed for the playing period. error = error.copyWithMediaPeriodId(playingPeriod.info.id); } Log.e(TAG, "Playback error", error); stopInternal(/* forceResetRenderers= */ false, /* acknowledgeStop= */ false); playbackInfo = playbackInfo.copyWithPlaybackError(error); } /** * Blocks the current thread until a condition becomes true or the specified amount of time has * elapsed. * * <p>If the current thread is interrupted while waiting for the condition to become true, this * method will restore the interrupt <b>after</b> the condition became true or the operation times * out. * * @param condition The condition. * @param timeoutMs The time in milliseconds to wait for the condition to become true. */ private synchronized void waitUninterruptibly(Supplier<Boolean> condition, long timeoutMs) { long deadlineMs = clock.elapsedRealtime() + timeoutMs; long remainingMs = timeoutMs; boolean wasInterrupted = false; while (!condition.get() && remainingMs > 0) { try { clock.onThreadBlocked(); wait(remainingMs); } catch (InterruptedException e) { wasInterrupted = true; } remainingMs = deadlineMs - clock.elapsedRealtime(); } if (wasInterrupted) { // Restore the interrupted status. Thread.currentThread().interrupt(); } } private void setState(int state) { if (playbackInfo.playbackState != state) { playbackInfo = playbackInfo.copyWithPlaybackState(state); } } private void maybeNotifyPlaybackInfoChanged() { playbackInfoUpdate.setPlaybackInfo(playbackInfo); if (playbackInfoUpdate.hasPendingChange) { playbackInfoUpdateListener.onPlaybackInfoUpdate(playbackInfoUpdate); playbackInfoUpdate = new PlaybackInfoUpdate(playbackInfo); } } private void prepareInternal() { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); resetInternal( /* resetRenderers= */ false, /* resetPosition= */ false, /* releaseMediaSourceList= */ false, /* resetError= */ true); loadControl.onPrepared(); setState(playbackInfo.timeline.isEmpty() ? Player.STATE_ENDED : Player.STATE_BUFFERING); mediaSourceList.prepare(bandwidthMeter.getTransferListener()); handler.sendEmptyMessage(MSG_DO_SOME_WORK); } private void setMediaItemsInternal(MediaSourceListUpdateMessage mediaSourceListUpdateMessage) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); if (mediaSourceListUpdateMessage.windowIndex != C.INDEX_UNSET) { pendingInitialSeekPosition = new SeekPosition( new PlaylistTimeline( mediaSourceListUpdateMessage.mediaSourceHolders, mediaSourceListUpdateMessage.shuffleOrder), mediaSourceListUpdateMessage.windowIndex, mediaSourceListUpdateMessage.positionUs); } Timeline timeline = mediaSourceList.setMediaSources( mediaSourceListUpdateMessage.mediaSourceHolders, mediaSourceListUpdateMessage.shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void addMediaItemsInternal(MediaSourceListUpdateMessage addMessage, int insertionIndex) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.addMediaSources( insertionIndex == C.INDEX_UNSET ? mediaSourceList.getSize() : insertionIndex, addMessage.mediaSourceHolders, addMessage.shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void moveMediaItemsInternal(MoveMediaItemsMessage moveMediaItemsMessage) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.moveMediaSourceRange( moveMediaItemsMessage.fromIndex, moveMediaItemsMessage.toIndex, moveMediaItemsMessage.newFromIndex, moveMediaItemsMessage.shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void removeMediaItemsInternal(int fromIndex, int toIndex, ShuffleOrder shuffleOrder) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.removeMediaSourceRange(fromIndex, toIndex, shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void mediaSourceListUpdateRequestedInternal() throws ExoPlaybackException { handleMediaSourceListInfoRefreshed( mediaSourceList.createTimeline(), /* isSourceRefresh= */ true); } private void setShuffleOrderInternal(ShuffleOrder shuffleOrder) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); Timeline timeline = mediaSourceList.setShuffleOrder(shuffleOrder); handleMediaSourceListInfoRefreshed(timeline, /* isSourceRefresh= */ false); } private void notifyTrackSelectionPlayWhenReadyChanged(boolean playWhenReady) { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onPlayWhenReadyChanged(playWhenReady); } } periodHolder = periodHolder.getNext(); } } private void setPlayWhenReadyInternal( boolean playWhenReady, @PlaybackSuppressionReason int playbackSuppressionReason, boolean operationAck, @Player.PlayWhenReadyChangeReason int reason) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(operationAck ? 1 : 0); playbackInfoUpdate.setPlayWhenReadyChangeReason(reason); playbackInfo = playbackInfo.copyWithPlayWhenReady(playWhenReady, playbackSuppressionReason); isRebuffering = false; notifyTrackSelectionPlayWhenReadyChanged(playWhenReady); if (!shouldPlayWhenReady()) { stopRenderers(); updatePlaybackPositions(); } else { if (playbackInfo.playbackState == Player.STATE_READY) { startRenderers(); handler.sendEmptyMessage(MSG_DO_SOME_WORK); } else if (playbackInfo.playbackState == Player.STATE_BUFFERING) { handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } } private void setPauseAtEndOfWindowInternal(boolean pauseAtEndOfWindow) throws ExoPlaybackException { this.pauseAtEndOfWindow = pauseAtEndOfWindow; resetPendingPauseAtEndOfPeriod(); if (pendingPauseAtEndOfPeriod && queue.getReadingPeriod() != queue.getPlayingPeriod()) { // When pausing is required, we need to set the streams of the playing period final. If we // already started reading the next period, we need to flush the renderers. seekToCurrentPosition(/* sendDiscontinuity= */ true); handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } } private void setOffloadSchedulingEnabledInternal(boolean offloadSchedulingEnabled) { if (offloadSchedulingEnabled == this.offloadSchedulingEnabled) { return; } this.offloadSchedulingEnabled = offloadSchedulingEnabled; @Player.State int state = playbackInfo.playbackState; if (offloadSchedulingEnabled || state == Player.STATE_ENDED || state == Player.STATE_IDLE) { playbackInfo = playbackInfo.copyWithOffloadSchedulingEnabled(offloadSchedulingEnabled); } else { handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } private void setRepeatModeInternal(@Player.RepeatMode int repeatMode) throws ExoPlaybackException { this.repeatMode = repeatMode; if (!queue.updateRepeatMode(playbackInfo.timeline, repeatMode)) { seekToCurrentPosition(/* sendDiscontinuity= */ true); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } private void setShuffleModeEnabledInternal(boolean shuffleModeEnabled) throws ExoPlaybackException { this.shuffleModeEnabled = shuffleModeEnabled; if (!queue.updateShuffleModeEnabled(playbackInfo.timeline, shuffleModeEnabled)) { seekToCurrentPosition(/* sendDiscontinuity= */ true); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } private void seekToCurrentPosition(boolean sendDiscontinuity) throws ExoPlaybackException { // Renderers may have read from a period that's been removed. Seek back to the current // position of the playing period to make sure none of the removed period is played. MediaPeriodId periodId = queue.getPlayingPeriod().info.id; long newPositionUs = seekToPeriodPosition( periodId, playbackInfo.positionUs, /* forceDisableRenderers= */ true, /* forceBufferingState= */ false); if (newPositionUs != playbackInfo.positionUs) { playbackInfo = handlePositionDiscontinuity( periodId, newPositionUs, playbackInfo.requestedContentPositionUs, playbackInfo.discontinuityStartPositionUs, sendDiscontinuity, Player.DISCONTINUITY_REASON_INTERNAL); } } private void startRenderers() throws ExoPlaybackException { isRebuffering = false; mediaClock.start(); for (Renderer renderer : renderers) { if (isRendererEnabled(renderer)) { renderer.start(); } } } private void stopRenderers() throws ExoPlaybackException { mediaClock.stop(); for (Renderer renderer : renderers) { if (isRendererEnabled(renderer)) { ensureStopped(renderer); } } } private void attemptRendererErrorRecovery() throws ExoPlaybackException { seekToCurrentPosition(/* sendDiscontinuity= */ true); } private void updatePlaybackPositions() throws ExoPlaybackException { MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder == null) { return; } // Update the playback position. long discontinuityPositionUs = playingPeriodHolder.prepared ? playingPeriodHolder.mediaPeriod.readDiscontinuity() : C.TIME_UNSET; if (discontinuityPositionUs != C.TIME_UNSET) { resetRendererPosition(discontinuityPositionUs); // A MediaPeriod may report a discontinuity at the current playback position to ensure the // renderers are flushed. Only report the discontinuity externally if the position changed. if (discontinuityPositionUs != playbackInfo.positionUs) { playbackInfo = handlePositionDiscontinuity( playbackInfo.periodId, /* positionUs= */ discontinuityPositionUs, playbackInfo.requestedContentPositionUs, /* discontinuityStartPositionUs= */ discontinuityPositionUs, /* reportDiscontinuity= */ true, Player.DISCONTINUITY_REASON_INTERNAL); } } else { rendererPositionUs = mediaClock.syncAndGetPositionUs( /* isReadingAhead= */ playingPeriodHolder != queue.getReadingPeriod()); long periodPositionUs = playingPeriodHolder.toPeriodTime(rendererPositionUs); maybeTriggerPendingMessages(playbackInfo.positionUs, periodPositionUs); playbackInfo.positionUs = periodPositionUs; } // Update the buffered position and total buffered duration. MediaPeriodHolder loadingPeriod = queue.getLoadingPeriod(); playbackInfo.bufferedPositionUs = loadingPeriod.getBufferedPositionUs(); playbackInfo.totalBufferedDurationUs = getTotalBufferedDurationUs(); // Adjust live playback speed to new position. if (playbackInfo.playWhenReady && playbackInfo.playbackState == Player.STATE_READY && shouldUseLivePlaybackSpeedControl(playbackInfo.timeline, playbackInfo.periodId) && playbackInfo.playbackParameters.speed == 1f) { float adjustedSpeed = livePlaybackSpeedControl.getAdjustedPlaybackSpeed( getCurrentLiveOffsetUs(), getTotalBufferedDurationUs()); if (mediaClock.getPlaybackParameters().speed != adjustedSpeed) { mediaClock.setPlaybackParameters(playbackInfo.playbackParameters.withSpeed(adjustedSpeed)); handlePlaybackParameters( playbackInfo.playbackParameters, /* currentPlaybackSpeed= */ mediaClock.getPlaybackParameters().speed, /* updatePlaybackInfo= */ false, /* acknowledgeCommand= */ false); } } } private void notifyTrackSelectionRebuffer() { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onRebuffer(); } } periodHolder = periodHolder.getNext(); } } private void doSomeWork() throws ExoPlaybackException, IOException { long operationStartTimeMs = clock.uptimeMillis(); updatePeriods(); if (playbackInfo.playbackState == Player.STATE_IDLE || playbackInfo.playbackState == Player.STATE_ENDED) { // Remove all messages. Prepare (in case of IDLE) or seek (in case of ENDED) will resume. handler.removeMessages(MSG_DO_SOME_WORK); return; } @Nullable MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder == null) { // We're still waiting until the playing period is available. scheduleNextWork(operationStartTimeMs, ACTIVE_INTERVAL_MS); return; } TraceUtil.beginSection("doSomeWork"); updatePlaybackPositions(); boolean renderersEnded = true; boolean renderersAllowPlayback = true; if (playingPeriodHolder.prepared) { long rendererPositionElapsedRealtimeUs = SystemClock.elapsedRealtime() * 1000; playingPeriodHolder.mediaPeriod.discardBuffer( playbackInfo.positionUs - backBufferDurationUs, retainBackBufferFromKeyframe); for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; if (!isRendererEnabled(renderer)) { continue; } // TODO: Each renderer should return the maximum delay before which it wishes to be called // again. The minimum of these values should then be used as the delay before the next // invocation of this method. renderer.render(rendererPositionUs, rendererPositionElapsedRealtimeUs); renderersEnded = renderersEnded && renderer.isEnded(); // Determine whether the renderer allows playback to continue. Playback can continue if the // renderer is ready or ended. Also continue playback if the renderer is reading ahead into // the next stream or is waiting for the next stream. This is to avoid getting stuck if // tracks in the current period have uneven durations and are still being read by another // renderer. See: https://github.com/google/ExoPlayer/issues/1874. boolean isReadingAhead = playingPeriodHolder.sampleStreams[i] != renderer.getStream(); boolean isWaitingForNextStream = !isReadingAhead && renderer.hasReadStreamToEnd(); boolean allowsPlayback = isReadingAhead || isWaitingForNextStream || renderer.isReady() || renderer.isEnded(); renderersAllowPlayback = renderersAllowPlayback && allowsPlayback; if (!allowsPlayback) { renderer.maybeThrowStreamError(); } } } else { playingPeriodHolder.mediaPeriod.maybeThrowPrepareError(); } long playingPeriodDurationUs = playingPeriodHolder.info.durationUs; boolean finishedRendering = renderersEnded && playingPeriodHolder.prepared && (playingPeriodDurationUs == C.TIME_UNSET || playingPeriodDurationUs <= playbackInfo.positionUs); if (finishedRendering && pendingPauseAtEndOfPeriod) { pendingPauseAtEndOfPeriod = false; setPlayWhenReadyInternal( /* playWhenReady= */ false, playbackInfo.playbackSuppressionReason, /* operationAck= */ false, Player.PLAY_WHEN_READY_CHANGE_REASON_END_OF_MEDIA_ITEM); } if (finishedRendering && playingPeriodHolder.info.isFinal) { setState(Player.STATE_ENDED); stopRenderers(); } else if (playbackInfo.playbackState == Player.STATE_BUFFERING && shouldTransitionToReadyState(renderersAllowPlayback)) { setState(Player.STATE_READY); pendingRecoverableRendererError = null; // Any pending error was successfully recovered from. if (shouldPlayWhenReady()) { startRenderers(); } } else if (playbackInfo.playbackState == Player.STATE_READY && !(enabledRendererCount == 0 ? isTimelineReady() : renderersAllowPlayback)) { isRebuffering = shouldPlayWhenReady(); setState(Player.STATE_BUFFERING); if (isRebuffering) { notifyTrackSelectionRebuffer(); livePlaybackSpeedControl.notifyRebuffer(); } stopRenderers(); } if (playbackInfo.playbackState == Player.STATE_BUFFERING) { for (int i = 0; i < renderers.length; i++) { if (isRendererEnabled(renderers[i]) && renderers[i].getStream() == playingPeriodHolder.sampleStreams[i]) { renderers[i].maybeThrowStreamError(); } } if (!playbackInfo.isLoading && playbackInfo.totalBufferedDurationUs < 500_000 && isLoadingPossible()) { // Throw if the LoadControl prevents loading even if the buffer is empty or almost empty. We // can't compare against 0 to account for small differences between the renderer position // and buffered position in the media at the point where playback gets stuck. throw new IllegalStateException("Playback stuck buffering and not loading"); } } if (offloadSchedulingEnabled != playbackInfo.offloadSchedulingEnabled) { playbackInfo = playbackInfo.copyWithOffloadSchedulingEnabled(offloadSchedulingEnabled); } boolean sleepingForOffload = false; if ((shouldPlayWhenReady() && playbackInfo.playbackState == Player.STATE_READY) || playbackInfo.playbackState == Player.STATE_BUFFERING) { sleepingForOffload = !maybeScheduleWakeup(operationStartTimeMs, ACTIVE_INTERVAL_MS); } else if (enabledRendererCount != 0 && playbackInfo.playbackState != Player.STATE_ENDED) { scheduleNextWork(operationStartTimeMs, IDLE_INTERVAL_MS); } else { handler.removeMessages(MSG_DO_SOME_WORK); } if (playbackInfo.sleepingForOffload != sleepingForOffload) { playbackInfo = playbackInfo.copyWithSleepingForOffload(sleepingForOffload); } requestForRendererSleep = false; // A sleep request is only valid for the current doSomeWork. TraceUtil.endSection(); } private long getCurrentLiveOffsetUs() { return getLiveOffsetUs( playbackInfo.timeline, playbackInfo.periodId.periodUid, playbackInfo.positionUs); } private long getLiveOffsetUs(Timeline timeline, Object periodUid, long periodPositionUs) { int windowIndex = timeline.getPeriodByUid(periodUid, period).windowIndex; timeline.getWindow(windowIndex, window); if (window.windowStartTimeMs == C.TIME_UNSET || !window.isLive() || !window.isDynamic) { return C.TIME_UNSET; } return C.msToUs(window.getCurrentUnixTimeMs() - window.windowStartTimeMs) - (periodPositionUs + period.getPositionInWindowUs()); } private boolean shouldUseLivePlaybackSpeedControl( Timeline timeline, MediaPeriodId mediaPeriodId) { if (mediaPeriodId.isAd() || timeline.isEmpty()) { return false; } int windowIndex = timeline.getPeriodByUid(mediaPeriodId.periodUid, period).windowIndex; timeline.getWindow(windowIndex, window); return window.isLive() && window.isDynamic && window.windowStartTimeMs != C.TIME_UNSET; } private void scheduleNextWork(long thisOperationStartTimeMs, long intervalMs) { handler.removeMessages(MSG_DO_SOME_WORK); handler.sendEmptyMessageAtTime(MSG_DO_SOME_WORK, thisOperationStartTimeMs + intervalMs); } private boolean maybeScheduleWakeup(long operationStartTimeMs, long intervalMs) { if (offloadSchedulingEnabled && requestForRendererSleep) { return false; } scheduleNextWork(operationStartTimeMs, intervalMs); return true; } private void seekToInternal(SeekPosition seekPosition) throws ExoPlaybackException { playbackInfoUpdate.incrementPendingOperationAcks(/* operationAcks= */ 1); MediaPeriodId periodId; long periodPositionUs; long requestedContentPositionUs; boolean seekPositionAdjusted; @Nullable Pair<Object, Long> resolvedSeekPosition = resolveSeekPosition( playbackInfo.timeline, seekPosition, /* trySubsequentPeriods= */ true, repeatMode, shuffleModeEnabled, window, period); if (resolvedSeekPosition == null) { // The seek position was valid for the timeline that it was performed into, but the // timeline has changed or is not ready and a suitable seek position could not be resolved. Pair<MediaPeriodId, Long> firstPeriodAndPosition = getPlaceholderFirstMediaPeriodPosition(playbackInfo.timeline); periodId = firstPeriodAndPosition.first; periodPositionUs = firstPeriodAndPosition.second; requestedContentPositionUs = C.TIME_UNSET; seekPositionAdjusted = !playbackInfo.timeline.isEmpty(); } else { // Update the resolved seek position to take ads into account. Object periodUid = resolvedSeekPosition.first; long resolvedContentPositionUs = resolvedSeekPosition.second; requestedContentPositionUs = seekPosition.windowPositionUs == C.TIME_UNSET ? C.TIME_UNSET : resolvedContentPositionUs; periodId = queue.resolveMediaPeriodIdForAds( playbackInfo.timeline, periodUid, resolvedContentPositionUs); if (periodId.isAd()) { playbackInfo.timeline.getPeriodByUid(periodId.periodUid, period); periodPositionUs = period.getFirstAdIndexToPlay(periodId.adGroupIndex) == periodId.adIndexInAdGroup ? period.getAdResumePositionUs() : 0; seekPositionAdjusted = true; } else { periodPositionUs = resolvedContentPositionUs; seekPositionAdjusted = seekPosition.windowPositionUs == C.TIME_UNSET; } } try { if (playbackInfo.timeline.isEmpty()) { // Save seek position for later, as we are still waiting for a prepared source. pendingInitialSeekPosition = seekPosition; } else if (resolvedSeekPosition == null) { // End playback, as we didn't manage to find a valid seek position. if (playbackInfo.playbackState != Player.STATE_IDLE) { setState(Player.STATE_ENDED); } resetInternal( /* resetRenderers= */ false, /* resetPosition= */ true, /* releaseMediaSourceList= */ false, /* resetError= */ true); } else { // Execute the seek in the current media periods. long newPeriodPositionUs = periodPositionUs; if (periodId.equals(playbackInfo.periodId)) { MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder != null && playingPeriodHolder.prepared && newPeriodPositionUs != 0) { newPeriodPositionUs = playingPeriodHolder.mediaPeriod.getAdjustedSeekPositionUs( newPeriodPositionUs, seekParameters); } if (C.usToMs(newPeriodPositionUs) == C.usToMs(playbackInfo.positionUs) && (playbackInfo.playbackState == Player.STATE_BUFFERING || playbackInfo.playbackState == Player.STATE_READY)) { // Seek will be performed to the current position. Do nothing. periodPositionUs = playbackInfo.positionUs; return; } } newPeriodPositionUs = seekToPeriodPosition( periodId, newPeriodPositionUs, /* forceBufferingState= */ playbackInfo.playbackState == Player.STATE_ENDED); seekPositionAdjusted |= periodPositionUs != newPeriodPositionUs; periodPositionUs = newPeriodPositionUs; updateLivePlaybackSpeedControl( /* newTimeline= */ playbackInfo.timeline, /* newPeriodId= */ periodId, /* oldTimeline= */ playbackInfo.timeline, /* oldPeriodId= */ playbackInfo.periodId, /* positionForTargetOffsetOverrideUs= */ requestedContentPositionUs); } } finally { playbackInfo = handlePositionDiscontinuity( periodId, periodPositionUs, requestedContentPositionUs, /* discontinuityStartPositionUs= */ periodPositionUs, /* reportDiscontinuity= */ seekPositionAdjusted, Player.DISCONTINUITY_REASON_SEEK_ADJUSTMENT); } } private long seekToPeriodPosition( MediaPeriodId periodId, long periodPositionUs, boolean forceBufferingState) throws ExoPlaybackException { // Force disable renderers if they are reading from a period other than the one being played. return seekToPeriodPosition( periodId, periodPositionUs, queue.getPlayingPeriod() != queue.getReadingPeriod(), forceBufferingState); } private long seekToPeriodPosition( MediaPeriodId periodId, long periodPositionUs, boolean forceDisableRenderers, boolean forceBufferingState) throws ExoPlaybackException { stopRenderers(); isRebuffering = false; if (forceBufferingState || playbackInfo.playbackState == Player.STATE_READY) { setState(Player.STATE_BUFFERING); } // Find the requested period if it already exists. @Nullable MediaPeriodHolder oldPlayingPeriodHolder = queue.getPlayingPeriod(); @Nullable MediaPeriodHolder newPlayingPeriodHolder = oldPlayingPeriodHolder; while (newPlayingPeriodHolder != null) { if (periodId.equals(newPlayingPeriodHolder.info.id)) { break; } newPlayingPeriodHolder = newPlayingPeriodHolder.getNext(); } // Disable all renderers if the period being played is changing, if the seek results in negative // renderer timestamps, or if forced. if (forceDisableRenderers || oldPlayingPeriodHolder != newPlayingPeriodHolder || (newPlayingPeriodHolder != null && newPlayingPeriodHolder.toRendererTime(periodPositionUs) < 0)) { for (Renderer renderer : renderers) { disableRenderer(renderer); } if (newPlayingPeriodHolder != null) { // Update the queue and reenable renderers if the requested media period already exists. while (queue.getPlayingPeriod() != newPlayingPeriodHolder) { queue.advancePlayingPeriod(); } queue.removeAfter(newPlayingPeriodHolder); newPlayingPeriodHolder.setRendererOffset(/* rendererPositionOffsetUs= */ 0); enableRenderers(); } } // Do the actual seeking. if (newPlayingPeriodHolder != null) { queue.removeAfter(newPlayingPeriodHolder); if (!newPlayingPeriodHolder.prepared) { newPlayingPeriodHolder.info = newPlayingPeriodHolder.info.copyWithStartPositionUs(periodPositionUs); } else { if (newPlayingPeriodHolder.info.durationUs != C.TIME_UNSET && periodPositionUs >= newPlayingPeriodHolder.info.durationUs) { // Make sure seek position doesn't exceed period duration. periodPositionUs = max(0, newPlayingPeriodHolder.info.durationUs - 1); } if (newPlayingPeriodHolder.hasEnabledTracks) { periodPositionUs = newPlayingPeriodHolder.mediaPeriod.seekToUs(periodPositionUs); newPlayingPeriodHolder.mediaPeriod.discardBuffer( periodPositionUs - backBufferDurationUs, retainBackBufferFromKeyframe); } } resetRendererPosition(periodPositionUs); maybeContinueLoading(); } else { // New period has not been prepared. queue.clear(); resetRendererPosition(periodPositionUs); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); handler.sendEmptyMessage(MSG_DO_SOME_WORK); return periodPositionUs; } private void resetRendererPosition(long periodPositionUs) throws ExoPlaybackException { MediaPeriodHolder playingMediaPeriod = queue.getPlayingPeriod(); rendererPositionUs = playingMediaPeriod == null ? periodPositionUs : playingMediaPeriod.toRendererTime(periodPositionUs); mediaClock.resetPosition(rendererPositionUs); for (Renderer renderer : renderers) { if (isRendererEnabled(renderer)) { renderer.resetPosition(rendererPositionUs); } } notifyTrackSelectionDiscontinuity(); } private void setPlaybackParametersInternal(PlaybackParameters playbackParameters) throws ExoPlaybackException { mediaClock.setPlaybackParameters(playbackParameters); handlePlaybackParameters(mediaClock.getPlaybackParameters(), /* acknowledgeCommand= */ true); } private void setSeekParametersInternal(SeekParameters seekParameters) { this.seekParameters = seekParameters; } private void setForegroundModeInternal( boolean foregroundMode, @Nullable AtomicBoolean processedFlag) { if (this.foregroundMode != foregroundMode) { this.foregroundMode = foregroundMode; if (!foregroundMode) { for (Renderer renderer : renderers) { if (!isRendererEnabled(renderer)) { renderer.reset(); } } } } if (processedFlag != null) { synchronized (this) { processedFlag.set(true); notifyAll(); } } } private void stopInternal(boolean forceResetRenderers, boolean acknowledgeStop) { resetInternal( /* resetRenderers= */ forceResetRenderers || !foregroundMode, /* resetPosition= */ false, /* releaseMediaSourceList= */ true, /* resetError= */ false); playbackInfoUpdate.incrementPendingOperationAcks(acknowledgeStop ? 1 : 0); loadControl.onStopped(); setState(Player.STATE_IDLE); } private void releaseInternal() { resetInternal( /* resetRenderers= */ true, /* resetPosition= */ false, /* releaseMediaSourceList= */ true, /* resetError= */ false); loadControl.onReleased(); setState(Player.STATE_IDLE); internalPlaybackThread.quit(); synchronized (this) { released = true; notifyAll(); } } private void resetInternal( boolean resetRenderers, boolean resetPosition, boolean releaseMediaSourceList, boolean resetError) { handler.removeMessages(MSG_DO_SOME_WORK); pendingRecoverableRendererError = null; isRebuffering = false; mediaClock.stop(); rendererPositionUs = 0; for (Renderer renderer : renderers) { try { disableRenderer(renderer); } catch (ExoPlaybackException | RuntimeException e) { // There's nothing we can do. Log.e(TAG, "Disable failed.", e); } } if (resetRenderers) { for (Renderer renderer : renderers) { try { renderer.reset(); } catch (RuntimeException e) { // There's nothing we can do. Log.e(TAG, "Reset failed.", e); } } } enabledRendererCount = 0; MediaPeriodId mediaPeriodId = playbackInfo.periodId; long startPositionUs = playbackInfo.positionUs; long requestedContentPositionUs = playbackInfo.periodId.isAd() || isUsingPlaceholderPeriod(playbackInfo, period) ? playbackInfo.requestedContentPositionUs : playbackInfo.positionUs; boolean resetTrackInfo = false; if (resetPosition) { pendingInitialSeekPosition = null; Pair<MediaPeriodId, Long> firstPeriodAndPosition = getPlaceholderFirstMediaPeriodPosition(playbackInfo.timeline); mediaPeriodId = firstPeriodAndPosition.first; startPositionUs = firstPeriodAndPosition.second; requestedContentPositionUs = C.TIME_UNSET; if (!mediaPeriodId.equals(playbackInfo.periodId)) { resetTrackInfo = true; } } queue.clear(); shouldContinueLoading = false; playbackInfo = new PlaybackInfo( playbackInfo.timeline, mediaPeriodId, requestedContentPositionUs, /* discontinuityStartPositionUs= */ startPositionUs, playbackInfo.playbackState, resetError ? null : playbackInfo.playbackError, /* isLoading= */ false, resetTrackInfo ? TrackGroupArray.EMPTY : playbackInfo.trackGroups, resetTrackInfo ? emptyTrackSelectorResult : playbackInfo.trackSelectorResult, resetTrackInfo ? ImmutableList.of() : playbackInfo.staticMetadata, mediaPeriodId, playbackInfo.playWhenReady, playbackInfo.playbackSuppressionReason, playbackInfo.playbackParameters, /* bufferedPositionUs= */ startPositionUs, /* totalBufferedDurationUs= */ 0, /* positionUs= */ startPositionUs, offloadSchedulingEnabled, /* sleepingForOffload= */ false); if (releaseMediaSourceList) { mediaSourceList.release(); } } private Pair<MediaPeriodId, Long> getPlaceholderFirstMediaPeriodPosition(Timeline timeline) { if (timeline.isEmpty()) { return Pair.create(PlaybackInfo.getDummyPeriodForEmptyTimeline(), 0L); } int firstWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); Pair<Object, Long> firstPeriodAndPosition = timeline.getPeriodPosition( window, period, firstWindowIndex, /* windowPositionUs= */ C.TIME_UNSET); // Add ad metadata if any and propagate the window sequence number to new period id. MediaPeriodId firstPeriodId = queue.resolveMediaPeriodIdForAds( timeline, firstPeriodAndPosition.first, /* positionUs= */ 0); long positionUs = firstPeriodAndPosition.second; if (firstPeriodId.isAd()) { timeline.getPeriodByUid(firstPeriodId.periodUid, period); positionUs = firstPeriodId.adIndexInAdGroup == period.getFirstAdIndexToPlay(firstPeriodId.adGroupIndex) ? period.getAdResumePositionUs() : 0; } return Pair.create(firstPeriodId, positionUs); } private void sendMessageInternal(PlayerMessage message) throws ExoPlaybackException { if (message.getPositionMs() == C.TIME_UNSET) { // If no delivery time is specified, trigger immediate message delivery. sendMessageToTarget(message); } else if (playbackInfo.timeline.isEmpty()) { // Still waiting for initial timeline to resolve position. pendingMessages.add(new PendingMessageInfo(message)); } else { PendingMessageInfo pendingMessageInfo = new PendingMessageInfo(message); if (resolvePendingMessagePosition( pendingMessageInfo, /* newTimeline= */ playbackInfo.timeline, /* previousTimeline= */ playbackInfo.timeline, repeatMode, shuffleModeEnabled, window, period)) { pendingMessages.add(pendingMessageInfo); // Ensure new message is inserted according to playback order. Collections.sort(pendingMessages); } else { message.markAsProcessed(/* isDelivered= */ false); } } } private void sendMessageToTarget(PlayerMessage message) throws ExoPlaybackException { if (message.getLooper() == playbackLooper) { deliverMessage(message); if (playbackInfo.playbackState == Player.STATE_READY || playbackInfo.playbackState == Player.STATE_BUFFERING) { // The message may have caused something to change that now requires us to do work. handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } else { handler.obtainMessage(MSG_SEND_MESSAGE_TO_TARGET_THREAD, message).sendToTarget(); } } private void sendMessageToTargetThread(final PlayerMessage message) { Looper looper = message.getLooper(); if (!looper.getThread().isAlive()) { Log.w("TAG", "Trying to send message on a dead thread."); message.markAsProcessed(/* isDelivered= */ false); return; } clock .createHandler(looper, /* callback= */ null) .post( () -> { try { deliverMessage(message); } catch (ExoPlaybackException e) { Log.e(TAG, "Unexpected error delivering message on external thread.", e); throw new RuntimeException(e); } }); } private void deliverMessage(PlayerMessage message) throws ExoPlaybackException { if (message.isCanceled()) { return; } try { message.getTarget().handleMessage(message.getType(), message.getPayload()); } finally { message.markAsProcessed(/* isDelivered= */ true); } } private void resolvePendingMessagePositions(Timeline newTimeline, Timeline previousTimeline) { if (newTimeline.isEmpty() && previousTimeline.isEmpty()) { // Keep all messages unresolved until we have a non-empty timeline. return; } for (int i = pendingMessages.size() - 1; i >= 0; i--) { if (!resolvePendingMessagePosition( pendingMessages.get(i), newTimeline, previousTimeline, repeatMode, shuffleModeEnabled, window, period)) { // Unable to resolve a new position for the message. Remove it. pendingMessages.get(i).message.markAsProcessed(/* isDelivered= */ false); pendingMessages.remove(i); } } // Re-sort messages by playback order. Collections.sort(pendingMessages); } private void maybeTriggerPendingMessages(long oldPeriodPositionUs, long newPeriodPositionUs) throws ExoPlaybackException { if (pendingMessages.isEmpty() || playbackInfo.periodId.isAd()) { return; } // If this is the first call after resetting the renderer position, include oldPeriodPositionUs // in potential trigger positions, but make sure we deliver it only once. if (deliverPendingMessageAtStartPositionRequired) { oldPeriodPositionUs--; deliverPendingMessageAtStartPositionRequired = false; } // Correct next index if necessary (e.g. after seeking, timeline changes, or new messages) int currentPeriodIndex = playbackInfo.timeline.getIndexOfPeriod(playbackInfo.periodId.periodUid); int nextPendingMessageIndex = min(nextPendingMessageIndexHint, pendingMessages.size()); PendingMessageInfo previousInfo = nextPendingMessageIndex > 0 ? pendingMessages.get(nextPendingMessageIndex - 1) : null; while (previousInfo != null && (previousInfo.resolvedPeriodIndex > currentPeriodIndex || (previousInfo.resolvedPeriodIndex == currentPeriodIndex && previousInfo.resolvedPeriodTimeUs > oldPeriodPositionUs))) { nextPendingMessageIndex--; previousInfo = nextPendingMessageIndex > 0 ? pendingMessages.get(nextPendingMessageIndex - 1) : null; } PendingMessageInfo nextInfo = nextPendingMessageIndex < pendingMessages.size() ? pendingMessages.get(nextPendingMessageIndex) : null; while (nextInfo != null && nextInfo.resolvedPeriodUid != null && (nextInfo.resolvedPeriodIndex < currentPeriodIndex || (nextInfo.resolvedPeriodIndex == currentPeriodIndex && nextInfo.resolvedPeriodTimeUs <= oldPeriodPositionUs))) { nextPendingMessageIndex++; nextInfo = nextPendingMessageIndex < pendingMessages.size() ? pendingMessages.get(nextPendingMessageIndex) : null; } // Check if any message falls within the covered time span. while (nextInfo != null && nextInfo.resolvedPeriodUid != null && nextInfo.resolvedPeriodIndex == currentPeriodIndex && nextInfo.resolvedPeriodTimeUs > oldPeriodPositionUs && nextInfo.resolvedPeriodTimeUs <= newPeriodPositionUs) { try { sendMessageToTarget(nextInfo.message); } finally { if (nextInfo.message.getDeleteAfterDelivery() || nextInfo.message.isCanceled()) { pendingMessages.remove(nextPendingMessageIndex); } else { nextPendingMessageIndex++; } } nextInfo = nextPendingMessageIndex < pendingMessages.size() ? pendingMessages.get(nextPendingMessageIndex) : null; } nextPendingMessageIndexHint = nextPendingMessageIndex; } private void ensureStopped(Renderer renderer) throws ExoPlaybackException { if (renderer.getState() == Renderer.STATE_STARTED) { renderer.stop(); } } private void disableRenderer(Renderer renderer) throws ExoPlaybackException { if (!isRendererEnabled(renderer)) { return; } mediaClock.onRendererDisabled(renderer); ensureStopped(renderer); renderer.disable(); enabledRendererCount--; } private void reselectTracksInternal() throws ExoPlaybackException { float playbackSpeed = mediaClock.getPlaybackParameters().speed; // Reselect tracks on each period in turn, until the selection changes. MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); boolean selectionsChangedForReadPeriod = true; TrackSelectorResult newTrackSelectorResult; while (true) { if (periodHolder == null || !periodHolder.prepared) { // The reselection did not change any prepared periods. return; } newTrackSelectorResult = periodHolder.selectTracks(playbackSpeed, playbackInfo.timeline); if (!newTrackSelectorResult.isEquivalent(periodHolder.getTrackSelectorResult())) { // Selected tracks have changed for this period. break; } if (periodHolder == readingPeriodHolder) { // The track reselection didn't affect any period that has been read. selectionsChangedForReadPeriod = false; } periodHolder = periodHolder.getNext(); } if (selectionsChangedForReadPeriod) { // Update streams and rebuffer for the new selection, recreating all streams if reading ahead. MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); boolean recreateStreams = queue.removeAfter(playingPeriodHolder); boolean[] streamResetFlags = new boolean[renderers.length]; long periodPositionUs = playingPeriodHolder.applyTrackSelection( newTrackSelectorResult, playbackInfo.positionUs, recreateStreams, streamResetFlags); boolean hasDiscontinuity = playbackInfo.playbackState != Player.STATE_ENDED && periodPositionUs != playbackInfo.positionUs; playbackInfo = handlePositionDiscontinuity( playbackInfo.periodId, periodPositionUs, playbackInfo.requestedContentPositionUs, playbackInfo.discontinuityStartPositionUs, hasDiscontinuity, Player.DISCONTINUITY_REASON_INTERNAL); if (hasDiscontinuity) { resetRendererPosition(periodPositionUs); } boolean[] rendererWasEnabledFlags = new boolean[renderers.length]; for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; rendererWasEnabledFlags[i] = isRendererEnabled(renderer); SampleStream sampleStream = playingPeriodHolder.sampleStreams[i]; if (rendererWasEnabledFlags[i]) { if (sampleStream != renderer.getStream()) { // We need to disable the renderer. disableRenderer(renderer); } else if (streamResetFlags[i]) { // The renderer will continue to consume from its current stream, but needs to be reset. renderer.resetPosition(rendererPositionUs); } } } enableRenderers(rendererWasEnabledFlags); } else { // Release and re-prepare/buffer periods after the one whose selection changed. queue.removeAfter(periodHolder); if (periodHolder.prepared) { long loadingPeriodPositionUs = max(periodHolder.info.startPositionUs, periodHolder.toPeriodTime(rendererPositionUs)); periodHolder.applyTrackSelection(newTrackSelectorResult, loadingPeriodPositionUs, false); } } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ true); if (playbackInfo.playbackState != Player.STATE_ENDED) { maybeContinueLoading(); updatePlaybackPositions(); handler.sendEmptyMessage(MSG_DO_SOME_WORK); } } private void updateTrackSelectionPlaybackSpeed(float playbackSpeed) { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onPlaybackSpeed(playbackSpeed); } } periodHolder = periodHolder.getNext(); } } private void notifyTrackSelectionDiscontinuity() { MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { for (ExoTrackSelection trackSelection : periodHolder.getTrackSelectorResult().selections) { if (trackSelection != null) { trackSelection.onDiscontinuity(); } } periodHolder = periodHolder.getNext(); } } private boolean shouldTransitionToReadyState(boolean renderersReadyOrEnded) { if (enabledRendererCount == 0) { // If there are no enabled renderers, determine whether we're ready based on the timeline. return isTimelineReady(); } if (!renderersReadyOrEnded) { return false; } if (!playbackInfo.isLoading) { // Renderers are ready and we're not loading. Transition to ready, since the alternative is // getting stuck waiting for additional media that's not being loaded. return true; } // Renderers are ready and we're loading. Ask the LoadControl whether to transition. long targetLiveOffsetUs = shouldUseLivePlaybackSpeedControl(playbackInfo.timeline, queue.getPlayingPeriod().info.id) ? livePlaybackSpeedControl.getTargetLiveOffsetUs() : C.TIME_UNSET; MediaPeriodHolder loadingHolder = queue.getLoadingPeriod(); boolean isBufferedToEnd = loadingHolder.isFullyBuffered() && loadingHolder.info.isFinal; // Ad loader implementations may only load ad media once playback has nearly reached the ad, but // it is possible for playback to be stuck buffering waiting for this. Therefore, we start // playback regardless of buffered duration if we are waiting for an ad media period to prepare. boolean isAdPendingPreparation = loadingHolder.info.id.isAd() && !loadingHolder.prepared; return isBufferedToEnd || isAdPendingPreparation || loadControl.shouldStartPlayback( getTotalBufferedDurationUs(), mediaClock.getPlaybackParameters().speed, isRebuffering, targetLiveOffsetUs); } private boolean isTimelineReady() { MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); long playingPeriodDurationUs = playingPeriodHolder.info.durationUs; return playingPeriodHolder.prepared && (playingPeriodDurationUs == C.TIME_UNSET || playbackInfo.positionUs < playingPeriodDurationUs || !shouldPlayWhenReady()); } private void handleMediaSourceListInfoRefreshed(Timeline timeline, boolean isSourceRefresh) throws ExoPlaybackException { PositionUpdateForPlaylistChange positionUpdate = resolvePositionForPlaylistChange( timeline, playbackInfo, pendingInitialSeekPosition, queue, repeatMode, shuffleModeEnabled, window, period); MediaPeriodId newPeriodId = positionUpdate.periodId; long newRequestedContentPositionUs = positionUpdate.requestedContentPositionUs; boolean forceBufferingState = positionUpdate.forceBufferingState; long newPositionUs = positionUpdate.periodPositionUs; boolean periodPositionChanged = !playbackInfo.periodId.equals(newPeriodId) || newPositionUs != playbackInfo.positionUs; try { if (positionUpdate.endPlayback) { if (playbackInfo.playbackState != Player.STATE_IDLE) { setState(Player.STATE_ENDED); } resetInternal( /* resetRenderers= */ false, /* resetPosition= */ false, /* releaseMediaSourceList= */ false, /* resetError= */ true); } if (!periodPositionChanged) { // We can keep the current playing period. Update the rest of the queued periods. if (!queue.updateQueuedPeriods( timeline, rendererPositionUs, getMaxRendererReadPositionUs())) { seekToCurrentPosition(/* sendDiscontinuity= */ false); } } else if (!timeline.isEmpty()) { // Something changed. Seek to new start position. @Nullable MediaPeriodHolder periodHolder = queue.getPlayingPeriod(); while (periodHolder != null) { // Update the new playing media period info if it already exists. if (periodHolder.info.id.equals(newPeriodId)) { periodHolder.info = queue.getUpdatedMediaPeriodInfo(timeline, periodHolder.info); periodHolder.updateClipping(); } periodHolder = periodHolder.getNext(); } newPositionUs = seekToPeriodPosition(newPeriodId, newPositionUs, forceBufferingState); } } finally { updateLivePlaybackSpeedControl( /* newTimeline= */ timeline, newPeriodId, /* oldTimeline= */ playbackInfo.timeline, /* oldPeriodId= */ playbackInfo.periodId, /* positionForTargetOffsetOverrideUs */ positionUpdate.setTargetLiveOffset ? newPositionUs : C.TIME_UNSET); if (periodPositionChanged || newRequestedContentPositionUs != playbackInfo.requestedContentPositionUs) { Object oldPeriodUid = playbackInfo.periodId.periodUid; Timeline oldTimeline = playbackInfo.timeline; boolean reportDiscontinuity = periodPositionChanged && isSourceRefresh && !oldTimeline.isEmpty() && !oldTimeline.getPeriodByUid(oldPeriodUid, period).isPlaceholder; playbackInfo = handlePositionDiscontinuity( newPeriodId, newPositionUs, newRequestedContentPositionUs, playbackInfo.discontinuityStartPositionUs, reportDiscontinuity, timeline.getIndexOfPeriod(oldPeriodUid) == C.INDEX_UNSET ? Player.DISCONTINUITY_REASON_REMOVE : Player.DISCONTINUITY_REASON_SKIP); } resetPendingPauseAtEndOfPeriod(); resolvePendingMessagePositions( /* newTimeline= */ timeline, /* previousTimeline= */ playbackInfo.timeline); playbackInfo = playbackInfo.copyWithTimeline(timeline); if (!timeline.isEmpty()) { // Retain pending seek position only while the timeline is still empty. pendingInitialSeekPosition = null; } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } } private void updateLivePlaybackSpeedControl( Timeline newTimeline, MediaPeriodId newPeriodId, Timeline oldTimeline, MediaPeriodId oldPeriodId, long positionForTargetOffsetOverrideUs) { if (newTimeline.isEmpty() || !shouldUseLivePlaybackSpeedControl(newTimeline, newPeriodId)) { // Live playback speed control is unused for the current period, reset speed if adjusted. if (mediaClock.getPlaybackParameters().speed != playbackInfo.playbackParameters.speed) { mediaClock.setPlaybackParameters(playbackInfo.playbackParameters); } return; } int windowIndex = newTimeline.getPeriodByUid(newPeriodId.periodUid, period).windowIndex; newTimeline.getWindow(windowIndex, window); livePlaybackSpeedControl.setLiveConfiguration(castNonNull(window.liveConfiguration)); if (positionForTargetOffsetOverrideUs != C.TIME_UNSET) { livePlaybackSpeedControl.setTargetLiveOffsetOverrideUs( getLiveOffsetUs(newTimeline, newPeriodId.periodUid, positionForTargetOffsetOverrideUs)); } else { Object windowUid = window.uid; @Nullable Object oldWindowUid = null; if (!oldTimeline.isEmpty()) { int oldWindowIndex = oldTimeline.getPeriodByUid(oldPeriodId.periodUid, period).windowIndex; oldWindowUid = oldTimeline.getWindow(oldWindowIndex, window).uid; } if (!Util.areEqual(oldWindowUid, windowUid)) { // Reset overridden target live offset to media values if window changes. livePlaybackSpeedControl.setTargetLiveOffsetOverrideUs(C.TIME_UNSET); } } } private long getMaxRendererReadPositionUs() { MediaPeriodHolder readingHolder = queue.getReadingPeriod(); if (readingHolder == null) { return 0; } long maxReadPositionUs = readingHolder.getRendererOffset(); if (!readingHolder.prepared) { return maxReadPositionUs; } for (int i = 0; i < renderers.length; i++) { if (!isRendererEnabled(renderers[i]) || renderers[i].getStream() != readingHolder.sampleStreams[i]) { // Ignore disabled renderers and renderers with sample streams from previous periods. continue; } long readingPositionUs = renderers[i].getReadingPositionUs(); if (readingPositionUs == C.TIME_END_OF_SOURCE) { return C.TIME_END_OF_SOURCE; } else { maxReadPositionUs = max(readingPositionUs, maxReadPositionUs); } } return maxReadPositionUs; } private void updatePeriods() throws ExoPlaybackException, IOException { if (playbackInfo.timeline.isEmpty() || !mediaSourceList.isPrepared()) { // No periods available. return; } maybeUpdateLoadingPeriod(); maybeUpdateReadingPeriod(); maybeUpdateReadingRenderers(); maybeUpdatePlayingPeriod(); } private void maybeUpdateLoadingPeriod() throws ExoPlaybackException { queue.reevaluateBuffer(rendererPositionUs); if (queue.shouldLoadNextMediaPeriod()) { @Nullable MediaPeriodInfo info = queue.getNextMediaPeriodInfo(rendererPositionUs, playbackInfo); if (info != null) { MediaPeriodHolder mediaPeriodHolder = queue.enqueueNextMediaPeriodHolder( rendererCapabilities, trackSelector, loadControl.getAllocator(), mediaSourceList, info, emptyTrackSelectorResult); mediaPeriodHolder.mediaPeriod.prepare(this, info.startPositionUs); if (queue.getPlayingPeriod() == mediaPeriodHolder) { resetRendererPosition(mediaPeriodHolder.getStartPositionRendererTime()); } handleLoadingMediaPeriodChanged(/* loadingTrackSelectionChanged= */ false); } } if (shouldContinueLoading) { // We should still be loading, except when there is nothing to load or we have fully loaded // the current period. shouldContinueLoading = isLoadingPossible(); updateIsLoading(); } else { maybeContinueLoading(); } } private void maybeUpdateReadingPeriod() { @Nullable MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); if (readingPeriodHolder == null) { return; } if (readingPeriodHolder.getNext() == null || pendingPauseAtEndOfPeriod) { // We don't have a successor to advance the reading period to or we want to let them end // intentionally to pause at the end of the period. if (readingPeriodHolder.info.isFinal || pendingPauseAtEndOfPeriod) { for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; SampleStream sampleStream = readingPeriodHolder.sampleStreams[i]; // Defer setting the stream as final until the renderer has actually consumed the whole // stream in case of playlist changes that cause the stream to be no longer final. if (sampleStream != null && renderer.getStream() == sampleStream && renderer.hasReadStreamToEnd()) { long streamEndPositionUs = readingPeriodHolder.info.durationUs != C.TIME_UNSET && readingPeriodHolder.info.durationUs != C.TIME_END_OF_SOURCE ? readingPeriodHolder.getRendererOffset() + readingPeriodHolder.info.durationUs : C.TIME_UNSET; setCurrentStreamFinal(renderer, streamEndPositionUs); } } } return; } if (!hasReadingPeriodFinishedReading()) { return; } if (!readingPeriodHolder.getNext().prepared && rendererPositionUs < readingPeriodHolder.getNext().getStartPositionRendererTime()) { // The successor is not prepared yet and playback hasn't reached the transition point. return; } TrackSelectorResult oldTrackSelectorResult = readingPeriodHolder.getTrackSelectorResult(); readingPeriodHolder = queue.advanceReadingPeriod(); TrackSelectorResult newTrackSelectorResult = readingPeriodHolder.getTrackSelectorResult(); if (readingPeriodHolder.prepared && readingPeriodHolder.mediaPeriod.readDiscontinuity() != C.TIME_UNSET) { // The new period starts with a discontinuity, so the renderers will play out all data, then // be disabled and re-enabled when they start playing the next period. setAllRendererStreamsFinal( /* streamEndPositionUs= */ readingPeriodHolder.getStartPositionRendererTime()); return; } for (int i = 0; i < renderers.length; i++) { boolean oldRendererEnabled = oldTrackSelectorResult.isRendererEnabled(i); boolean newRendererEnabled = newTrackSelectorResult.isRendererEnabled(i); if (oldRendererEnabled && !renderers[i].isCurrentStreamFinal()) { boolean isNoSampleRenderer = rendererCapabilities[i].getTrackType() == C.TRACK_TYPE_NONE; RendererConfiguration oldConfig = oldTrackSelectorResult.rendererConfigurations[i]; RendererConfiguration newConfig = newTrackSelectorResult.rendererConfigurations[i]; if (!newRendererEnabled || !newConfig.equals(oldConfig) || isNoSampleRenderer) { // The renderer will be disabled when transitioning to playing the next period, because // there's no new selection, or because a configuration change is required, or because // it's a no-sample renderer for which rendererOffsetUs should be updated only when // starting to play the next period. Mark the SampleStream as final to play out any // remaining data. setCurrentStreamFinal( renderers[i], /* streamEndPositionUs= */ readingPeriodHolder.getStartPositionRendererTime()); } } } } private void maybeUpdateReadingRenderers() throws ExoPlaybackException { @Nullable MediaPeriodHolder readingPeriod = queue.getReadingPeriod(); if (readingPeriod == null || queue.getPlayingPeriod() == readingPeriod || readingPeriod.allRenderersInCorrectState) { // Not reading ahead or all renderers updated. return; } if (replaceStreamsOrDisableRendererForTransition()) { enableRenderers(); } } private boolean replaceStreamsOrDisableRendererForTransition() throws ExoPlaybackException { MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); TrackSelectorResult newTrackSelectorResult = readingPeriodHolder.getTrackSelectorResult(); boolean needsToWaitForRendererToEnd = false; for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; if (!isRendererEnabled(renderer)) { continue; } boolean rendererIsReadingOldStream = renderer.getStream() != readingPeriodHolder.sampleStreams[i]; boolean rendererShouldBeEnabled = newTrackSelectorResult.isRendererEnabled(i); if (rendererShouldBeEnabled && !rendererIsReadingOldStream) { // All done. continue; } if (!renderer.isCurrentStreamFinal()) { // The renderer stream is not final, so we can replace the sample streams immediately. Format[] formats = getFormats(newTrackSelectorResult.selections[i]); renderer.replaceStream( formats, readingPeriodHolder.sampleStreams[i], readingPeriodHolder.getStartPositionRendererTime(), readingPeriodHolder.getRendererOffset()); } else if (renderer.isEnded()) { // The renderer has finished playback, so we can disable it now. disableRenderer(renderer); } else { // We need to wait until rendering finished before disabling the renderer. needsToWaitForRendererToEnd = true; } } return !needsToWaitForRendererToEnd; } private void maybeUpdatePlayingPeriod() throws ExoPlaybackException { boolean advancedPlayingPeriod = false; while (shouldAdvancePlayingPeriod()) { if (advancedPlayingPeriod) { // If we advance more than one period at a time, notify listeners after each update. maybeNotifyPlaybackInfoChanged(); } MediaPeriodHolder oldPlayingPeriodHolder = queue.getPlayingPeriod(); MediaPeriodHolder newPlayingPeriodHolder = queue.advancePlayingPeriod(); playbackInfo = handlePositionDiscontinuity( newPlayingPeriodHolder.info.id, newPlayingPeriodHolder.info.startPositionUs, newPlayingPeriodHolder.info.requestedContentPositionUs, /* discontinuityStartPositionUs= */ newPlayingPeriodHolder.info.startPositionUs, /* reportDiscontinuity= */ true, Player.DISCONTINUITY_REASON_AUTO_TRANSITION); updateLivePlaybackSpeedControl( /* newTimeline= */ playbackInfo.timeline, /* newPeriodId= */ newPlayingPeriodHolder.info.id, /* oldTimeline= */ playbackInfo.timeline, /* oldPeriodId= */ oldPlayingPeriodHolder.info.id, /* positionForTargetOffsetOverrideUs= */ C.TIME_UNSET); resetPendingPauseAtEndOfPeriod(); updatePlaybackPositions(); advancedPlayingPeriod = true; } } private void resetPendingPauseAtEndOfPeriod() { @Nullable MediaPeriodHolder playingPeriod = queue.getPlayingPeriod(); pendingPauseAtEndOfPeriod = playingPeriod != null && playingPeriod.info.isLastInTimelineWindow && pauseAtEndOfWindow; } private boolean shouldAdvancePlayingPeriod() { if (!shouldPlayWhenReady()) { return false; } if (pendingPauseAtEndOfPeriod) { return false; } MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); if (playingPeriodHolder == null) { return false; } MediaPeriodHolder nextPlayingPeriodHolder = playingPeriodHolder.getNext(); return nextPlayingPeriodHolder != null && rendererPositionUs >= nextPlayingPeriodHolder.getStartPositionRendererTime() && nextPlayingPeriodHolder.allRenderersInCorrectState; } private boolean hasReadingPeriodFinishedReading() { MediaPeriodHolder readingPeriodHolder = queue.getReadingPeriod(); if (!readingPeriodHolder.prepared) { return false; } for (int i = 0; i < renderers.length; i++) { Renderer renderer = renderers[i]; SampleStream sampleStream = readingPeriodHolder.sampleStreams[i]; if (renderer.getStream() != sampleStream || (sampleStream != null && !renderer.hasReadStreamToEnd() && !hasReachedServerSideInsertedAdsTransition(renderer, readingPeriodHolder))) { // The current reading period is still being read by at least one renderer. return false; } } return true; } private boolean hasReachedServerSideInsertedAdsTransition( Renderer renderer, MediaPeriodHolder reading) { MediaPeriodHolder nextPeriod = reading.getNext(); // We can advance the reading period early once we read beyond the transition point in a // server-side inserted ads stream because we know the samples are read from the same underlying // stream. This shortcut is helpful in case the transition point moved and renderers already // read beyond the new transition point. But wait until the next period is actually prepared to // allow a seamless transition. return reading.info.isFollowedByTransitionToSameStream && nextPeriod.prepared && (renderer instanceof TextRenderer // [internal: b/181312195] || renderer.getReadingPositionUs() >= nextPeriod.getStartPositionRendererTime()); } private void setAllRendererStreamsFinal(long streamEndPositionUs) { for (Renderer renderer : renderers) { if (renderer.getStream() != null) { setCurrentStreamFinal(renderer, streamEndPositionUs); } } } private void setCurrentStreamFinal(Renderer renderer, long streamEndPositionUs) { renderer.setCurrentStreamFinal(); if (renderer instanceof TextRenderer) { ((TextRenderer) renderer).setFinalStreamEndPositionUs(streamEndPositionUs); } } private void handlePeriodPrepared(MediaPeriod mediaPeriod) throws ExoPlaybackException { if (!queue.isLoading(mediaPeriod)) { // Stale event. return; } MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); loadingPeriodHolder.handlePrepared( mediaClock.getPlaybackParameters().speed, playbackInfo.timeline); updateLoadControlTrackSelection( loadingPeriodHolder.getTrackGroups(), loadingPeriodHolder.getTrackSelectorResult()); if (loadingPeriodHolder == queue.getPlayingPeriod()) { // This is the first prepared period, so update the position and the renderers. resetRendererPosition(loadingPeriodHolder.info.startPositionUs); enableRenderers(); playbackInfo = handlePositionDiscontinuity( playbackInfo.periodId, loadingPeriodHolder.info.startPositionUs, playbackInfo.requestedContentPositionUs, loadingPeriodHolder.info.startPositionUs, /* reportDiscontinuity= */ false, /* ignored */ Player.DISCONTINUITY_REASON_INTERNAL); } maybeContinueLoading(); } private void handleContinueLoadingRequested(MediaPeriod mediaPeriod) { if (!queue.isLoading(mediaPeriod)) { // Stale event. return; } queue.reevaluateBuffer(rendererPositionUs); maybeContinueLoading(); } private void handlePlaybackParameters( PlaybackParameters playbackParameters, boolean acknowledgeCommand) throws ExoPlaybackException { handlePlaybackParameters( playbackParameters, playbackParameters.speed, /* updatePlaybackInfo= */ true, acknowledgeCommand); } private void handlePlaybackParameters( PlaybackParameters playbackParameters, float currentPlaybackSpeed, boolean updatePlaybackInfo, boolean acknowledgeCommand) throws ExoPlaybackException { if (updatePlaybackInfo) { if (acknowledgeCommand) { playbackInfoUpdate.incrementPendingOperationAcks(1); } playbackInfo = playbackInfo.copyWithPlaybackParameters(playbackParameters); } updateTrackSelectionPlaybackSpeed(playbackParameters.speed); for (Renderer renderer : renderers) { if (renderer != null) { renderer.setPlaybackSpeed( currentPlaybackSpeed, /* targetPlaybackSpeed= */ playbackParameters.speed); } } } private void maybeContinueLoading() { shouldContinueLoading = shouldContinueLoading(); if (shouldContinueLoading) { queue.getLoadingPeriod().continueLoading(rendererPositionUs); } updateIsLoading(); } private boolean shouldContinueLoading() { if (!isLoadingPossible()) { return false; } MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); long bufferedDurationUs = getTotalBufferedDurationUs(loadingPeriodHolder.getNextLoadPositionUs()); long playbackPositionUs = loadingPeriodHolder == queue.getPlayingPeriod() ? loadingPeriodHolder.toPeriodTime(rendererPositionUs) : loadingPeriodHolder.toPeriodTime(rendererPositionUs) - loadingPeriodHolder.info.startPositionUs; return loadControl.shouldContinueLoading( playbackPositionUs, bufferedDurationUs, mediaClock.getPlaybackParameters().speed); } private boolean isLoadingPossible() { MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); if (loadingPeriodHolder == null) { return false; } long nextLoadPositionUs = loadingPeriodHolder.getNextLoadPositionUs(); if (nextLoadPositionUs == C.TIME_END_OF_SOURCE) { return false; } return true; } private void updateIsLoading() { MediaPeriodHolder loadingPeriod = queue.getLoadingPeriod(); boolean isLoading = shouldContinueLoading || (loadingPeriod != null && loadingPeriod.mediaPeriod.isLoading()); if (isLoading != playbackInfo.isLoading) { playbackInfo = playbackInfo.copyWithIsLoading(isLoading); } } @CheckResult private PlaybackInfo handlePositionDiscontinuity( MediaPeriodId mediaPeriodId, long positionUs, long contentPositionUs, long discontinuityStartPositionUs, boolean reportDiscontinuity, @DiscontinuityReason int discontinuityReason) { deliverPendingMessageAtStartPositionRequired = deliverPendingMessageAtStartPositionRequired || positionUs != playbackInfo.positionUs || !mediaPeriodId.equals(playbackInfo.periodId); resetPendingPauseAtEndOfPeriod(); TrackGroupArray trackGroupArray = playbackInfo.trackGroups; TrackSelectorResult trackSelectorResult = playbackInfo.trackSelectorResult; List<Metadata> staticMetadata = playbackInfo.staticMetadata; if (mediaSourceList.isPrepared()) { @Nullable MediaPeriodHolder playingPeriodHolder = queue.getPlayingPeriod(); trackGroupArray = playingPeriodHolder == null ? TrackGroupArray.EMPTY : playingPeriodHolder.getTrackGroups(); trackSelectorResult = playingPeriodHolder == null ? emptyTrackSelectorResult : playingPeriodHolder.getTrackSelectorResult(); staticMetadata = extractMetadataFromTrackSelectionArray(trackSelectorResult.selections); // Ensure the media period queue requested content position matches the new playback info. if (playingPeriodHolder != null && playingPeriodHolder.info.requestedContentPositionUs != contentPositionUs) { playingPeriodHolder.info = playingPeriodHolder.info.copyWithRequestedContentPositionUs(contentPositionUs); } } else if (!mediaPeriodId.equals(playbackInfo.periodId)) { // Reset previously kept track info if unprepared and the period changes. trackGroupArray = TrackGroupArray.EMPTY; trackSelectorResult = emptyTrackSelectorResult; staticMetadata = ImmutableList.of(); } if (reportDiscontinuity) { playbackInfoUpdate.setPositionDiscontinuity(discontinuityReason); } return playbackInfo.copyWithNewPosition( mediaPeriodId, positionUs, contentPositionUs, discontinuityStartPositionUs, getTotalBufferedDurationUs(), trackGroupArray, trackSelectorResult, staticMetadata); } private ImmutableList<Metadata> extractMetadataFromTrackSelectionArray( ExoTrackSelection[] trackSelections) { ImmutableList.Builder<Metadata> result = new ImmutableList.Builder<>(); boolean seenNonEmptyMetadata = false; for (ExoTrackSelection trackSelection : trackSelections) { if (trackSelection != null) { Format format = trackSelection.getFormat(/* index= */ 0); if (format.metadata == null) { result.add(new Metadata()); } else { result.add(format.metadata); seenNonEmptyMetadata = true; } } } return seenNonEmptyMetadata ? result.build() : ImmutableList.of(); } private void enableRenderers() throws ExoPlaybackException { enableRenderers(/* rendererWasEnabledFlags= */ new boolean[renderers.length]); } private void enableRenderers(boolean[] rendererWasEnabledFlags) throws ExoPlaybackException { MediaPeriodHolder readingMediaPeriod = queue.getReadingPeriod(); TrackSelectorResult trackSelectorResult = readingMediaPeriod.getTrackSelectorResult(); // Reset all disabled renderers before enabling any new ones. This makes sure resources released // by the disabled renderers will be available to renderers that are being enabled. for (int i = 0; i < renderers.length; i++) { if (!trackSelectorResult.isRendererEnabled(i)) { renderers[i].reset(); } } // Enable the renderers. for (int i = 0; i < renderers.length; i++) { if (trackSelectorResult.isRendererEnabled(i)) { enableRenderer(i, rendererWasEnabledFlags[i]); } } readingMediaPeriod.allRenderersInCorrectState = true; } private void enableRenderer(int rendererIndex, boolean wasRendererEnabled) throws ExoPlaybackException { Renderer renderer = renderers[rendererIndex]; if (isRendererEnabled(renderer)) { return; } MediaPeriodHolder periodHolder = queue.getReadingPeriod(); boolean mayRenderStartOfStream = periodHolder == queue.getPlayingPeriod(); TrackSelectorResult trackSelectorResult = periodHolder.getTrackSelectorResult(); RendererConfiguration rendererConfiguration = trackSelectorResult.rendererConfigurations[rendererIndex]; ExoTrackSelection newSelection = trackSelectorResult.selections[rendererIndex]; Format[] formats = getFormats(newSelection); // The renderer needs enabling with its new track selection. boolean playing = shouldPlayWhenReady() && playbackInfo.playbackState == Player.STATE_READY; // Consider as joining only if the renderer was previously disabled. boolean joining = !wasRendererEnabled && playing; // Enable the renderer. enabledRendererCount++; renderer.enable( rendererConfiguration, formats, periodHolder.sampleStreams[rendererIndex], rendererPositionUs, joining, mayRenderStartOfStream, periodHolder.getStartPositionRendererTime(), periodHolder.getRendererOffset()); renderer.handleMessage( Renderer.MSG_SET_WAKEUP_LISTENER, new Renderer.WakeupListener() { @Override public void onSleep(long wakeupDeadlineMs) { // Do not sleep if the expected sleep time is not long enough to save significant power. if (wakeupDeadlineMs >= MIN_RENDERER_SLEEP_DURATION_MS) { requestForRendererSleep = true; } } @Override public void onWakeup() { handler.sendEmptyMessage(MSG_DO_SOME_WORK); } }); mediaClock.onRendererEnabled(renderer); // Start the renderer if playing. if (playing) { renderer.start(); } } private void handleLoadingMediaPeriodChanged(boolean loadingTrackSelectionChanged) { MediaPeriodHolder loadingMediaPeriodHolder = queue.getLoadingPeriod(); MediaPeriodId loadingMediaPeriodId = loadingMediaPeriodHolder == null ? playbackInfo.periodId : loadingMediaPeriodHolder.info.id; boolean loadingMediaPeriodChanged = !playbackInfo.loadingMediaPeriodId.equals(loadingMediaPeriodId); if (loadingMediaPeriodChanged) { playbackInfo = playbackInfo.copyWithLoadingMediaPeriodId(loadingMediaPeriodId); } playbackInfo.bufferedPositionUs = loadingMediaPeriodHolder == null ? playbackInfo.positionUs : loadingMediaPeriodHolder.getBufferedPositionUs(); playbackInfo.totalBufferedDurationUs = getTotalBufferedDurationUs(); if ((loadingMediaPeriodChanged || loadingTrackSelectionChanged) && loadingMediaPeriodHolder != null && loadingMediaPeriodHolder.prepared) { updateLoadControlTrackSelection( loadingMediaPeriodHolder.getTrackGroups(), loadingMediaPeriodHolder.getTrackSelectorResult()); } } private long getTotalBufferedDurationUs() { return getTotalBufferedDurationUs(playbackInfo.bufferedPositionUs); } private long getTotalBufferedDurationUs(long bufferedPositionInLoadingPeriodUs) { MediaPeriodHolder loadingPeriodHolder = queue.getLoadingPeriod(); if (loadingPeriodHolder == null) { return 0; } long totalBufferedDurationUs = bufferedPositionInLoadingPeriodUs - loadingPeriodHolder.toPeriodTime(rendererPositionUs); return max(0, totalBufferedDurationUs); } private void updateLoadControlTrackSelection( TrackGroupArray trackGroups, TrackSelectorResult trackSelectorResult) { loadControl.onTracksSelected(renderers, trackGroups, trackSelectorResult.selections); } private boolean shouldPlayWhenReady() { return playbackInfo.playWhenReady && playbackInfo.playbackSuppressionReason == Player.PLAYBACK_SUPPRESSION_REASON_NONE; } private static PositionUpdateForPlaylistChange resolvePositionForPlaylistChange( Timeline timeline, PlaybackInfo playbackInfo, @Nullable SeekPosition pendingInitialSeekPosition, MediaPeriodQueue queue, @RepeatMode int repeatMode, boolean shuffleModeEnabled, Timeline.Window window, Timeline.Period period) { if (timeline.isEmpty()) { return new PositionUpdateForPlaylistChange( PlaybackInfo.getDummyPeriodForEmptyTimeline(), /* periodPositionUs= */ 0, /* requestedContentPositionUs= */ C.TIME_UNSET, /* forceBufferingState= */ false, /* endPlayback= */ true, /* setTargetLiveOffset= */ false); } MediaPeriodId oldPeriodId = playbackInfo.periodId; Object newPeriodUid = oldPeriodId.periodUid; boolean isUsingPlaceholderPeriod = isUsingPlaceholderPeriod(playbackInfo, period); long oldContentPositionUs = playbackInfo.periodId.isAd() || isUsingPlaceholderPeriod ? playbackInfo.requestedContentPositionUs : playbackInfo.positionUs; long newContentPositionUs = oldContentPositionUs; int startAtDefaultPositionWindowIndex = C.INDEX_UNSET; boolean forceBufferingState = false; boolean endPlayback = false; boolean setTargetLiveOffset = false; if (pendingInitialSeekPosition != null) { // Resolve initial seek position. @Nullable Pair<Object, Long> periodPosition = resolveSeekPosition( timeline, pendingInitialSeekPosition, /* trySubsequentPeriods= */ true, repeatMode, shuffleModeEnabled, window, period); if (periodPosition == null) { // The initial seek in the empty old timeline is invalid in the new timeline. endPlayback = true; startAtDefaultPositionWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); } else { // The pending seek has been resolved successfully in the new timeline. if (pendingInitialSeekPosition.windowPositionUs == C.TIME_UNSET) { startAtDefaultPositionWindowIndex = timeline.getPeriodByUid(periodPosition.first, period).windowIndex; } else { newPeriodUid = periodPosition.first; newContentPositionUs = periodPosition.second; // Use explicit initial seek as new target live offset. setTargetLiveOffset = true; } forceBufferingState = playbackInfo.playbackState == Player.STATE_ENDED; } } else if (playbackInfo.timeline.isEmpty()) { // Resolve to default position if the old timeline is empty and no seek is requested above. startAtDefaultPositionWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); } else if (timeline.getIndexOfPeriod(newPeriodUid) == C.INDEX_UNSET) { // The current period isn't in the new timeline. Attempt to resolve a subsequent period whose // window we can restart from. @Nullable Object subsequentPeriodUid = resolveSubsequentPeriod( window, period, repeatMode, shuffleModeEnabled, newPeriodUid, playbackInfo.timeline, timeline); if (subsequentPeriodUid == null) { // We failed to resolve a suitable restart position but the timeline is not empty. endPlayback = true; startAtDefaultPositionWindowIndex = timeline.getFirstWindowIndex(shuffleModeEnabled); } else { // We resolved a subsequent period. Start at the default position in the corresponding // window. startAtDefaultPositionWindowIndex = timeline.getPeriodByUid(subsequentPeriodUid, period).windowIndex; } } else if (oldContentPositionUs == C.TIME_UNSET) { // The content was requested to start from its default position and we haven't used the // resolved position yet. Re-resolve in case the default position changed. startAtDefaultPositionWindowIndex = timeline.getPeriodByUid(newPeriodUid, period).windowIndex; } else if (isUsingPlaceholderPeriod) { // We previously requested a content position for a placeholder period, but haven't used it // yet. Re-resolve the requested window position to the period position in case it changed. playbackInfo.timeline.getPeriodByUid(oldPeriodId.periodUid, period); if (playbackInfo.timeline.getWindow(period.windowIndex, window).firstPeriodIndex == playbackInfo.timeline.getIndexOfPeriod(oldPeriodId.periodUid)) { // Only need to resolve the first period in a window because subsequent periods must start // at position 0 and don't need to be resolved. long windowPositionUs = oldContentPositionUs + period.getPositionInWindowUs(); int windowIndex = timeline.getPeriodByUid(newPeriodUid, period).windowIndex; Pair<Object, Long> periodPosition = timeline.getPeriodPosition(window, period, windowIndex, windowPositionUs); newPeriodUid = periodPosition.first; newContentPositionUs = periodPosition.second; } // Use an explicitly requested content position as new target live offset. setTargetLiveOffset = true; } // Set period uid for default positions and resolve position for ad resolution. long contentPositionForAdResolutionUs = newContentPositionUs; if (startAtDefaultPositionWindowIndex != C.INDEX_UNSET) { Pair<Object, Long> defaultPosition = timeline.getPeriodPosition( window, period, startAtDefaultPositionWindowIndex, /* windowPositionUs= */ C.TIME_UNSET); newPeriodUid = defaultPosition.first; contentPositionForAdResolutionUs = defaultPosition.second; newContentPositionUs = C.TIME_UNSET; } // Ensure ad insertion metadata is up to date. MediaPeriodId periodIdWithAds = queue.resolveMediaPeriodIdForAds(timeline, newPeriodUid, contentPositionForAdResolutionUs); boolean earliestCuePointIsUnchangedOrLater = periodIdWithAds.nextAdGroupIndex == C.INDEX_UNSET || (oldPeriodId.nextAdGroupIndex != C.INDEX_UNSET && periodIdWithAds.adGroupIndex >= oldPeriodId.nextAdGroupIndex); // Drop update if we keep playing the same content (MediaPeriod.periodUid are identical) and // the only change is that MediaPeriodId.nextAdGroupIndex increased. This postpones a potential // discontinuity until we reach the former next ad group position. boolean sameOldAndNewPeriodUid = oldPeriodId.periodUid.equals(newPeriodUid); boolean onlyNextAdGroupIndexIncreased = sameOldAndNewPeriodUid && !oldPeriodId.isAd() && !periodIdWithAds.isAd() && earliestCuePointIsUnchangedOrLater; // Drop update if the change is from/to server-side inserted ads at the same content position to // avoid any unintentional renderer reset. timeline.getPeriodByUid(newPeriodUid, period); boolean isInStreamAdChange = sameOldAndNewPeriodUid && !isUsingPlaceholderPeriod && oldContentPositionUs == newContentPositionUs && ((periodIdWithAds.isAd() && period.isServerSideInsertedAdGroup(periodIdWithAds.adGroupIndex)) || (oldPeriodId.isAd() && period.isServerSideInsertedAdGroup(oldPeriodId.adGroupIndex))); MediaPeriodId newPeriodId = onlyNextAdGroupIndexIncreased || isInStreamAdChange ? oldPeriodId : periodIdWithAds; long periodPositionUs = contentPositionForAdResolutionUs; if (newPeriodId.isAd()) { if (newPeriodId.equals(oldPeriodId)) { periodPositionUs = playbackInfo.positionUs; } else { timeline.getPeriodByUid(newPeriodId.periodUid, period); periodPositionUs = newPeriodId.adIndexInAdGroup == period.getFirstAdIndexToPlay(newPeriodId.adGroupIndex) ? period.getAdResumePositionUs() : 0; } } return new PositionUpdateForPlaylistChange( newPeriodId, periodPositionUs, newContentPositionUs, forceBufferingState, endPlayback, setTargetLiveOffset); } private static boolean isUsingPlaceholderPeriod( PlaybackInfo playbackInfo, Timeline.Period period) { MediaPeriodId periodId = playbackInfo.periodId; Timeline timeline = playbackInfo.timeline; return timeline.isEmpty() || timeline.getPeriodByUid(periodId.periodUid, period).isPlaceholder; } /** * Updates pending message to a new timeline. * * @param pendingMessageInfo The pending message. * @param newTimeline The new timeline. * @param previousTimeline The previous timeline used to set the message positions. * @param repeatMode The current repeat mode. * @param shuffleModeEnabled The current shuffle mode. * @param window A scratch window. * @param period A scratch period. * @return Whether the message position could be resolved to the current timeline. */ private static boolean resolvePendingMessagePosition( PendingMessageInfo pendingMessageInfo, Timeline newTimeline, Timeline previousTimeline, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled, Timeline.Window window, Timeline.Period period) { if (pendingMessageInfo.resolvedPeriodUid == null) { // Position is still unresolved. Try to find window in new timeline. long requestPositionUs = pendingMessageInfo.message.getPositionMs() == C.TIME_END_OF_SOURCE ? C.TIME_UNSET : C.msToUs(pendingMessageInfo.message.getPositionMs()); @Nullable Pair<Object, Long> periodPosition = resolveSeekPosition( newTimeline, new SeekPosition( pendingMessageInfo.message.getTimeline(), pendingMessageInfo.message.getWindowIndex(), requestPositionUs), /* trySubsequentPeriods= */ false, repeatMode, shuffleModeEnabled, window, period); if (periodPosition == null) { return false; } pendingMessageInfo.setResolvedPosition( /* periodIndex= */ newTimeline.getIndexOfPeriod(periodPosition.first), /* periodTimeUs= */ periodPosition.second, /* periodUid= */ periodPosition.first); if (pendingMessageInfo.message.getPositionMs() == C.TIME_END_OF_SOURCE) { resolvePendingMessageEndOfStreamPosition(newTimeline, pendingMessageInfo, window, period); } return true; } // Position has been resolved for a previous timeline. Try to find the updated period index. int index = newTimeline.getIndexOfPeriod(pendingMessageInfo.resolvedPeriodUid); if (index == C.INDEX_UNSET) { return false; } if (pendingMessageInfo.message.getPositionMs() == C.TIME_END_OF_SOURCE) { // Re-resolve end of stream in case the duration changed. resolvePendingMessageEndOfStreamPosition(newTimeline, pendingMessageInfo, window, period); return true; } pendingMessageInfo.resolvedPeriodIndex = index; previousTimeline.getPeriodByUid(pendingMessageInfo.resolvedPeriodUid, period); if (period.isPlaceholder && previousTimeline.getWindow(period.windowIndex, window).firstPeriodIndex == previousTimeline.getIndexOfPeriod(pendingMessageInfo.resolvedPeriodUid)) { // The position needs to be re-resolved because the window in the previous timeline wasn't // fully prepared. Only resolve the first period in a window because subsequent periods must // start at position 0 and don't need to be resolved. long windowPositionUs = pendingMessageInfo.resolvedPeriodTimeUs + period.getPositionInWindowUs(); int windowIndex = newTimeline.getPeriodByUid(pendingMessageInfo.resolvedPeriodUid, period).windowIndex; Pair<Object, Long> periodPosition = newTimeline.getPeriodPosition(window, period, windowIndex, windowPositionUs); pendingMessageInfo.setResolvedPosition( /* periodIndex= */ newTimeline.getIndexOfPeriod(periodPosition.first), /* periodTimeUs= */ periodPosition.second, /* periodUid= */ periodPosition.first); } return true; } private static void resolvePendingMessageEndOfStreamPosition( Timeline timeline, PendingMessageInfo messageInfo, Timeline.Window window, Timeline.Period period) { int windowIndex = timeline.getPeriodByUid(messageInfo.resolvedPeriodUid, period).windowIndex; int lastPeriodIndex = timeline.getWindow(windowIndex, window).lastPeriodIndex; Object lastPeriodUid = timeline.getPeriod(lastPeriodIndex, period, /* setIds= */ true).uid; long positionUs = period.durationUs != C.TIME_UNSET ? period.durationUs - 1 : Long.MAX_VALUE; messageInfo.setResolvedPosition(lastPeriodIndex, positionUs, lastPeriodUid); } /** * Converts a {@link SeekPosition} into the corresponding (periodUid, periodPositionUs) for the * internal timeline. * * @param seekPosition The position to resolve. * @param trySubsequentPeriods Whether the position can be resolved to a subsequent matching * period if the original period is no longer available. * @return The resolved position, or null if resolution was not successful. * @throws IllegalSeekPositionException If the window index of the seek position is outside the * bounds of the timeline. */ @Nullable private static Pair<Object, Long> resolveSeekPosition( Timeline timeline, SeekPosition seekPosition, boolean trySubsequentPeriods, @RepeatMode int repeatMode, boolean shuffleModeEnabled, Timeline.Window window, Timeline.Period period) { Timeline seekTimeline = seekPosition.timeline; if (timeline.isEmpty()) { // We don't have a valid timeline yet, so we can't resolve the position. return null; } if (seekTimeline.isEmpty()) { // The application performed a blind seek with an empty timeline (most likely based on // knowledge of what the future timeline will be). Use the internal timeline. seekTimeline = timeline; } // Map the SeekPosition to a position in the corresponding timeline. Pair<Object, Long> periodPosition; try { periodPosition = seekTimeline.getPeriodPosition( window, period, seekPosition.windowIndex, seekPosition.windowPositionUs); } catch (IndexOutOfBoundsException e) { // The window index of the seek position was outside the bounds of the timeline. return null; } if (timeline.equals(seekTimeline)) { // Our internal timeline is the seek timeline, so the mapped position is correct. return periodPosition; } // Attempt to find the mapped period in the internal timeline. int periodIndex = timeline.getIndexOfPeriod(periodPosition.first); if (periodIndex != C.INDEX_UNSET) { // We successfully located the period in the internal timeline. if (seekTimeline.getPeriodByUid(periodPosition.first, period).isPlaceholder && seekTimeline.getWindow(period.windowIndex, window).firstPeriodIndex == seekTimeline.getIndexOfPeriod(periodPosition.first)) { // The seek timeline was using a placeholder, so we need to re-resolve using the updated // timeline in case the resolved position changed. Only resolve the first period in a window // because subsequent periods must start at position 0 and don't need to be resolved. int newWindowIndex = timeline.getPeriodByUid(periodPosition.first, period).windowIndex; periodPosition = timeline.getPeriodPosition( window, period, newWindowIndex, seekPosition.windowPositionUs); } return periodPosition; } if (trySubsequentPeriods) { // Try and find a subsequent period from the seek timeline in the internal timeline. @Nullable Object periodUid = resolveSubsequentPeriod( window, period, repeatMode, shuffleModeEnabled, periodPosition.first, seekTimeline, timeline); if (periodUid != null) { // We found one. Use the default position of the corresponding window. return timeline.getPeriodPosition( window, period, timeline.getPeriodByUid(periodUid, period).windowIndex, /* windowPositionUs= */ C.TIME_UNSET); } } // We didn't find one. Give up. return null; } /** * Given a period index into an old timeline, finds the first subsequent period that also exists * in a new timeline. The uid of this period in the new timeline is returned. * * @param window A {@link Timeline.Window} to be used internally. * @param period A {@link Timeline.Period} to be used internally. * @param repeatMode The repeat mode to use. * @param shuffleModeEnabled Whether the shuffle mode is enabled. * @param oldPeriodUid The index of the period in the old timeline. * @param oldTimeline The old timeline. * @param newTimeline The new timeline. * @return The uid in the new timeline of the first subsequent period, or null if no such period * was found. */ /* package */ static @Nullable Object resolveSubsequentPeriod( Timeline.Window window, Timeline.Period period, @Player.RepeatMode int repeatMode, boolean shuffleModeEnabled, Object oldPeriodUid, Timeline oldTimeline, Timeline newTimeline) { int oldPeriodIndex = oldTimeline.getIndexOfPeriod(oldPeriodUid); int newPeriodIndex = C.INDEX_UNSET; int maxIterations = oldTimeline.getPeriodCount(); for (int i = 0; i < maxIterations && newPeriodIndex == C.INDEX_UNSET; i++) { oldPeriodIndex = oldTimeline.getNextPeriodIndex( oldPeriodIndex, period, window, repeatMode, shuffleModeEnabled); if (oldPeriodIndex == C.INDEX_UNSET) { // We've reached the end of the old timeline. break; } newPeriodIndex = newTimeline.getIndexOfPeriod(oldTimeline.getUidOfPeriod(oldPeriodIndex)); } return newPeriodIndex == C.INDEX_UNSET ? null : newTimeline.getUidOfPeriod(newPeriodIndex); } private static Format[] getFormats(ExoTrackSelection newSelection) { // Build an array of formats contained by the selection. int length = newSelection != null ? newSelection.length() : 0; Format[] formats = new Format[length]; for (int i = 0; i < length; i++) { formats[i] = newSelection.getFormat(i); } return formats; } private static boolean isRendererEnabled(Renderer renderer) { return renderer.getState() != Renderer.STATE_DISABLED; } private static final class SeekPosition { public final Timeline timeline; public final int windowIndex; public final long windowPositionUs; public SeekPosition(Timeline timeline, int windowIndex, long windowPositionUs) { this.timeline = timeline; this.windowIndex = windowIndex; this.windowPositionUs = windowPositionUs; } } private static final class PositionUpdateForPlaylistChange { public final MediaPeriodId periodId; public final long periodPositionUs; public final long requestedContentPositionUs; public final boolean forceBufferingState; public final boolean endPlayback; public final boolean setTargetLiveOffset; public PositionUpdateForPlaylistChange( MediaPeriodId periodId, long periodPositionUs, long requestedContentPositionUs, boolean forceBufferingState, boolean endPlayback, boolean setTargetLiveOffset) { this.periodId = periodId; this.periodPositionUs = periodPositionUs; this.requestedContentPositionUs = requestedContentPositionUs; this.forceBufferingState = forceBufferingState; this.endPlayback = endPlayback; this.setTargetLiveOffset = setTargetLiveOffset; } } private static final class PendingMessageInfo implements Comparable<PendingMessageInfo> { public final PlayerMessage message; public int resolvedPeriodIndex; public long resolvedPeriodTimeUs; @Nullable public Object resolvedPeriodUid; public PendingMessageInfo(PlayerMessage message) { this.message = message; } public void setResolvedPosition(int periodIndex, long periodTimeUs, Object periodUid) { resolvedPeriodIndex = periodIndex; resolvedPeriodTimeUs = periodTimeUs; resolvedPeriodUid = periodUid; } @Override public int compareTo(PendingMessageInfo other) { if ((resolvedPeriodUid == null) != (other.resolvedPeriodUid == null)) { // PendingMessageInfos with a resolved period position are always smaller. return resolvedPeriodUid != null ? -1 : 1; } if (resolvedPeriodUid == null) { // Don't sort message with unresolved positions. return 0; } // Sort resolved media times by period index and then by period position. int comparePeriodIndex = resolvedPeriodIndex - other.resolvedPeriodIndex; if (comparePeriodIndex != 0) { return comparePeriodIndex; } return Util.compareLong(resolvedPeriodTimeUs, other.resolvedPeriodTimeUs); } } private static final class MediaSourceListUpdateMessage { private final List<MediaSourceList.MediaSourceHolder> mediaSourceHolders; private final ShuffleOrder shuffleOrder; private final int windowIndex; private final long positionUs; private MediaSourceListUpdateMessage( List<MediaSourceList.MediaSourceHolder> mediaSourceHolders, ShuffleOrder shuffleOrder, int windowIndex, long positionUs) { this.mediaSourceHolders = mediaSourceHolders; this.shuffleOrder = shuffleOrder; this.windowIndex = windowIndex; this.positionUs = positionUs; } } private static class MoveMediaItemsMessage { public final int fromIndex; public final int toIndex; public final int newFromIndex; public final ShuffleOrder shuffleOrder; public MoveMediaItemsMessage( int fromIndex, int toIndex, int newFromIndex, ShuffleOrder shuffleOrder) { this.fromIndex = fromIndex; this.toIndex = toIndex; this.newFromIndex = newFromIndex; this.shuffleOrder = shuffleOrder; } } @RequiresApi(18) private static final class PlaformOperationsWrapperV18 { @DoNotInline public static boolean isNotProvisionedException(@Nullable Throwable throwable) { return throwable instanceof NotProvisionedException; } @DoNotInline public static boolean isDeniedByServerException(@Nullable Throwable throwable) { return throwable instanceof DeniedByServerException; } } @RequiresApi(21) private static final class PlatformOperationsWrapperV21 { @DoNotInline public static boolean isPermissionError(@Nullable Throwable e) { return e instanceof ErrnoException && ((ErrnoException) e).errno == OsConstants.EACCES; } @DoNotInline public static boolean isMediaDrmStateException(@Nullable Throwable throwable) { return throwable instanceof MediaDrm.MediaDrmStateException; } @DoNotInline public static int mediaDrmStateExceptionToErrorCode(Throwable throwable) { @Nullable String diagnosticsInfo = ((MediaDrm.MediaDrmStateException) throwable).getDiagnosticInfo(); return Util.getErrorCodeFromPlatformDiagnosticsInfo(diagnosticsInfo); } } @RequiresApi(23) private static final class PlaformOperationsWrapperV23 { @DoNotInline public static boolean isMediaDrmResetException(@Nullable Throwable throwable) { return throwable instanceof MediaDrmResetException; } } }
Fix typo in internal class name PiperOrigin-RevId: 382766969
library/core/src/main/java/com/google/android/exoplayer2/ExoPlayerImplInternal.java
Fix typo in internal class name
<ide><path>ibrary/core/src/main/java/com/google/android/exoplayer2/ExoPlayerImplInternal.java <ide> if (Util.SDK_INT >= 21 && PlatformOperationsWrapperV21.isMediaDrmStateException(cause)) { <ide> errorCode = PlatformOperationsWrapperV21.mediaDrmStateExceptionToErrorCode(cause); <ide> } else if (Util.SDK_INT >= 23 <del> && PlaformOperationsWrapperV23.isMediaDrmResetException(cause)) { <add> && PlatformOperationsWrapperV23.isMediaDrmResetException(cause)) { <ide> errorCode = PlaybackException.ERROR_CODE_DRM_SYSTEM_ERROR; <ide> } else if (Util.SDK_INT >= 18 <del> && PlaformOperationsWrapperV18.isNotProvisionedException(cause)) { <add> && PlatformOperationsWrapperV18.isNotProvisionedException(cause)) { <ide> errorCode = PlaybackException.ERROR_CODE_DRM_PROVISIONING_FAILED; <ide> } else if (Util.SDK_INT >= 18 <del> && PlaformOperationsWrapperV18.isDeniedByServerException(cause)) { <add> && PlatformOperationsWrapperV18.isDeniedByServerException(cause)) { <ide> errorCode = PlaybackException.ERROR_CODE_DRM_DEVICE_REVOKED; <ide> } else if (cause instanceof UnsupportedDrmException) { <ide> errorCode = PlaybackException.ERROR_CODE_DRM_SCHEME_UNSUPPORTED; <ide> } <ide> <ide> @RequiresApi(18) <del> private static final class PlaformOperationsWrapperV18 { <add> private static final class PlatformOperationsWrapperV18 { <ide> <ide> @DoNotInline <ide> public static boolean isNotProvisionedException(@Nullable Throwable throwable) { <ide> } <ide> <ide> @RequiresApi(23) <del> private static final class PlaformOperationsWrapperV23 { <add> private static final class PlatformOperationsWrapperV23 { <ide> <ide> @DoNotInline <ide> public static boolean isMediaDrmResetException(@Nullable Throwable throwable) {
Java
artistic-2.0
fb2600066f482409a6512405d91e9b2b3dc1bee7
0
jdownloader-mirror/appwork-utils
package org.appwork.swing.synthetica; import java.awt.Font; import java.io.UnsupportedEncodingException; import javax.swing.UIManager; import org.appwork.storage.config.JsonConfig; import org.appwork.swing.components.ExtPasswordField; import org.appwork.txtresource.TranslationFactory; import org.appwork.utils.logging.Log; import org.appwork.utils.os.CrossSystem; public class SyntheticaHelper { /** * @throws UnsupportedEncodingException * */ public static void init() throws UnsupportedEncodingException { init("de.javasoft.plaf.synthetica.SyntheticaSimple2DLookAndFeel"); } public static int getFontScaleFaktor(final SyntheticaSettings config, final LanguageFileSetup translationFileConfig) { int fontScale = -1; try { fontScale = Integer.parseInt(translationFileConfig.config_fontscale_faktor()); } catch (final Exception e) { } if (config.getFontScaleFactor() != 100 || fontScale <= 0) { fontScale = config.getFontScaleFactor(); } return fontScale; } /** * @param string * @throws UnsupportedEncodingException */ public static void init(final String laf) throws UnsupportedEncodingException { final long start = System.currentTimeMillis(); try { final LanguageFileSetup locale = TranslationFactory.create(LanguageFileSetup.class); final SyntheticaSettings config = JsonConfig.create(SyntheticaSettings.class); de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setWindowsDecorated(false); // final HashMap<String, String> dummy = new HashMap<String, // String>(); // dummy.put("defaultlaf","BlaBlaLeberLAF"); // AppContext.getAppContext().put("swing.lafdata", dummy); UIManager.put("Synthetica.window.decoration", false); UIManager.put("Synthetica.text.antialias", config.isTextAntiAliasEnabled()); UIManager.put("Synthetica.extendedFileChooser.rememberPreferences", Boolean.FALSE); UIManager.put("Synthetica.extendedFileChooser.rememberLastDirectory", Boolean.FALSE); // /* http://www.jyloo.com/news/?pubId=1297681728000 */ // /* we want our own FontScaling, not SystemDPI */ UIManager.put("Synthetica.font.respectSystemDPI", config.isFontRespectsSystemDPI()); final int fontScale = getFontScaleFaktor(config, locale); UIManager.put("Synthetica.font.scaleFactor", fontScale); if (config.isFontRespectsSystemDPI() && fontScale != 100) { Log.L.warning("SystemDPI might interfere with JD's FontScaling"); } UIManager.put("Synthetica.animation.enabled", config.isAnimationEnabled()); if (CrossSystem.isWindows()) { /* only windows opaque works fine */ UIManager.put("Synthetica.window.opaque", config.isWindowOpaque()); } else { /* must be true to disable it..strange world ;) */ UIManager.put("Synthetica.window.opaque", true); } /* * NOTE: This Licensee Information may only be used by AppWork UG. * If you like to create derived creation based on this sourcecode, * you have to remove this license key. Instead you may use the FREE * Version of synthetica found on javasoft.de */ /* we save around x-400 ms here by not using AES */ final String key = new String(new byte[] { 67, 49, 52, 49, 48, 50, 57, 52, 45, 54, 49, 66, 54, 52, 65, 65, 67, 45, 52, 66, 55, 68, 51, 48, 51, 57, 45, 56, 51, 52, 65, 56, 50, 65, 49, 45, 51, 55, 69, 53, 68, 54, 57, 53 }, "UTF-8"); if (key != null) { final String[] li = { "Licensee=AppWork UG", "LicenseRegistrationNumber=289416475", "Product=Synthetica", "LicenseType=Small Business License", "ExpireDate=--.--.----", "MaxVersion=2.999.999" }; UIManager.put("Synthetica.license.info", li); UIManager.put("Synthetica.license.key", key); } de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setLookAndFeel(laf); de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setExtendedFileChooserEnabled(false); final String fontName = getFontName(config, locale); int fontSize = de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.getFont().getSize(); fontSize = (fontScale * fontSize) / 100; if (fontName != null) { /* change Font */ final int oldStyle = de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.getFont().getStyle(); final Font newFont = new Font(fontName, oldStyle, fontSize); de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setFont(newFont, false); } UIManager.put("ExtTable.SuggestedFontHeight", fontSize); ExtPasswordField.MASK = "*******"; } finally { final long time = System.currentTimeMillis() - start; Log.L.info("LAF Init duration: " + time + "ms"); } } /** * @param config * @param locale * @return */ public static String getFontName(final SyntheticaSettings config, final LanguageFileSetup locale) { final String fontName = config.getFontName(); final String fontFromTranslation = locale.config_fontname(); String newFontName = null; if (fontFromTranslation != null && !"default".equalsIgnoreCase(fontFromTranslation)) { /* we have customized fontName in translation */ /* lower priority than fontName in settings */ newFontName = fontFromTranslation; } if (fontName != null && !"default".equalsIgnoreCase(fontName)) { /* we have customized fontName in settings, it has highest priority */ newFontName = fontName; } if (newFontName == null) { newFontName = getDefaultFont(); } return newFontName; } public static String getDefaultFont() { switch (CrossSystem.OS_ID) { case CrossSystem.OS_WINDOWS_7: case CrossSystem.OS_WINDOWS_8: case CrossSystem.OS_WINDOWS_VISTA: return "Segoe UI"; } return null; } }
src/org/appwork/swing/synthetica/SyntheticaHelper.java
package org.appwork.swing.synthetica; import java.awt.Font; import java.io.UnsupportedEncodingException; import javax.swing.UIManager; import org.appwork.storage.config.JsonConfig; import org.appwork.swing.components.ExtPasswordField; import org.appwork.txtresource.TranslationFactory; import org.appwork.utils.logging.Log; import org.appwork.utils.os.CrossSystem; public class SyntheticaHelper { /** * @throws UnsupportedEncodingException * */ public static void init() throws UnsupportedEncodingException { init("de.javasoft.plaf.synthetica.SyntheticaSimple2DLookAndFeel"); } public static int getFontScaleFaktor(final SyntheticaSettings config, final LanguageFileSetup translationFileConfig) { int fontScale = -1; try { fontScale = Integer.parseInt(translationFileConfig.config_fontscale_faktor()); } catch (final Exception e) { } if (config.getFontScaleFactor() != 100 || fontScale <= 0) { fontScale = config.getFontScaleFactor(); } return fontScale; } /** * @param string * @throws UnsupportedEncodingException */ public static void init(final String laf) throws UnsupportedEncodingException { final long start = System.currentTimeMillis(); try { final LanguageFileSetup locale = TranslationFactory.create(LanguageFileSetup.class); final SyntheticaSettings config = JsonConfig.create(SyntheticaSettings.class); de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setWindowsDecorated(false); // final HashMap<String, String> dummy = new HashMap<String, // String>(); // dummy.put("defaultlaf","BlaBlaLeberLAF"); // AppContext.getAppContext().put("swing.lafdata", dummy); UIManager.put("Synthetica.window.decoration", false); UIManager.put("Synthetica.text.antialias", config.isTextAntiAliasEnabled()); UIManager.put("Synthetica.extendedFileChooser.rememberPreferences", Boolean.FALSE); UIManager.put("Synthetica.extendedFileChooser.rememberLastDirectory", Boolean.FALSE); // /* http://www.jyloo.com/news/?pubId=1297681728000 */ // /* we want our own FontScaling, not SystemDPI */ UIManager.put("Synthetica.font.respectSystemDPI", config.isFontRespectsSystemDPI()); final int fontScale = getFontScaleFaktor(config, locale); UIManager.put("Synthetica.font.scaleFactor", fontScale); if (config.isFontRespectsSystemDPI() && fontScale != 100) { Log.L.warning("SystemDPI might interfere with JD's FontScaling"); } UIManager.put("Synthetica.animation.enabled", config.isAnimationEnabled()); if (CrossSystem.isWindows()) { /* only windows opaque works fine */ UIManager.put("Synthetica.window.opaque", config.isWindowOpaque()); } else { /* must be true to disable it..strange world ;) */ UIManager.put("Synthetica.window.opaque", true); } /* * NOTE: This Licensee Information may only be used by AppWork UG. * If you like to create derived creation based on this sourcecode, * you have to remove this license key. Instead you may use the FREE * Version of synthetica found on javasoft.de */ /* we save around x-400 ms here by not using AES */ final String key = new String(new byte[] { 67, 49, 52, 49, 48, 50, 57, 52, 45, 54, 49, 66, 54, 52, 65, 65, 67, 45, 52, 66, 55, 68, 51, 48, 51, 57, 45, 56, 51, 52, 65, 56, 50, 65, 49, 45, 51, 55, 69, 53, 68, 54, 57, 53 }, "UTF-8"); if (key != null) { final String[] li = { "Licensee=AppWork UG", "LicenseRegistrationNumber=289416475", "Product=Synthetica", "LicenseType=Small Business License", "ExpireDate=--.--.----", "MaxVersion=2.999.999" }; UIManager.put("Synthetica.license.info", li); UIManager.put("Synthetica.license.key", key); } de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setLookAndFeel(laf); de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setExtendedFileChooserEnabled(false); final String fontName = getFontName(config, locale); int fontSize = de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.getFont().getSize(); fontSize = (fontScale * fontSize) / 100; if (fontName != null) { /* change Font */ final int oldStyle = de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.getFont().getStyle(); final Font newFont = new Font(fontName, oldStyle, fontSize); de.javasoft.plaf.synthetica.SyntheticaLookAndFeel.setFont(newFont, false); } UIManager.put("ExtTable.SuggestedFontHeight", fontSize); ExtPasswordField.MASK = "*******"; } finally { final long time = System.currentTimeMillis() - start; Log.L.info("LAF Init duration: " + time + "ms"); } } /** * @param config * @param locale * @return */ private static String getFontName(final SyntheticaSettings config, final LanguageFileSetup locale) { final String fontName = config.getFontName(); final String fontFromTranslation = locale.config_fontname(); String newFontName = null; if (fontFromTranslation != null && !"default".equalsIgnoreCase(fontFromTranslation)) { /* we have customized fontName in translation */ /* lower priority than fontName in settings */ newFontName = fontFromTranslation; } if (fontName != null && !"default".equalsIgnoreCase(fontName)) { /* we have customized fontName in settings, it has highest priority */ newFontName = fontName; } if (newFontName == null) { switch (CrossSystem.OS_ID) { case CrossSystem.OS_WINDOWS_7: case CrossSystem.OS_WINDOWS_8: case CrossSystem.OS_WINDOWS_VISTA: return "Segoe UI"; } } return newFontName; } }
build>full
src/org/appwork/swing/synthetica/SyntheticaHelper.java
build>full
<ide><path>rc/org/appwork/swing/synthetica/SyntheticaHelper.java <ide> * @param locale <ide> * @return <ide> */ <del> private static String getFontName(final SyntheticaSettings config, final LanguageFileSetup locale) { <add> public static String getFontName(final SyntheticaSettings config, final LanguageFileSetup locale) { <ide> final String fontName = config.getFontName(); <ide> <ide> final String fontFromTranslation = locale.config_fontname(); <ide> newFontName = fontName; <ide> } <ide> if (newFontName == null) { <del> switch (CrossSystem.OS_ID) { <del> case CrossSystem.OS_WINDOWS_7: <del> case CrossSystem.OS_WINDOWS_8: <del> case CrossSystem.OS_WINDOWS_VISTA: <del> return "Segoe UI"; <del> } <add> newFontName = getDefaultFont(); <ide> } <ide> return newFontName; <ide> } <ide> <add> public static String getDefaultFont() { <add> switch (CrossSystem.OS_ID) { <add> case CrossSystem.OS_WINDOWS_7: <add> case CrossSystem.OS_WINDOWS_8: <add> case CrossSystem.OS_WINDOWS_VISTA: <add> return "Segoe UI"; <add> } <add> <add> return null; <add> } <add> <ide> }
JavaScript
mit
a65113944eadc90972d753a21b6e1bae95a4ba36
0
jfilter/frag-den-staat-app,jfilter/frag-den-staat-app,jfilter/frag-den-staat-app,jfilter/frag-den-staat-app
import { AppRegistry } from 'react-native'; import App from './app/App'; console.disableYellowBox = true; AppRegistry.registerComponent('FragDenStaat', () => App);
index.ios.js
import { AppRegistry } from 'react-native'; import App from './app/App'; AppRegistry.registerComponent('FragDenStaat', () => App);
disable in-app warnings
index.ios.js
disable in-app warnings
<ide><path>ndex.ios.js <ide> import { AppRegistry } from 'react-native'; <ide> import App from './app/App'; <ide> <add>console.disableYellowBox = true; <add> <add> <ide> AppRegistry.registerComponent('FragDenStaat', () => App);
Java
apache-2.0
c7e05865765deee0eb8dc3bb80962a2375d7c942
0
da1z/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,adedayo/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,asedunov/intellij-community,semonte/intellij-community,jagguli/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,allotria/intellij-community,slisson/intellij-community,apixandru/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,apixandru/intellij-community,hurricup/intellij-community,amith01994/intellij-community,consulo/consulo,slisson/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,supersven/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,blademainer/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,ivan-fedorov/intellij-community,kdwink/intellij-community,slisson/intellij-community,izonder/intellij-community,consulo/consulo,michaelgallacher/intellij-community,caot/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,slisson/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,fnouama/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,robovm/robovm-studio,semonte/intellij-community,hurricup/intellij-community,signed/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,clumsy/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,amith01994/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,fitermay/intellij-community,asedunov/intellij-community,FHannes/intellij-community,apixandru/intellij-community,samthor/intellij-community,izonder/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,amith01994/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,fnouama/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,vladmm/intellij-community,slisson/intellij-community,holmes/intellij-community,asedunov/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,slisson/intellij-community,clumsy/intellij-community,vladmm/intellij-community,samthor/intellij-community,orekyuu/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,slisson/intellij-community,allotria/intellij-community,supersven/intellij-community,robovm/robovm-studio,fnouama/intellij-community,ahb0327/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,semonte/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,semonte/intellij-community,signed/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,ftomassetti/intellij-community,kool79/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,da1z/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,retomerz/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,ibinti/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,FHannes/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,petteyg/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,clumsy/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,signed/intellij-community,ryano144/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,da1z/intellij-community,robovm/robovm-studio,clumsy/intellij-community,da1z/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,robovm/robovm-studio,adedayo/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,kool79/intellij-community,ernestp/consulo,youdonghai/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,semonte/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,ibinti/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,hurricup/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,fnouama/intellij-community,jagguli/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,alphafoobar/intellij-community,da1z/intellij-community,adedayo/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,consulo/consulo,MER-GROUP/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,retomerz/intellij-community,da1z/intellij-community,vladmm/intellij-community,petteyg/intellij-community,orekyuu/intellij-community,petteyg/intellij-community,hurricup/intellij-community,robovm/robovm-studio,signed/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,samthor/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,slisson/intellij-community,caot/intellij-community,akosyakov/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,izonder/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,izonder/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,amith01994/intellij-community,diorcety/intellij-community,fitermay/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,izonder/intellij-community,da1z/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,consulo/consulo,wreckJ/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,samthor/intellij-community,consulo/consulo,blademainer/intellij-community,ibinti/intellij-community,diorcety/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,slisson/intellij-community,ernestp/consulo,ryano144/intellij-community,diorcety/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,ryano144/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,retomerz/intellij-community,kdwink/intellij-community,clumsy/intellij-community,petteyg/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,jagguli/intellij-community,holmes/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,allotria/intellij-community,xfournet/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,allotria/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,petteyg/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,xfournet/intellij-community,kool79/intellij-community,da1z/intellij-community,fnouama/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,FHannes/intellij-community,kdwink/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,kool79/intellij-community,blademainer/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,ryano144/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,orekyuu/intellij-community,semonte/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,vladmm/intellij-community,jagguli/intellij-community,da1z/intellij-community,consulo/consulo,alphafoobar/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,adedayo/intellij-community,pwoodworth/intellij-community,Distrotech/intellij-community,signed/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,caot/intellij-community,xfournet/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,signed/intellij-community,izonder/intellij-community,retomerz/intellij-community,ryano144/intellij-community,asedunov/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,jagguli/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,ryano144/intellij-community,caot/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,asedunov/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,holmes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,izonder/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,dslomov/intellij-community,fitermay/intellij-community,xfournet/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,FHannes/intellij-community,caot/intellij-community,da1z/intellij-community,caot/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,retomerz/intellij-community,samthor/intellij-community,adedayo/intellij-community,asedunov/intellij-community,kdwink/intellij-community,FHannes/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,xfournet/intellij-community,kdwink/intellij-community,fnouama/intellij-community,samthor/intellij-community,kool79/intellij-community,ernestp/consulo,ol-loginov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,supersven/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,hurricup/intellij-community,fitermay/intellij-community,supersven/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,diorcety/intellij-community,allotria/intellij-community,semonte/intellij-community,caot/intellij-community,semonte/intellij-community,signed/intellij-community,da1z/intellij-community,fitermay/intellij-community,supersven/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,semonte/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,kdwink/intellij-community,fitermay/intellij-community,izonder/intellij-community,allotria/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,blademainer/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ernestp/consulo,amith01994/intellij-community,vladmm/intellij-community,muntasirsyed/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,izonder/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,asedunov/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,dslomov/intellij-community,fitermay/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,semonte/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,fnouama/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,xfournet/intellij-community,izonder/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,apixandru/intellij-community
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.dsl; import com.intellij.notification.*; import com.intellij.notification.impl.NotificationsConfigurationImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileAdapter; import com.intellij.openapi.vfs.VirtualFileEvent; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.FileAttribute; import com.intellij.psi.*; import com.intellij.psi.impl.PsiModificationTrackerImpl; import com.intellij.psi.scope.DelegatingScopeProcessor; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.ExceptionUtil; import com.intellij.util.PathUtil; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.containers.ConcurrentMultiMap; import com.intellij.util.containers.MultiMap; import com.intellij.util.indexing.*; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.annotator.GroovyFrameworkConfigNotification; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import javax.swing.event.HyperlinkEvent; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author peter */ public class GroovyDslFileIndex extends ScalarIndexExtension<String> { private static final Key<Pair<GroovyDslExecutor, Long>> CACHED_EXECUTOR = Key.create("CachedGdslExecutor"); private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.dsl.GroovyDslFileIndex"); private static final FileAttribute ENABLED = new FileAttribute("ENABLED", 0); @NonNls public static final ID<String, Void> NAME = ID.create("GroovyDslFileIndex"); @NonNls private static final String OUR_KEY = "ourKey"; public static final String MODIFIED = "Modified"; public static final NotificationGroup NOTIFICATION_GROUP = new NotificationGroup("Groovy DSL errors", NotificationDisplayType.BALLOON, true); private final MyDataIndexer myDataIndexer = new MyDataIndexer(); private final MyInputFilter myInputFilter = new MyInputFilter(); private static final MultiMap<String, LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>>> filesInProcessing = new ConcurrentMultiMap<String, LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>>>(); private static final ThreadPoolExecutor ourPool = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "Groovy DSL File Index Executor"); } }); private final EnumeratorStringDescriptor myKeyDescriptor = new EnumeratorStringDescriptor(); private static final byte[] ENABLED_FLAG = new byte[]{(byte)239}; static { NotificationsConfigurationImpl.remove("Groovy DSL parsing"); } public GroovyDslFileIndex() { VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() { @Override public void contentsChanged(VirtualFileEvent event) { if (event.getFileName().endsWith(".gdsl")) { disableFile(event.getFile(), MODIFIED); } } }); } public ID<String, Void> getName() { return NAME; } public DataIndexer<String, Void, FileContent> getIndexer() { return myDataIndexer; } public KeyDescriptor<String> getKeyDescriptor() { return myKeyDescriptor; } public FileBasedIndex.InputFilter getInputFilter() { return myInputFilter; } public boolean dependsOnFileContent() { return false; } public int getVersion() { return 0; } @Nullable public static String getInactivityReason(VirtualFile file) { try { final byte[] bytes = ENABLED.readAttributeBytes(file); if (bytes == null || bytes.length < 1) { return null; } if (bytes[0] != 42) { return null; } return new String(bytes, 1, bytes.length - 1); } catch (IOException e) { return null; } } public static boolean isActivated(VirtualFile file) { try { final byte[] bytes = ENABLED.readAttributeBytes(file); if (bytes == null) { return true; } return bytes.length == ENABLED_FLAG.length && bytes[0] == ENABLED_FLAG[0]; } catch (IOException e) { return false; } } public static void activateUntilModification(final VirtualFile vfile) { try { ENABLED.writeAttributeBytes(vfile, ENABLED_FLAG); } catch (IOException e) { LOG.error(e); } clearScriptCache(); } private static void clearScriptCache() { for (Project project : ProjectManager.getInstance().getOpenProjects()) { project.putUserData(SCRIPTS_CACHE, null); ((PsiModificationTrackerImpl)PsiManager.getInstance(project).getModificationTracker()).incCounter(); } } private static void disableFile(final VirtualFile vfile, String error) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(error.length() * 2 + 1); stream.write(42); stream.write(error.getBytes()); ENABLED.writeAttributeBytes(vfile, stream.toByteArray()); } catch (IOException e1) { LOG.error(e1); } vfile.putUserData(CACHED_EXECUTOR, null); clearScriptCache(); } @Nullable private static GroovyDslExecutor getCachedExecutor(@NotNull final VirtualFile file, final long stamp) { final Pair<GroovyDslExecutor, Long> pair = file.getUserData(CACHED_EXECUTOR); if (pair == null || pair.second.longValue() != stamp) { return null; } return pair.first; } public static boolean processExecutors(PsiType psiType, GroovyPsiElement place, final PsiScopeProcessor processor, ResolveState state) { if (insideAnnotation(place)) { // Basic filter, all DSL contexts are applicable for reference expressions only return true; } final String qname = psiType.getCanonicalText(); if (qname == null) { return true; } final PsiFile placeFile = place.getContainingFile().getOriginalFile(); final DelegatingScopeProcessor nameChecker = new DelegatingScopeProcessor(processor) { @Override public boolean execute(PsiElement element, ResolveState state) { if (element instanceof PsiMethod && ((PsiMethod)element).isConstructor()) { return processor.execute(element, state); } return ResolveUtil.processElement(processor, (PsiNamedElement)element, state); } }; for (GroovyDslScript script : getDslScripts(place.getProject())) { if (!script.processExecutor(nameChecker, psiType, place, placeFile, qname, state)) { return false; } } return true; } private static boolean insideAnnotation(PsiElement place) { while (place != null) { if (place instanceof PsiAnnotation) return true; if (place instanceof PsiFile) return false; place = place.getParent(); } return false; } private static volatile List<Pair<File, GroovyDslExecutor>> ourStandardScripts; private static List<Pair<File, GroovyDslExecutor>> getStandardScripts() { List<Pair<File, GroovyDslExecutor>> result = ourStandardScripts; if (result != null) { return result; } final Semaphore semaphore = new Semaphore(); semaphore.down(); ourPool.execute(new Runnable() { @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod") @Override public void run() { if (ourStandardScripts != null) { return; } try { Set<File> scriptFolders = new LinkedHashSet<File>(); // perhaps a separate extension for that? for (GroovyFrameworkConfigNotification extension : GroovyFrameworkConfigNotification.EP_NAME.getExtensions()) { File jarPath = new File(PathUtil.getJarPathForClass(extension.getClass())); if (jarPath.isFile()) { jarPath = jarPath.getParentFile(); } scriptFolders.add(new File(jarPath, "standardDsls")); } List<Pair<File, GroovyDslExecutor>> executors = new ArrayList<Pair<File, GroovyDslExecutor>>(); for (File file : scriptFolders) { if (file.exists()) { for (File child : file.listFiles()) { final String fileName = child.getName(); if (fileName.endsWith(".gdsl")) { try { final String text = new String(FileUtil.loadFileText(child)); executors.add(Pair.create(child, new GroovyDslExecutor(text, fileName))); } catch (IOException e) { LOG.error(e); } } } } } ourStandardScripts = executors; } catch (OutOfMemoryError e) { stopGdsl = true; throw e; } catch (NoClassDefFoundError e) { stopGdsl = true; throw e; } finally { semaphore.up(); } } }); while (ourStandardScripts == null && !stopGdsl && !semaphore.waitFor(20)) { ProgressManager.checkCanceled(); } if (stopGdsl) { return Collections.emptyList(); } return ourStandardScripts; } private static final Key<CachedValue<List<GroovyDslScript>>> SCRIPTS_CACHE = Key.create("GdslScriptCache"); private static List<GroovyDslScript> getDslScripts(final Project project) { return CachedValuesManager.getManager(project).getCachedValue(project, SCRIPTS_CACHE, new CachedValueProvider<List<GroovyDslScript>>() { @Override public Result<List<GroovyDslScript>> compute() { if (stopGdsl) { return Result.create(Collections.<GroovyDslScript>emptyList()); } int count = 0; List<GroovyDslScript> result = new ArrayList<GroovyDslScript>(); for (Pair<File, GroovyDslExecutor> pair : getStandardScripts()) { result.add(new GroovyDslScript(project, null, pair.second, pair.first.getPath())); } if (stopGdsl) { return Result.create(Collections.<GroovyDslScript>emptyList()); } final LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>> queue = new LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>>(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (VirtualFile vfile : FileBasedIndex.getInstance().getContainingFiles(NAME, OUR_KEY, GlobalSearchScope.allScope(project))) { if (!vfile.isValid()) { continue; } if (!fileIndex.isInLibraryClasses(vfile) && !fileIndex.isInLibrarySource(vfile)) { if (!fileIndex.isInSourceContent(vfile) || !isActivated(vfile)) { continue; } } final long stamp = vfile.getModificationStamp(); final GroovyDslExecutor cached = getCachedExecutor(vfile, stamp); if (cached == null) { scheduleParsing(queue, project, vfile, stamp, LoadTextUtil.loadText(vfile).toString()); count++; } else { result.add(new GroovyDslScript(project, vfile, cached, vfile.getPath())); } } try { while (count > 0 && !stopGdsl) { ProgressManager.checkCanceled(); final Pair<VirtualFile, GroovyDslExecutor> pair = queue.poll(20, TimeUnit.MILLISECONDS); if (pair != null) { count--; if (pair.second != null) { result.add(new GroovyDslScript(project, pair.first, pair.second, pair.first.getPath())); } } } } catch (InterruptedException e) { LOG.error(e); } return Result.create(result, PsiModificationTracker.MODIFICATION_COUNT, ProjectRootManager.getInstance(project)); } }, false); } private static class MyDataIndexer implements DataIndexer<String, Void, FileContent> { @NotNull public Map<String, Void> map(final FileContent inputData) { return Collections.singletonMap(OUR_KEY, null); } } private static class MyInputFilter implements FileBasedIndex.InputFilter { public boolean acceptInput(final VirtualFile file) { return "gdsl".equals(file.getExtension()); } } private static void scheduleParsing(final LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>> queue, final Project project, final VirtualFile vfile, final long stamp, final String text) { final String fileUrl = vfile.getUrl(); final Runnable parseScript = new Runnable() { public void run() { GroovyDslExecutor executor = getCachedExecutor(vfile, stamp); try { if (executor == null && isActivated(vfile)) { executor = createExecutor(text, vfile, project); // executor is not only time-consuming to create, but also takes some PermGenSpace // => we can't afford garbage-collecting it together with PsiFile // => cache globally by file instance vfile.putUserData(CACHED_EXECUTOR, Pair.create(executor, stamp)); if (executor != null) { activateUntilModification(vfile); } } } finally { // access to our MultiMap should be synchronized synchronized (vfile) { // put evaluated executor to all queues for (LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>> queue : filesInProcessing.remove(fileUrl)) { queue.offer(Pair.create(vfile, executor)); } } } } }; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (vfile) { //ensure that only one thread calculates dsl executor final boolean isNewRequest = !filesInProcessing.containsKey(fileUrl); filesInProcessing.putValue(fileUrl, queue); if (isNewRequest) { ourPool.execute(parseScript); //todo bring back multithreading when Groovy team fixes http://jira.codehaus.org/browse/GROOVY-4292 //ApplicationManager.getApplication().executeOnPooledThread(parseScript); } } } private static volatile boolean stopGdsl = false; @Nullable private static GroovyDslExecutor createExecutor(String text, VirtualFile vfile, final Project project) { if (stopGdsl) { return null; } try { return new GroovyDslExecutor(text, vfile.getName()); } catch (final Throwable e) { if (project.isDisposed()) { LOG.error(e); return null; } if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.error(e); return null; } invokeDslErrorPopup(e, project, vfile); if (e instanceof OutOfMemoryError) { stopGdsl = true; throw (Error)e; } if (e instanceof NoClassDefFoundError) { stopGdsl = true; throw (NoClassDefFoundError) e; } return null; } } static void invokeDslErrorPopup(Throwable e, final Project project, @NotNull VirtualFile vfile) { if (!isActivated(vfile)) { return; } final String exceptionText = ExceptionUtil.getThrowableText(e); LOG.info(exceptionText); disableFile(vfile, exceptionText); if (!ApplicationManagerEx.getApplicationEx().isInternal() && !ProjectRootManager.getInstance(project).getFileIndex().isInContent(vfile)) { return; } String content = "<p>" + e.getMessage() + "</p><p><a href=\"\">Click here to investigate.</a></p>"; NOTIFICATION_GROUP.createNotification("DSL script execution error", content, NotificationType.ERROR, new NotificationListener() { public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { GroovyDslAnnotator.analyzeStackTrace(project, exceptionText); notification.expire(); } }).notify(project); } }
plugins/groovy/src/org/jetbrains/plugins/groovy/dsl/GroovyDslFileIndex.java
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.dsl; import com.intellij.notification.*; import com.intellij.notification.impl.NotificationsConfigurationImpl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.impl.LoadTextUtil; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileAdapter; import com.intellij.openapi.vfs.VirtualFileEvent; import com.intellij.openapi.vfs.VirtualFileManager; import com.intellij.openapi.vfs.newvfs.FileAttribute; import com.intellij.psi.*; import com.intellij.psi.impl.PsiModificationTrackerImpl; import com.intellij.psi.scope.DelegatingScopeProcessor; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.CachedValue; import com.intellij.psi.util.CachedValueProvider; import com.intellij.psi.util.CachedValuesManager; import com.intellij.psi.util.PsiModificationTracker; import com.intellij.util.ExceptionUtil; import com.intellij.util.PathUtil; import com.intellij.util.containers.ConcurrentMultiMap; import com.intellij.util.containers.MultiMap; import com.intellij.util.indexing.*; import com.intellij.util.io.EnumeratorStringDescriptor; import com.intellij.util.io.KeyDescriptor; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.annotator.GroovyFrameworkConfigNotification; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil; import javax.swing.event.HyperlinkEvent; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author peter */ public class GroovyDslFileIndex extends ScalarIndexExtension<String> { private static final Key<Pair<GroovyDslExecutor, Long>> CACHED_EXECUTOR = Key.create("CachedGdslExecutor"); private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.dsl.GroovyDslFileIndex"); private static final FileAttribute ENABLED = new FileAttribute("ENABLED", 0); @NonNls public static final ID<String, Void> NAME = ID.create("GroovyDslFileIndex"); @NonNls private static final String OUR_KEY = "ourKey"; public static final String MODIFIED = "Modified"; public static final NotificationGroup NOTIFICATION_GROUP = new NotificationGroup("Groovy DSL errors", NotificationDisplayType.BALLOON, true); private final MyDataIndexer myDataIndexer = new MyDataIndexer(); private final MyInputFilter myInputFilter = new MyInputFilter(); private static final MultiMap<String, LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>>> filesInProcessing = new ConcurrentMultiMap<String, LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>>>(); private static final ThreadPoolExecutor ourPool = new ThreadPoolExecutor(1, 1, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "Groovy DSL File Index Executor"); } }); private final EnumeratorStringDescriptor myKeyDescriptor = new EnumeratorStringDescriptor(); private static final byte[] ENABLED_FLAG = new byte[]{(byte)239}; static { NotificationsConfigurationImpl.remove("Groovy DSL parsing"); } public GroovyDslFileIndex() { VirtualFileManager.getInstance().addVirtualFileListener(new VirtualFileAdapter() { @Override public void contentsChanged(VirtualFileEvent event) { if (event.getFileName().endsWith(".gdsl")) { disableFile(event.getFile(), MODIFIED); } } }); } public ID<String, Void> getName() { return NAME; } public DataIndexer<String, Void, FileContent> getIndexer() { return myDataIndexer; } public KeyDescriptor<String> getKeyDescriptor() { return myKeyDescriptor; } public FileBasedIndex.InputFilter getInputFilter() { return myInputFilter; } public boolean dependsOnFileContent() { return false; } public int getVersion() { return 0; } @Nullable public static String getInactivityReason(VirtualFile file) { try { final byte[] bytes = ENABLED.readAttributeBytes(file); if (bytes == null || bytes.length < 1) { return null; } if (bytes[0] != 42) { return null; } return new String(bytes, 1, bytes.length - 1); } catch (IOException e) { return null; } } public static boolean isActivated(VirtualFile file) { try { final byte[] bytes = ENABLED.readAttributeBytes(file); if (bytes == null) { return true; } return bytes.length == ENABLED_FLAG.length && bytes[0] == ENABLED_FLAG[0]; } catch (IOException e) { return false; } } public static void activateUntilModification(final VirtualFile vfile) { try { ENABLED.writeAttributeBytes(vfile, ENABLED_FLAG); } catch (IOException e) { LOG.error(e); } clearScriptCache(); } private static void clearScriptCache() { for (Project project : ProjectManager.getInstance().getOpenProjects()) { project.putUserData(SCRIPTS_CACHE, null); ((PsiModificationTrackerImpl)PsiManager.getInstance(project).getModificationTracker()).incCounter(); } } private static void disableFile(final VirtualFile vfile, String error) { try { ByteArrayOutputStream stream = new ByteArrayOutputStream(error.length() * 2 + 1); stream.write(42); stream.write(error.getBytes()); ENABLED.writeAttributeBytes(vfile, stream.toByteArray()); } catch (IOException e1) { LOG.error(e1); } vfile.putUserData(CACHED_EXECUTOR, null); clearScriptCache(); } @Nullable private static GroovyDslExecutor getCachedExecutor(@NotNull final VirtualFile file, final long stamp) { final Pair<GroovyDslExecutor, Long> pair = file.getUserData(CACHED_EXECUTOR); if (pair == null || pair.second.longValue() != stamp) { return null; } return pair.first; } public static boolean processExecutors(PsiType psiType, GroovyPsiElement place, final PsiScopeProcessor processor, ResolveState state) { if (insideAnnotation(place)) { // Basic filter, all DSL contexts are applicable for reference expressions only return true; } final String qname = psiType.getCanonicalText(); if (qname == null) { return true; } final PsiFile placeFile = place.getContainingFile().getOriginalFile(); final DelegatingScopeProcessor nameChecker = new DelegatingScopeProcessor(processor) { @Override public boolean execute(PsiElement element, ResolveState state) { if (element instanceof PsiMethod && ((PsiMethod)element).isConstructor()) { return processor.execute(element, state); } return ResolveUtil.processElement(processor, (PsiNamedElement)element, state); } }; for (GroovyDslScript script : getDslScripts(place.getProject())) { if (!script.processExecutor(nameChecker, psiType, place, placeFile, qname, state)) { return false; } } return true; } private static boolean insideAnnotation(PsiElement place) { while (place != null) { if (place instanceof PsiAnnotation) return true; if (place instanceof PsiFile) return false; place = place.getParent(); } return false; } private static volatile List<Pair<File, GroovyDslExecutor>> ourStandardScripts; private static List<Pair<File, GroovyDslExecutor>> getStandardScripts() { if (ourStandardScripts == null) { synchronized (SCRIPTS_CACHE) { if (ourStandardScripts == null) { Set<File> scriptFolders = new LinkedHashSet<File>(); // perhaps a separate extension for that? for (GroovyFrameworkConfigNotification extension : GroovyFrameworkConfigNotification.EP_NAME.getExtensions()) { File jarPath = new File(PathUtil.getJarPathForClass(extension.getClass())); if (jarPath.isFile()) { jarPath = jarPath.getParentFile(); } scriptFolders.add(new File(jarPath, "standardDsls")); } List<Pair<File, GroovyDslExecutor>> executors = new ArrayList<Pair<File, GroovyDslExecutor>>(); for (File file : scriptFolders) { if (file.exists()) { for (File child : file.listFiles()) { final String fileName = child.getName(); if (fileName.endsWith(".gdsl")) { try { final String text = new String(FileUtil.loadFileText(child)); executors.add(Pair.create(child, new GroovyDslExecutor(text, fileName))); } catch (IOException e) { LOG.error(e); } } } } } ourStandardScripts = executors; } } } return ourStandardScripts; } private static final Key<CachedValue<List<GroovyDslScript>>> SCRIPTS_CACHE = Key.create("GdslScriptCache"); private static List<GroovyDslScript> getDslScripts(final Project project) { return CachedValuesManager.getManager(project).getCachedValue(project, SCRIPTS_CACHE, new CachedValueProvider<List<GroovyDslScript>>() { @Override public Result<List<GroovyDslScript>> compute() { if (stopGdsl) { return Result.create(Collections.<GroovyDslScript>emptyList()); } int count = 0; List<GroovyDslScript> result = new ArrayList<GroovyDslScript>(); try { for (Pair<File, GroovyDslExecutor> pair : getStandardScripts()) { result.add(new GroovyDslScript(project, null, pair.second, pair.first.getPath())); } } catch (OutOfMemoryError e) { stopGdsl = true; throw e; } catch (NoClassDefFoundError e) { stopGdsl = true; throw e; } final LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>> queue = new LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>>(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (VirtualFile vfile : FileBasedIndex.getInstance().getContainingFiles(NAME, OUR_KEY, GlobalSearchScope.allScope(project))) { if (!vfile.isValid()) { continue; } if (!fileIndex.isInLibraryClasses(vfile) && !fileIndex.isInLibrarySource(vfile)) { if (!fileIndex.isInSourceContent(vfile) || !isActivated(vfile)) { continue; } } final long stamp = vfile.getModificationStamp(); final GroovyDslExecutor cached = getCachedExecutor(vfile, stamp); if (cached == null) { scheduleParsing(queue, project, vfile, stamp, LoadTextUtil.loadText(vfile).toString()); count++; } else { result.add(new GroovyDslScript(project, vfile, cached, vfile.getPath())); } } try { while (count > 0 && !stopGdsl) { ProgressManager.checkCanceled(); final Pair<VirtualFile, GroovyDslExecutor> pair = queue.poll(20, TimeUnit.MILLISECONDS); if (pair != null) { count--; if (pair.second != null) { result.add(new GroovyDslScript(project, pair.first, pair.second, pair.first.getPath())); } } } } catch (InterruptedException e) { LOG.error(e); } return Result.create(result, PsiModificationTracker.MODIFICATION_COUNT, ProjectRootManager.getInstance(project)); } }, false); } private static class MyDataIndexer implements DataIndexer<String, Void, FileContent> { @NotNull public Map<String, Void> map(final FileContent inputData) { return Collections.singletonMap(OUR_KEY, null); } } private static class MyInputFilter implements FileBasedIndex.InputFilter { public boolean acceptInput(final VirtualFile file) { return "gdsl".equals(file.getExtension()); } } private static void scheduleParsing(final LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>> queue, final Project project, final VirtualFile vfile, final long stamp, final String text) { final String fileUrl = vfile.getUrl(); final Runnable parseScript = new Runnable() { public void run() { GroovyDslExecutor executor = getCachedExecutor(vfile, stamp); try { if (executor == null && isActivated(vfile)) { executor = createExecutor(text, vfile, project); // executor is not only time-consuming to create, but also takes some PermGenSpace // => we can't afford garbage-collecting it together with PsiFile // => cache globally by file instance vfile.putUserData(CACHED_EXECUTOR, Pair.create(executor, stamp)); if (executor != null) { activateUntilModification(vfile); } } } finally { // access to our MultiMap should be synchronized synchronized (vfile) { // put evaluated executor to all queues for (LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>> queue : filesInProcessing.remove(fileUrl)) { queue.offer(Pair.create(vfile, executor)); } } } } }; //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (vfile) { //ensure that only one thread calculates dsl executor final boolean isNewRequest = !filesInProcessing.containsKey(fileUrl); filesInProcessing.putValue(fileUrl, queue); if (isNewRequest) { ourPool.execute(parseScript); //todo bring back multithreading when Groovy team fixes http://jira.codehaus.org/browse/GROOVY-4292 //ApplicationManager.getApplication().executeOnPooledThread(parseScript); } } } private static volatile boolean stopGdsl = false; @Nullable private static GroovyDslExecutor createExecutor(String text, VirtualFile vfile, final Project project) { if (stopGdsl) { return null; } try { return new GroovyDslExecutor(text, vfile.getName()); } catch (final Throwable e) { if (project.isDisposed()) { LOG.error(e); return null; } if (ApplicationManager.getApplication().isUnitTestMode()) { LOG.error(e); return null; } invokeDslErrorPopup(e, project, vfile); if (e instanceof OutOfMemoryError) { stopGdsl = true; throw (Error)e; } if (e instanceof NoClassDefFoundError) { stopGdsl = true; throw (NoClassDefFoundError) e; } return null; } } static void invokeDslErrorPopup(Throwable e, final Project project, @NotNull VirtualFile vfile) { if (!isActivated(vfile)) { return; } final String exceptionText = ExceptionUtil.getThrowableText(e); LOG.info(exceptionText); disableFile(vfile, exceptionText); if (!ApplicationManagerEx.getApplicationEx().isInternal() && !ProjectRootManager.getInstance(project).getFileIndex().isInContent(vfile)) { return; } String content = "<p>" + e.getMessage() + "</p><p><a href=\"\">Click here to investigate.</a></p>"; NOTIFICATION_GROUP.createNotification("DSL script execution error", content, NotificationType.ERROR, new NotificationListener() { public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { GroovyDslAnnotator.analyzeStackTrace(project, exceptionText); notification.expire(); } }).notify(project); } }
non-blocking bundled gdsl scripts parsing
plugins/groovy/src/org/jetbrains/plugins/groovy/dsl/GroovyDslFileIndex.java
non-blocking bundled gdsl scripts parsing
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/dsl/GroovyDslFileIndex.java <ide> import com.intellij.psi.util.PsiModificationTracker; <ide> import com.intellij.util.ExceptionUtil; <ide> import com.intellij.util.PathUtil; <add>import com.intellij.util.concurrency.Semaphore; <ide> import com.intellij.util.containers.ConcurrentMultiMap; <ide> import com.intellij.util.containers.MultiMap; <ide> import com.intellij.util.indexing.*; <ide> private static volatile List<Pair<File, GroovyDslExecutor>> ourStandardScripts; <ide> <ide> private static List<Pair<File, GroovyDslExecutor>> getStandardScripts() { <del> if (ourStandardScripts == null) { <del> synchronized (SCRIPTS_CACHE) { <del> if (ourStandardScripts == null) { <add> List<Pair<File, GroovyDslExecutor>> result = ourStandardScripts; <add> if (result != null) { <add> return result; <add> } <add> <add> final Semaphore semaphore = new Semaphore(); <add> semaphore.down(); <add> ourPool.execute(new Runnable() { <add> @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod") <add> @Override <add> public void run() { <add> if (ourStandardScripts != null) { <add> return; <add> } <add> <add> try { <ide> Set<File> scriptFolders = new LinkedHashSet<File>(); <ide> // perhaps a separate extension for that? <ide> for (GroovyFrameworkConfigNotification extension : GroovyFrameworkConfigNotification.EP_NAME.getExtensions()) { <ide> } <ide> } <ide> } <del> <ide> } <ide> ourStandardScripts = executors; <ide> } <del> } <add> catch (OutOfMemoryError e) { <add> stopGdsl = true; <add> throw e; <add> } <add> catch (NoClassDefFoundError e) { <add> stopGdsl = true; <add> throw e; <add> } <add> finally { <add> semaphore.up(); <add> } <add> } <add> }); <add> <add> while (ourStandardScripts == null && !stopGdsl && !semaphore.waitFor(20)) { <add> ProgressManager.checkCanceled(); <add> } <add> if (stopGdsl) { <add> return Collections.emptyList(); <ide> } <ide> return ourStandardScripts; <ide> } <ide> <ide> List<GroovyDslScript> result = new ArrayList<GroovyDslScript>(); <ide> <del> try { <del> for (Pair<File, GroovyDslExecutor> pair : getStandardScripts()) { <del> result.add(new GroovyDslScript(project, null, pair.second, pair.first.getPath())); <del> } <del> } <del> catch (OutOfMemoryError e) { <del> stopGdsl = true; <del> throw e; <del> } <del> catch (NoClassDefFoundError e) { <del> stopGdsl = true; <del> throw e; <add> for (Pair<File, GroovyDslExecutor> pair : getStandardScripts()) { <add> result.add(new GroovyDslScript(project, null, pair.second, pair.first.getPath())); <add> } <add> if (stopGdsl) { <add> return Result.create(Collections.<GroovyDslScript>emptyList()); <ide> } <ide> <ide> final LinkedBlockingQueue<Pair<VirtualFile, GroovyDslExecutor>> queue =
Java
epl-1.0
6ecb6c6c3dee46cc81428d5d63e597a85e34195c
0
dynamid/golo-lang-insa-citilab-historical-reference,dynamid/golo-lang-insa-citilab-historical-reference,smarr/golo-lang,titimoby/golo-lang,smarr/golo-lang,titimoby/golo-lang,dynamid/golo-lang-insa-citilab-historical-reference
/* * Copyright 2012-2014 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.insalyon.citi.golo.runtime; import org.testng.annotations.Test; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandle; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodType.genericMethodType; import static java.lang.invoke.MethodType.methodType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class ClosureCallSupportTest { static Object objectToString(Object foo) { return foo.toString(); } static Object objectToStringDecorated(Object foo) { return "[" + foo.toString() + "]"; } static Object concat(Object... args) { String result = ""; for (Object arg : args) { result = result + arg; } return result; } static Integer parseIntWrap(String s) { return Integer.parseInt(s, 10); } @Test public void check_bootstrap() throws Throwable { MethodHandle handle = lookup().findStatic(ClosureCallSupportTest.class, "objectToString", genericMethodType(1)); CallSite callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); MethodHandle invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, 123), is("123")); assertThat((String) invoker.invokeWithArguments(handle, 123), is("123")); handle = lookup().findStatic(ClosureCallSupportTest.class, "objectToStringDecorated", genericMethodType(1)); assertThat((String) invoker.invokeWithArguments(handle, 123), is("[123]")); assertThat((String) invoker.invokeWithArguments(handle, 123), is("[123]")); } @Test public void check_bootstrap_varargs() throws Throwable { MethodHandle handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); CallSite callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class, Object.class), 0); MethodHandle invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, 1, 2), is("12")); handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, 1), is("1")); handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class), 0); invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle), is("")); handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, new Object[]{1,2}), is("12")); } @Test public void check_bootstrap_besides_Object() throws Throwable { MethodHandle handle = lookup().findStatic(ClosureCallSupportTest.class, "parseIntWrap", methodType(Integer.class, String.class)); CallSite callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); MethodHandle invoker = callSite.dynamicInvoker(); assertThat((Integer) invoker.invokeWithArguments(handle, "123"), is(123)); assertThat((Integer) invoker.invokeWithArguments(handle, "123"), is(123)); } }
src/test/java/fr/insalyon/citi/golo/runtime/ClosureCallSupportTest.java
/* * Copyright 2012-2014 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.insalyon.citi.golo.runtime; import org.testng.annotations.Test; import java.lang.invoke.CallSite; import java.lang.invoke.MethodHandle; import static java.lang.invoke.MethodHandles.lookup; import static java.lang.invoke.MethodType.genericMethodType; import static java.lang.invoke.MethodType.methodType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class ClosureCallSupportTest { static Object objectToString(Object foo) { return foo.toString(); } static Object objectToStringDecorated(Object foo) { return "[" + foo.toString() + "]"; } static Object concat(Object... args) { String result = ""; for (Object arg : args) { result = result + arg; } return result; } @Test public void check_bootstrap() throws Throwable { MethodHandle handle = lookup().findStatic(ClosureCallSupportTest.class, "objectToString", genericMethodType(1)); CallSite callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); MethodHandle invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, 123), is("123")); assertThat((String) invoker.invokeWithArguments(handle, 123), is("123")); handle = lookup().findStatic(ClosureCallSupportTest.class, "objectToStringDecorated", genericMethodType(1)); assertThat((String) invoker.invokeWithArguments(handle, 123), is("[123]")); assertThat((String) invoker.invokeWithArguments(handle, 123), is("[123]")); } @Test public void check_bootstrap_varargs() throws Throwable { MethodHandle handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); CallSite callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class, Object.class), 0); MethodHandle invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, 1, 2), is("12")); handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, 1), is("1")); handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class), 0); invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle), is("")); handle = lookup().findStatic(ClosureCallSupportTest.class, "concat", genericMethodType(0, true)); callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); invoker = callSite.dynamicInvoker(); assertThat((String) invoker.invokeWithArguments(handle, new Object[]{1,2}), is("12")); } }
Add test to call closure with types besides Object
src/test/java/fr/insalyon/citi/golo/runtime/ClosureCallSupportTest.java
Add test to call closure with types besides Object
<ide><path>rc/test/java/fr/insalyon/citi/golo/runtime/ClosureCallSupportTest.java <ide> return result; <ide> } <ide> <add> static Integer parseIntWrap(String s) { <add> return Integer.parseInt(s, 10); <add> } <add> <ide> @Test <ide> public void check_bootstrap() throws Throwable { <ide> MethodHandle handle = lookup().findStatic(ClosureCallSupportTest.class, "objectToString", genericMethodType(1)); <ide> invoker = callSite.dynamicInvoker(); <ide> assertThat((String) invoker.invokeWithArguments(handle, new Object[]{1,2}), is("12")); <ide> } <add> <add> @Test <add> public void check_bootstrap_besides_Object() throws Throwable { <add> MethodHandle handle = lookup().findStatic(ClosureCallSupportTest.class, "parseIntWrap", methodType(Integer.class, String.class)); <add> CallSite callSite = ClosureCallSupport.bootstrap(lookup(), "closure", methodType(Object.class, MethodHandle.class, Object.class), 0); <add> MethodHandle invoker = callSite.dynamicInvoker(); <add> assertThat((Integer) invoker.invokeWithArguments(handle, "123"), is(123)); <add> assertThat((Integer) invoker.invokeWithArguments(handle, "123"), is(123)); <add> } <ide> }
JavaScript
mit
02d48d05deac6e4668d4d28ad6ea1a3f7e7ee9b7
0
vigour-io/hub
'use strict' var Protocol = require('../../protocol') var Event = require('vigour-js/lib/event') var hash = require('vigour-js/lib/util/hash') var isEmpty = require('vigour-js/lib/util/is/empty') var Observable = require('vigour-js/lib/observable') var _subscribe = Observable.prototype.subscribe exports.inject = require('./data') exports.properties = { subsrefs: true, subscollectors: true, cachedSyncPath: true } exports.define = { subscribe (pattern) { var add // NEEDS GAURD // if (!this._on[subs.key]) { // add = true // } var subs = _subscribe.apply(this, arguments) // if (!dontadd) { this.sendSubscriptionUpstream(this, subs.pattern, void 0, subs.key) // } return subs }, unsubscribe (key, event) { console.log('dirt mc gurd 2', key) if (typeof key === 'string') { // this has to be handled better if (this.removeSubscription(key)) { let emitter = this._on && this._on[key] if (!event) { event = new Event(this, 'removeitsubs') event.stamp += 'subscription' } this.sendUpstream(void 0, event, { unsubscribe: { val: [ key ], path: this.syncPath } }) // if (emitter) { // have to count listeners and shit // emitter.remove() // } // for non server hub this is wrong! // if emitter is empty // emitter.remove() } } }, syncPath: { get () { var parent = this var path = [] if (this.cachedSyncPath) { return this.cachedSyncPath } while (parent && parent.key && !parent.adapter) { path.unshift(parent.key) parent = parent._parent } this.cachedSyncPath = path return path } }, onSubRemove (emitter, event) { console.log('dirt mc gurd') if (!this.subsrefs) { return } let path = emitter._path.join('.') let hashed = this.subsrefs[path] if (hashed) { delete this.subsrefs[path] if (isEmpty(this.subsrefs)) { delete this.subsrefs } this.unsubscribe(hashed, event) } }, addSubscription (key) { var newsub if (!this.hasOwnProperty('subscollectors')) { this.subscollectors = {} } if (!this.subscollectors[key]) { this.subscollectors[key] = 0 newsub = true } this.subscollectors[key]++ return newsub }, removeSubscription (key) { if (this.subscollectors && this.subscollectors[key]) { this.subscollectors[key]-- if (!this.subscollectors[key]) { delete this.subscollectors[key] if (isEmpty(this.subscollectors)) { delete this.subscollectors } return true } } }, onSub (data, event, emitter, pattern, current, mapvalue, map, context) { var genpath = emitter.path.join('.') if (this.subsrefs && this.subsrefs[genpath]) { return } if (!this.hasOwnProperty('substore')) { this.subsrefs = {} } let key = this.sendSubscriptionUpstream(pattern, event) this.subsrefs[genpath] = key }, getAdapter () { let adapter let parent = this while (!adapter && parent) { adapter = parent.adapter if (!adapter) { parent = parent.parent } } if (!adapter) { this.emit('error', 'no adapter yet') return } return adapter }, sendUpstream (data, event, subscribe) { var adapter = this.getAdapter() if (!adapter) { return } let eventorigin = this.parseEvent(event, adapter) if (!eventorigin) { return } if (!event.upstream) { adapter.each( (property) => property.client.origin.send(this, adapter.parent, data, event, eventorigin, subscribe), (property) => (property instanceof Protocol) && property._input && property.client ) } }, sendSubscriptionUpstream (pattern, event, key) { if (!event) { event = new Event(this, 'makeitsubs') event.stamp += 'subscription' } var path = this.syncPath var serialized = pattern.serialize() walker(serialized) if (!key) { key = hash(JSON.stringify(serialized)) } if (this.addSubscription(key)) { this.sendUpstream(void 0, event, { [key]: { val: serialized, path: path } }) } return key }, parseEvent (event, adapter) { let id = adapter.id let eventorigin = ( event.stamp.indexOf && event.stamp.indexOf('|') && event.stamp.slice(0, event.stamp.indexOf('|')) ) || id return eventorigin } } function walker (val) { for (var i in val) { if (typeof val[i] === 'object') { walker(val[i]) } else { val[i] = true } } }
lib/syncable/on/index.js
'use strict' var Protocol = require('../../protocol') var Event = require('vigour-js/lib/event') var hash = require('vigour-js/lib/util/hash') var isEmpty = require('vigour-js/lib/util/is/empty') var Observable = require('vigour-js/lib/observable') var _subscribe = Observable.prototype.subscribe exports.inject = require('./data') exports.properties = { subsrefs: true, subscollectors: true, cachedSyncPath: true } exports.define = { subscribe (pattern) { var add // NEEDS GAURD // if (!this._on[subs.key]) { // add = true // } var subs = _subscribe.apply(this, arguments) console.log('lulllz subscribing!'.rainbow, subs.key) // if (!dontadd) { sendSubsUp(this, subs.pattern, void 0, subs.key) // } return subs }, unsubscribe (key, event) { console.log('dirt mc gurd 2', key) if (typeof key === 'string') { // this has to be handled better if (this.removeSubscription(key)) { let emitter = this._on && this._on[key] if (!event) { event = new Event(this, 'removeitsubs') event.stamp += 'subscription' } this.sendUpstream(void 0, event, { unsubscribe: { val: [ key ], path: this.syncPath } }) // if (emitter) { // have to count listeners and shit // emitter.remove() // } // for non server hub this is wrong! // if emitter is empty // emitter.remove() } } }, syncPath: { get () { var parent = this var path = [] if (this.cachedSyncPath) { return this.cachedSyncPath } while (parent && parent.key && !parent.adapter) { path.unshift(parent.key) parent = parent._parent } this.cachedSyncPath = path return path } }, onSubRemove (emitter, event) { console.log('dirt mc gurd') if (!this.subsrefs) { return } let path = emitter._path.join('.') let hashed = this.subsrefs[path] if (hashed) { delete this.subsrefs[path] if (isEmpty(this.subsrefs)) { delete this.subsrefs } this.unsubscribe(hashed, event) } }, addSubscription (key) { var newsub if (!this.hasOwnProperty('subscollectors')) { this.subscollectors = {} } if (!this.subscollectors[key]) { this.subscollectors[key] = 0 newsub = true } this.subscollectors[key]++ return newsub }, removeSubscription (key) { if (this.subscollectors && this.subscollectors[key]) { this.subscollectors[key]-- if (!this.subscollectors[key]) { delete this.subscollectors[key] if (isEmpty(this.subscollectors)) { delete this.subscollectors } return true } } }, onSub (data, event, emitter, pattern, current, mapvalue, map, context) { var genpath = emitter.path.join('.') console.log(genpath.rainbow) if (this.subsrefs && this.subsrefs[genpath]) { console.log('BLOCK!!!') return } if (!this.hasOwnProperty('substore')) { this.subsrefs = {} } this.subsrefs[genpath] = key let key = sendSubsUp(this, pattern, event) }, getAdapter () { let adapter let parent = this while (!adapter && parent) { adapter = parent.adapter if (!adapter) { parent = parent.parent } } if (!adapter) { this.emit('error', 'no adapter yet') return } return adapter }, sendUpstream (data, event, subscribe) { var adapter = this.getAdapter() if (!adapter) { return } let eventorigin = this.parseEvent(event, adapter) if (!eventorigin) { return } if (!event.upstream) { adapter.each( (property) => property.client.origin.send(this, adapter.parent, data, event, eventorigin, subscribe), (property) => (property instanceof Protocol) && property._input && property.client ) } }, parseEvent (event, adapter) { let id = adapter.id let eventorigin = ( event.stamp.indexOf && event.stamp.indexOf('|') && event.stamp.slice(0, event.stamp.indexOf('|')) ) || id return eventorigin } } function sendSubsUp (base, pattern, event, key) { if (!event) { event = new Event(base, 'makeitsubs') event.stamp += 'subscription' } var path = base.syncPath var serialized = pattern.serialize() walker(serialized) if (!key) { key = hash(JSON.stringify(serialized)) } if (base.addSubscription(key)) { base.sendUpstream(void 0, event, { [key]: { val: serialized, path: path } }) } return key } function walker (val) { for (var i in val) { if (typeof val[i] === 'object') { walker(val[i]) } else { val[i] = true } } }
clean up Former-commit-id: 7ef9102811fd386c0a96fde93a403b3c2e8e68b7
lib/syncable/on/index.js
clean up
<ide><path>ib/syncable/on/index.js <ide> // add = true <ide> // } <ide> var subs = _subscribe.apply(this, arguments) <del> console.log('lulllz subscribing!'.rainbow, subs.key) <ide> // if (!dontadd) { <del> sendSubsUp(this, subs.pattern, void 0, subs.key) <add> this.sendSubscriptionUpstream(this, subs.pattern, void 0, subs.key) <ide> // } <ide> return subs <ide> }, <ide> }, <ide> onSub (data, event, emitter, pattern, current, mapvalue, map, context) { <ide> var genpath = emitter.path.join('.') <del> console.log(genpath.rainbow) <ide> if (this.subsrefs && this.subsrefs[genpath]) { <del> console.log('BLOCK!!!') <ide> return <ide> } <ide> if (!this.hasOwnProperty('substore')) { <ide> this.subsrefs = {} <ide> } <add> let key = this.sendSubscriptionUpstream(pattern, event) <ide> this.subsrefs[genpath] = key <del> let key = sendSubsUp(this, pattern, event) <ide> }, <ide> getAdapter () { <ide> let adapter <ide> ) <ide> } <ide> }, <add> sendSubscriptionUpstream (pattern, event, key) { <add> if (!event) { <add> event = new Event(this, 'makeitsubs') <add> event.stamp += 'subscription' <add> } <add> var path = this.syncPath <add> var serialized = pattern.serialize() <add> walker(serialized) <add> if (!key) { <add> key = hash(JSON.stringify(serialized)) <add> } <add> if (this.addSubscription(key)) { <add> this.sendUpstream(void 0, event, { [key]: { val: serialized, path: path } }) <add> } <add> return key <add> }, <ide> parseEvent (event, adapter) { <ide> let id = adapter.id <ide> let eventorigin = ( <ide> } <ide> } <ide> <del>function sendSubsUp (base, pattern, event, key) { <del> if (!event) { <del> event = new Event(base, 'makeitsubs') <del> event.stamp += 'subscription' <del> } <del> var path = base.syncPath <del> var serialized = pattern.serialize() <del> walker(serialized) <del> if (!key) { <del> key = hash(JSON.stringify(serialized)) <del> } <del> if (base.addSubscription(key)) { <del> base.sendUpstream(void 0, event, { [key]: { val: serialized, path: path } }) <del> } <del> return key <del>} <del> <ide> function walker (val) { <ide> for (var i in val) { <ide> if (typeof val[i] === 'object') {
Java
bsd-3-clause
aa9f068236c921da01d9c59e880975c196c50c7c
0
hispindia/dhis2-Core,msf-oca-his/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,dhis2/dhis2-core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,hispindia/dhis2-Core,dhis2/dhis2-core,dhis2/dhis2-core,dhis2/dhis2-core
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.user.hibernate; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Root; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; import org.hibernate.annotations.QueryHints; import org.hibernate.query.Query; import org.hisp.dhis.common.IdentifiableObjectUtils; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.commons.collection.CollectionUtils; import org.hisp.dhis.commons.util.SqlHelper; import org.hisp.dhis.commons.util.TextUtils; import org.hisp.dhis.query.JpaQueryUtils; import org.hisp.dhis.query.Order; import org.hisp.dhis.query.QueryUtils; import org.hisp.dhis.schema.Schema; import org.hisp.dhis.schema.SchemaService; import org.hisp.dhis.security.acl.AclService; import org.hisp.dhis.user.CurrentUserGroupInfo; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserCredentials; import org.hisp.dhis.user.UserInvitationStatus; import org.hisp.dhis.user.UserQueryParams; import org.hisp.dhis.user.UserStore; import org.springframework.context.ApplicationEventPublisher; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; /** * @author Nguyen Hong Duc */ @Slf4j @Repository( "org.hisp.dhis.user.UserStore" ) public class HibernateUserStore extends HibernateIdentifiableObjectStore<User> implements UserStore { private final SchemaService schemaService; public HibernateUserStore( SessionFactory sessionFactory, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService, SchemaService schemaService ) { super( sessionFactory, jdbcTemplate, publisher, User.class, currentUserService, aclService, true ); checkNotNull( schemaService ); this.schemaService = schemaService; } @Override public void save( User user, boolean clearSharing ) { super.save( user, clearSharing ); currentUserService.invalidateUserGroupCache( user.getUsername() ); } @Override public List<User> getUsers( UserQueryParams params, @Nullable List<String> orders ) { return extractUserQueryUsers( getUserQuery( params, orders, false ).list() ); } @Override public List<User> getUsers( UserQueryParams params ) { return getUsers( params, null ); } @Override public List<User> getExpiringUsers( UserQueryParams params ) { return extractUserQueryUsers( getUserQuery( params, null, false ).list() ); } @Override public int getUserCount( UserQueryParams params ) { Long count = (Long) getUserQuery( params, null, true ).uniqueResult(); return count != null ? count.intValue() : 0; } @Nonnull private List<User> extractUserQueryUsers( @Nonnull List<?> result ) { if ( result.isEmpty() ) { return Collections.emptyList(); } final List<User> users = new ArrayList<>( result.size() ); for ( Object o : result ) { if ( o instanceof User ) { users.add( (User) o ); } else if ( o.getClass().isArray() ) { users.add( (User) ((Object[]) o)[0] ); } } return users; } private Query getUserQuery( UserQueryParams params, List<String> orders, boolean count ) { SqlHelper hlp = new SqlHelper(); List<Order> convertedOrder = null; String hql = null; if ( count ) { hql = "select count(distinct u) "; } else { Schema userSchema = schemaService.getSchema( User.class ); convertedOrder = QueryUtils.convertOrderStrings( orders, userSchema ); hql = Stream.of( "select distinct u", JpaQueryUtils.createSelectOrderExpression( convertedOrder, "u" ) ) .filter( Objects::nonNull ).collect( Collectors.joining( "," ) ); hql += " "; } hql += "from User u "; if ( count ) { hql += "inner join u.userCredentials uc "; } else { hql += "inner join fetch u.userCredentials uc "; } if ( params.isPrefetchUserGroups() && !count ) { hql += "left join fetch u.groups g "; } else { hql += "left join u.groups g "; } if ( params.hasOrganisationUnits() ) { hql += "left join u.organisationUnits ou "; if ( params.isIncludeOrgUnitChildren() ) { hql += hlp.whereAnd() + " ("; for ( int i = 0; i < params.getOrganisationUnits().size(); i++ ) { hql += String.format( "ou.path like :ouUid%d or ", i ); } hql = TextUtils.removeLastOr( hql ) + ")"; } else { hql += hlp.whereAnd() + " ou.id in (:ouIds) "; } } if ( params.hasUserGroups() ) { hql += hlp.whereAnd() + " g.id in (:userGroupIds) "; } if ( params.getDisabled() != null ) { hql += hlp.whereAnd() + " uc.disabled = :disabled "; } if ( params.isNot2FA() ) { hql += hlp.whereAnd() + " uc.secret is null "; } if ( params.getQuery() != null ) { hql += hlp.whereAnd() + " (" + "concat(lower(u.firstName),' ',lower(u.surname)) like :key " + "or lower(u.email) like :key " + "or lower(uc.username) like :key) "; } if ( params.getPhoneNumber() != null ) { hql += hlp.whereAnd() + " u.phoneNumber = :phoneNumber "; } if ( params.isCanManage() && params.getUser() != null ) { hql += hlp.whereAnd() + " g.id in (:ids) "; } if ( params.isAuthSubset() && params.getUser() != null ) { hql += hlp.whereAnd() + " not exists (" + "select uc2 from UserCredentials uc2 " + "inner join uc2.userAuthorityGroups ag2 " + "inner join ag2.authorities a " + "where uc2.id = uc.id " + "and a not in (:auths) ) "; } // TODO handle users with no user roles if ( params.isDisjointRoles() && params.getUser() != null ) { hql += hlp.whereAnd() + " not exists (" + "select uc3 from UserCredentials uc3 " + "inner join uc3.userAuthorityGroups ag3 " + "where uc3.id = uc.id " + "and ag3.id in (:roles) ) "; } if ( params.getLastLogin() != null ) { hql += hlp.whereAnd() + " uc.lastLogin >= :lastLogin "; } if ( params.getInactiveSince() != null ) { hql += hlp.whereAnd() + " uc.lastLogin < :inactiveSince "; } if ( params.getPasswordLastUpdated() != null ) { hql += hlp.whereAnd() + " uc.passwordLastUpdated < :passwordLastUpdated "; } if ( params.isSelfRegistered() ) { hql += hlp.whereAnd() + " uc.selfRegistered = true "; } if ( UserInvitationStatus.ALL.equals( params.getInvitationStatus() ) ) { hql += hlp.whereAnd() + " uc.invitation = true "; } if ( UserInvitationStatus.EXPIRED.equals( params.getInvitationStatus() ) ) { hql += hlp.whereAnd() + " uc.invitation = true " + "and uc.restoreToken is not null " + "and uc.restoreExpiry is not null " + "and uc.restoreExpiry < current_timestamp() "; } if ( !count ) { String orderExpression = JpaQueryUtils.createOrderExpression( convertedOrder, "u" ); hql += "order by " + StringUtils.defaultString( orderExpression, "u.surname, u.firstName" ); } // --------------------------------------------------------------------- // Query parameters // --------------------------------------------------------------------- log.debug( "User query HQL: '{}'", hql ); Query query = getQuery( hql ); if ( params.getQuery() != null ) { query.setParameter( "key", "%" + params.getQuery().toLowerCase() + "%" ); } if ( params.getPhoneNumber() != null ) { query.setParameter( "phoneNumber", params.getPhoneNumber() ); } if ( params.isCanManage() && params.getUser() != null ) { Collection<Long> managedGroups = IdentifiableObjectUtils .getIdentifiers( params.getUser().getManagedGroups() ); query.setParameterList( "ids", managedGroups ); } if ( params.getDisabled() != null ) { query.setParameter( "disabled", params.getDisabled() ); } if ( params.isAuthSubset() && params.getUser() != null ) { Set<String> auths = params.getUser().getUserCredentials().getAllAuthorities(); query.setParameterList( "auths", auths ); } if ( params.isDisjointRoles() && params.getUser() != null ) { Collection<Long> roles = IdentifiableObjectUtils .getIdentifiers( params.getUser().getUserCredentials().getUserAuthorityGroups() ); query.setParameterList( "roles", roles ); } if ( params.getLastLogin() != null ) { query.setParameter( "lastLogin", params.getLastLogin() ); } if ( params.getPasswordLastUpdated() != null ) { query.setParameter( "passwordLastUpdated", params.getPasswordLastUpdated() ); } if ( params.getInactiveSince() != null ) { query.setParameter( "inactiveSince", params.getInactiveSince() ); } if ( params.hasOrganisationUnits() ) { if ( params.isIncludeOrgUnitChildren() ) { for ( int i = 0; i < params.getOrganisationUnits().size(); i++ ) { query.setParameter( String.format( "ouUid%d", i ), "%/" + params.getOrganisationUnits().get( i ).getUid() + "%" ); } } else { Collection<Long> ouIds = IdentifiableObjectUtils.getIdentifiers( params.getOrganisationUnits() ); query.setParameterList( "ouIds", ouIds ); } } if ( params.hasUserGroups() ) { Collection<Long> userGroupIds = IdentifiableObjectUtils.getIdentifiers( params.getUserGroups() ); query.setParameterList( "userGroupIds", userGroupIds ); } if ( !count ) { if ( params.getFirst() != null ) { query.setFirstResult( params.getFirst() ); } if ( params.getMax() != null ) { query.setMaxResults( params.getMax() ); } } return query; } @Override public int getUserCount() { Query<Long> query = getTypedQuery( "select count(*) from User" ); return query.uniqueResult().intValue(); } @Override public User getUser( long id ) { return getSession().get( User.class, id ); } @Override public UserCredentials getUserCredentialsByUsername( String username ) { if ( username == null ) { return null; } String hql = "from UserCredentials uc where uc.username = :username"; TypedQuery<UserCredentials> typedQuery = sessionFactory.getCurrentSession().createQuery( hql, UserCredentials.class ); typedQuery.setParameter( "username", username ); typedQuery.setHint( QueryHints.CACHEABLE, true ); return QueryUtils.getSingleResult( typedQuery ); } @Override public CurrentUserGroupInfo getCurrentUserGroupInfo( long userId ) { CriteriaBuilder builder = getCriteriaBuilder(); CriteriaQuery<Object[]> query = builder.createQuery( Object[].class ); Root<User> root = query.from( User.class ); query.where( builder.equal( root.get( "id" ), userId ) ); query.select( builder.array( root.get( "uid" ), root.join( "groups", JoinType.LEFT ).get( "uid" ) ) ); List<Object[]> results = getSession().createQuery( query ).getResultList(); CurrentUserGroupInfo currentUserGroupInfo = new CurrentUserGroupInfo(); if ( CollectionUtils.isEmpty( results ) ) { return currentUserGroupInfo; } for ( Object[] result : results ) { if ( currentUserGroupInfo.getUserUID() == null ) { currentUserGroupInfo.setUserUID( result[0].toString() ); } if ( result[1] != null ) { currentUserGroupInfo.getUserGroupUIDs().add( result[1].toString() ); } } return currentUserGroupInfo; } }
dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/user/hibernate/HibernateUserStore.java
/* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.user.hibernate; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Root; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.hibernate.SessionFactory; import org.hibernate.annotations.QueryHints; import org.hibernate.query.Query; import org.hisp.dhis.common.IdentifiableObjectUtils; import org.hisp.dhis.common.hibernate.HibernateIdentifiableObjectStore; import org.hisp.dhis.commons.collection.CollectionUtils; import org.hisp.dhis.commons.util.SqlHelper; import org.hisp.dhis.commons.util.TextUtils; import org.hisp.dhis.query.JpaQueryUtils; import org.hisp.dhis.query.Order; import org.hisp.dhis.query.QueryUtils; import org.hisp.dhis.schema.Schema; import org.hisp.dhis.schema.SchemaService; import org.hisp.dhis.security.acl.AclService; import org.hisp.dhis.user.CurrentUserGroupInfo; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.hisp.dhis.user.UserCredentials; import org.hisp.dhis.user.UserInvitationStatus; import org.hisp.dhis.user.UserQueryParams; import org.hisp.dhis.user.UserStore; import org.springframework.context.ApplicationEventPublisher; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; /** * @author Nguyen Hong Duc */ @Slf4j @Repository( "org.hisp.dhis.user.UserStore" ) public class HibernateUserStore extends HibernateIdentifiableObjectStore<User> implements UserStore { private final SchemaService schemaService; public HibernateUserStore( SessionFactory sessionFactory, JdbcTemplate jdbcTemplate, ApplicationEventPublisher publisher, CurrentUserService currentUserService, AclService aclService, SchemaService schemaService ) { super( sessionFactory, jdbcTemplate, publisher, User.class, currentUserService, aclService, true ); checkNotNull( schemaService ); this.schemaService = schemaService; } @Override public void save( User user, boolean clearSharing ) { super.save( user, clearSharing ); currentUserService.invalidateUserGroupCache( user.getUsername() ); } @Override public List<User> getUsers( UserQueryParams params, @Nullable List<String> orders ) { return extractUserQueryUsers( getUserQuery( params, orders, false ).list() ); } @Override public List<User> getUsers( UserQueryParams params ) { return getUsers( params, null ); } @Override public List<User> getExpiringUsers( UserQueryParams params ) { return extractUserQueryUsers( getUserQuery( params, null, false ).list() ); } @Override public int getUserCount( UserQueryParams params ) { Long count = (Long) getUserQuery( params, null, true ).uniqueResult(); return count != null ? count.intValue() : 0; } @Nonnull private List<User> extractUserQueryUsers( @Nonnull List<?> result ) { if ( result.isEmpty() ) { return Collections.emptyList(); } final List<User> users = new ArrayList<>( result.size() ); for ( Object o : result ) { if ( o instanceof User ) { users.add( (User) o ); } else if ( o.getClass().isArray() ) { users.add( (User) ((Object[]) o)[0] ); } } return users; } private Query getUserQuery( UserQueryParams params, List<String> orders, boolean count ) { SqlHelper hlp = new SqlHelper(); List<Order> convertedOrder = null; String hql = null; if ( count ) { hql = "select count(distinct u) "; } else { Schema userSchema = schemaService.getSchema( User.class ); convertedOrder = QueryUtils.convertOrderStrings( orders, userSchema ); hql = Stream.of( "select distinct u", JpaQueryUtils.createSelectOrderExpression( convertedOrder, "u" ) ) .filter( Objects::nonNull ).collect( Collectors.joining( "," ) ); hql += " "; } hql += "from User u " + "inner join u.userCredentials uc "; if ( params.isPrefetchUserGroups() && !count ) { hql += "left join fetch u.groups g "; } else { hql += "left join u.groups g "; } if ( params.hasOrganisationUnits() ) { hql += "left join u.organisationUnits ou "; if ( params.isIncludeOrgUnitChildren() ) { hql += hlp.whereAnd() + " ("; for ( int i = 0; i < params.getOrganisationUnits().size(); i++ ) { hql += String.format( "ou.path like :ouUid%d or ", i ); } hql = TextUtils.removeLastOr( hql ) + ")"; } else { hql += hlp.whereAnd() + " ou.id in (:ouIds) "; } } if ( params.hasUserGroups() ) { hql += hlp.whereAnd() + " g.id in (:userGroupIds) "; } if ( params.getDisabled() != null ) { hql += hlp.whereAnd() + " uc.disabled = :disabled "; } if ( params.isNot2FA() ) { hql += hlp.whereAnd() + " uc.secret is null "; } if ( params.getQuery() != null ) { hql += hlp.whereAnd() + " (" + "concat(lower(u.firstName),' ',lower(u.surname)) like :key " + "or lower(u.email) like :key " + "or lower(uc.username) like :key) "; } if ( params.getPhoneNumber() != null ) { hql += hlp.whereAnd() + " u.phoneNumber = :phoneNumber "; } if ( params.isCanManage() && params.getUser() != null ) { hql += hlp.whereAnd() + " g.id in (:ids) "; } if ( params.isAuthSubset() && params.getUser() != null ) { hql += hlp.whereAnd() + " not exists (" + "select uc2 from UserCredentials uc2 " + "inner join uc2.userAuthorityGroups ag2 " + "inner join ag2.authorities a " + "where uc2.id = uc.id " + "and a not in (:auths) ) "; } // TODO handle users with no user roles if ( params.isDisjointRoles() && params.getUser() != null ) { hql += hlp.whereAnd() + " not exists (" + "select uc3 from UserCredentials uc3 " + "inner join uc3.userAuthorityGroups ag3 " + "where uc3.id = uc.id " + "and ag3.id in (:roles) ) "; } if ( params.getLastLogin() != null ) { hql += hlp.whereAnd() + " uc.lastLogin >= :lastLogin "; } if ( params.getInactiveSince() != null ) { hql += hlp.whereAnd() + " uc.lastLogin < :inactiveSince "; } if ( params.getPasswordLastUpdated() != null ) { hql += hlp.whereAnd() + " uc.passwordLastUpdated < :passwordLastUpdated "; } if ( params.isSelfRegistered() ) { hql += hlp.whereAnd() + " uc.selfRegistered = true "; } if ( UserInvitationStatus.ALL.equals( params.getInvitationStatus() ) ) { hql += hlp.whereAnd() + " uc.invitation = true "; } if ( UserInvitationStatus.EXPIRED.equals( params.getInvitationStatus() ) ) { hql += hlp.whereAnd() + " uc.invitation = true " + "and uc.restoreToken is not null " + "and uc.restoreExpiry is not null " + "and uc.restoreExpiry < current_timestamp() "; } if ( !count ) { String orderExpression = JpaQueryUtils.createOrderExpression( convertedOrder, "u" ); hql += "order by " + StringUtils.defaultString( orderExpression, "u.surname, u.firstName" ); } // --------------------------------------------------------------------- // Query parameters // --------------------------------------------------------------------- log.debug( "User query HQL: '{}'", hql ); Query query = getQuery( hql ); if ( params.getQuery() != null ) { query.setParameter( "key", "%" + params.getQuery().toLowerCase() + "%" ); } if ( params.getPhoneNumber() != null ) { query.setParameter( "phoneNumber", params.getPhoneNumber() ); } if ( params.isCanManage() && params.getUser() != null ) { Collection<Long> managedGroups = IdentifiableObjectUtils .getIdentifiers( params.getUser().getManagedGroups() ); query.setParameterList( "ids", managedGroups ); } if ( params.getDisabled() != null ) { query.setParameter( "disabled", params.getDisabled() ); } if ( params.isAuthSubset() && params.getUser() != null ) { Set<String> auths = params.getUser().getUserCredentials().getAllAuthorities(); query.setParameterList( "auths", auths ); } if ( params.isDisjointRoles() && params.getUser() != null ) { Collection<Long> roles = IdentifiableObjectUtils .getIdentifiers( params.getUser().getUserCredentials().getUserAuthorityGroups() ); query.setParameterList( "roles", roles ); } if ( params.getLastLogin() != null ) { query.setParameter( "lastLogin", params.getLastLogin() ); } if ( params.getPasswordLastUpdated() != null ) { query.setParameter( "passwordLastUpdated", params.getPasswordLastUpdated() ); } if ( params.getInactiveSince() != null ) { query.setParameter( "inactiveSince", params.getInactiveSince() ); } if ( params.hasOrganisationUnits() ) { if ( params.isIncludeOrgUnitChildren() ) { for ( int i = 0; i < params.getOrganisationUnits().size(); i++ ) { query.setParameter( String.format( "ouUid%d", i ), "%/" + params.getOrganisationUnits().get( i ).getUid() + "%" ); } } else { Collection<Long> ouIds = IdentifiableObjectUtils.getIdentifiers( params.getOrganisationUnits() ); query.setParameterList( "ouIds", ouIds ); } } if ( params.hasUserGroups() ) { Collection<Long> userGroupIds = IdentifiableObjectUtils.getIdentifiers( params.getUserGroups() ); query.setParameterList( "userGroupIds", userGroupIds ); } if ( !count ) { if ( params.getFirst() != null ) { query.setFirstResult( params.getFirst() ); } if ( params.getMax() != null ) { query.setMaxResults( params.getMax() ); } } return query; } @Override public int getUserCount() { Query<Long> query = getTypedQuery( "select count(*) from User" ); return query.uniqueResult().intValue(); } @Override public User getUser( long id ) { return getSession().get( User.class, id ); } @Override public UserCredentials getUserCredentialsByUsername( String username ) { if ( username == null ) { return null; } String hql = "from UserCredentials uc where uc.username = :username"; TypedQuery<UserCredentials> typedQuery = sessionFactory.getCurrentSession().createQuery( hql, UserCredentials.class ); typedQuery.setParameter( "username", username ); typedQuery.setHint( QueryHints.CACHEABLE, true ); return QueryUtils.getSingleResult( typedQuery ); } @Override public CurrentUserGroupInfo getCurrentUserGroupInfo( long userId ) { CriteriaBuilder builder = getCriteriaBuilder(); CriteriaQuery<Object[]> query = builder.createQuery( Object[].class ); Root<User> root = query.from( User.class ); query.where( builder.equal( root.get( "id" ), userId ) ); query.select( builder.array( root.get( "uid" ), root.join( "groups", JoinType.LEFT ).get( "uid" ) ) ); List<Object[]> results = getSession().createQuery( query ).getResultList(); CurrentUserGroupInfo currentUserGroupInfo = new CurrentUserGroupInfo(); if ( CollectionUtils.isEmpty( results ) ) { return currentUserGroupInfo; } for ( Object[] result : results ) { if ( currentUserGroupInfo.getUserUID() == null ) { currentUserGroupInfo.setUserUID( result[0].toString() ); } if ( result[1] != null ) { currentUserGroupInfo.getUserGroupUIDs().add( result[1].toString() ); } } return currentUserGroupInfo; } }
fix: performance improvement for users API when filtering with userCredentials.username (2.36) (#7165)
dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/user/hibernate/HibernateUserStore.java
fix: performance improvement for users API when filtering with userCredentials.username (2.36) (#7165)
<ide><path>his-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/user/hibernate/HibernateUserStore.java <ide> hql += " "; <ide> } <ide> <del> hql += "from User u " + <del> "inner join u.userCredentials uc "; <add> hql += "from User u "; <add> <add> if ( count ) <add> { <add> hql += "inner join u.userCredentials uc "; <add> } <add> else <add> { <add> hql += "inner join fetch u.userCredentials uc "; <add> } <ide> <ide> if ( params.isPrefetchUserGroups() && !count ) <ide> {
Java
apache-2.0
6f3d76cabe9d284f1400e7ee2657b7406b8bf779
0
google/mobly-bundled-snippets,lrbom/mobly-bundled-snippets
/* * Copyright (C) 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.mobly.snippet.bundled; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.support.test.InstrumentationRegistry; import com.google.android.mobly.snippet.Snippet; import com.google.android.mobly.snippet.bundled.utils.JsonSerializer; import com.google.android.mobly.snippet.bundled.utils.Utils; import com.google.android.mobly.snippet.rpc.Rpc; import com.google.android.mobly.snippet.rpc.RpcMinSdk; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; /** Snippet class exposing Android APIs in BluetoothAdapter. */ public class BluetoothAdapterSnippet implements Snippet { private static class BluetoothAdapterSnippetException extends Exception { private static final long serialVersionUID = 1; public BluetoothAdapterSnippetException(String msg) { super(msg); } } private final Context mContext; private final BluetoothAdapter mBluetoothAdapter; private final JsonSerializer mJsonSerializer = new JsonSerializer(); private final ArrayList<BluetoothDevice> mDiscoveryResults = new ArrayList<>(); private volatile boolean mIsScanResultAvailable = false; public BluetoothAdapterSnippet() { mContext = InstrumentationRegistry.getContext(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } @Rpc(description = "Enable bluetooth with a 30s timeout.") public void btEnable() throws BluetoothAdapterSnippetException, InterruptedException { if (!mBluetoothAdapter.enable()) { throw new BluetoothAdapterSnippetException("Failed to start enabling bluetooth"); } if (!Utils.waitUntil(() -> mBluetoothAdapter.isEnabled(), 30)) { throw new BluetoothAdapterSnippetException("Bluetooth did not turn on within 30s."); } } @Rpc(description = "Disable bluetooth with a 30s timeout.") public void btDisable() throws BluetoothAdapterSnippetException, InterruptedException { if (!mBluetoothAdapter.disable()) { throw new BluetoothAdapterSnippetException("Failed to start disabling bluetooth"); } if (!Utils.waitUntil(() -> !mBluetoothAdapter.isEnabled(), 30)) { throw new BluetoothAdapterSnippetException("Bluetooth did not turn off within 30s."); } } @Rpc( description = "Get bluetooth discovery results, which is a list of serialized BluetoothDevice objects." ) public JSONArray btGetCachedScanResults() throws JSONException { JSONArray results = new JSONArray(); for (BluetoothDevice result : mDiscoveryResults) { results.put(mJsonSerializer.toJson(result)); } return results; } @Rpc( description = "Start discovery, wait for discovery to complete, and return results, which is a list of " + "serialized BluetoothDevice objects." ) public JSONArray btDiscoveryAndGetResults() throws InterruptedException, JSONException, BluetoothAdapterSnippetException { IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } mDiscoveryResults.clear(); mIsScanResultAvailable = false; BroadcastReceiver receiver = new BluetoothScanReceiver(); mContext.registerReceiver(receiver, filter); try { if (!mBluetoothAdapter.startDiscovery()) { throw new BluetoothAdapterSnippetException( "Failed to initiate Bluetooth Discovery."); } if (!Utils.waitUntil(() -> mIsScanResultAvailable, 60)) { throw new BluetoothAdapterSnippetException( "Failed to get discovery results after 1 min, timeout!"); } } finally { mContext.unregisterReceiver(receiver); } return btGetCachedScanResults(); } @Rpc(description = "Get the list of paired bluetooth devices.") public JSONArray btGetPairedDevices() throws BluetoothAdapterSnippetException, InterruptedException, JSONException { JSONArray pairedDevices = new JSONArray(); for (BluetoothDevice device : mBluetoothAdapter.getBondedDevices()) { pairedDevices.put(mJsonSerializer.toJson(device)); } return pairedDevices; } /** * Enable Bluetooth HCI snoop log collection. * * <p>The file can be pulled from `/sdcard/btsnoop_hci.log`. * * @throws Throwable */ @RpcMinSdk(Build.VERSION_CODES.KITKAT) @Rpc(description = "Enable Bluetooth HCI snoop log for debugging.") public void btEnableHciSnoopLog() throws Throwable { boolean success; try { success = (boolean) mBluetoothAdapter .getClass() .getDeclaredMethod("configHciSnoopLog", boolean.class) .invoke(mBluetoothAdapter, true); } catch (InvocationTargetException e) { throw e.getCause(); } if (!success) { throw new BluetoothAdapterSnippetException("Failed to enable HCI snoop log."); } } @RpcMinSdk(Build.VERSION_CODES.KITKAT) @Rpc(description = "Disable Bluetooth HCI snoop log.") public void btDisableHciSnoopLog() throws Throwable { boolean success; try { success = (boolean) mBluetoothAdapter .getClass() .getDeclaredMethod("configHciSnoopLog", boolean.class) .invoke(mBluetoothAdapter, false); } catch (InvocationTargetException e) { throw e.getCause(); } if (!success) { throw new BluetoothAdapterSnippetException("Failed to disable HCI snoop log."); } } @Override public void shutdown() {} private class BluetoothScanReceiver extends BroadcastReceiver { /** * The receiver gets an ACTION_FOUND intent whenever a new device is found. * ACTION_DISCOVERY_FINISHED intent is received when the discovery process ends. */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { mIsScanResultAvailable = true; } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); mDiscoveryResults.add(device); } } } }
src/main/java/com/google/android/mobly/snippet/bundled/BluetoothAdapterSnippet.java
/* * Copyright (C) 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.mobly.snippet.bundled; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.support.test.InstrumentationRegistry; import com.google.android.mobly.snippet.Snippet; import com.google.android.mobly.snippet.bundled.utils.JsonSerializer; import com.google.android.mobly.snippet.bundled.utils.Utils; import com.google.android.mobly.snippet.rpc.Rpc; import com.google.android.mobly.snippet.rpc.RpcMinSdk; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; /** Snippet class exposing Android APIs in BluetoothAdapter. */ public class BluetoothAdapterSnippet implements Snippet { private static class BluetoothAdapterSnippetException extends Exception { private static final long serialVersionUID = 1; public BluetoothAdapterSnippetException(String msg) { super(msg); } } private final Context mContext; private final BluetoothAdapter mBluetoothAdapter; private final JsonSerializer mJsonSerializer = new JsonSerializer(); private final ArrayList<BluetoothDevice> mDiscoveryResults = new ArrayList<>(); private volatile boolean mIsScanResultAvailable = false; public BluetoothAdapterSnippet() { mContext = InstrumentationRegistry.getContext(); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } @Rpc(description = "Enable bluetooth with a 30s timeout.") public void btEnable() throws BluetoothAdapterSnippetException, InterruptedException { if (!mBluetoothAdapter.enable()) { throw new BluetoothAdapterSnippetException("Failed to start enabling bluetooth"); } if (!Utils.waitUntil(() -> mBluetoothAdapter.isEnabled(), 30)) { throw new BluetoothAdapterSnippetException("Bluetooth did not turn on within 30s."); } } @Rpc(description = "Disable bluetooth with a 30s timeout.") public void btDisable() throws BluetoothAdapterSnippetException, InterruptedException { if (!mBluetoothAdapter.disable()) { throw new BluetoothAdapterSnippetException("Failed to start disabling bluetooth"); } if (!Utils.waitUntil(() -> !mBluetoothAdapter.isEnabled(), 30)) { throw new BluetoothAdapterSnippetException("Bluetooth did not turn off within 30s."); } } @Rpc( description = "Get bluetooth discovery results, which is a list of serialized BluetoothDevice objects." ) public JSONArray btGetCachedScanResults() throws JSONException { JSONArray results = new JSONArray(); for (BluetoothDevice result : mDiscoveryResults) { results.put(mJsonSerializer.toJson(result)); } return results; } @Rpc( description = "Start discovery, wait for discovery to complete, and return results, which is a list of " + "serialized BluetoothDevice objects." ) public JSONArray btDiscoveryAndGetResults() throws InterruptedException, JSONException, BluetoothAdapterSnippetException { IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); if (mBluetoothAdapter.isDiscovering()) { mBluetoothAdapter.cancelDiscovery(); } mDiscoveryResults.clear(); mIsScanResultAvailable = false; BroadcastReceiver receiver = new BluetoothScanReceiver(); mContext.registerReceiver(receiver, filter); try { if (!mBluetoothAdapter.startDiscovery()) { throw new BluetoothAdapterSnippetException( "Failed to initiate Bluetooth Discovery."); } if (!Utils.waitUntil(() -> mIsScanResultAvailable, 60)) { throw new BluetoothAdapterSnippetException( "Failed to get discovery results after 1 min, timeout!"); } } finally { mContext.unregisterReceiver(receiver); } return btGetCachedScanResults(); } @Rpc(description = "Get the list of paired bluetooth devices.") public JSONArray btGetPairedDevices() throws BluetoothAdapterSnippetException, InterruptedException, JSONException { JSONArray pairedDevices = new JSONArray(); for (BluetoothDevice device : mBluetoothAdapter.getBondedDevices()) { pairedDevices.put(mJsonSerializer.toJson(device)); } return pairedDevices; } /** * Enable Bluetooth HCI snoop log collection. * * <p>The file can be pulled from `/sdcard/btsnoop_hci.log`. * * @return false if enabling the snoop log failed, true otherwise. * @throws Throwable */ @RpcMinSdk(Build.VERSION_CODES.KITKAT) @Rpc(description = "Enable Bluetooth HCI snoop log for debugging.") public boolean btEnableHciSnoopLog() throws Throwable { try { return (boolean) mBluetoothAdapter .getClass() .getDeclaredMethod("configHciSnoopLog", boolean.class) .invoke(mBluetoothAdapter, true); } catch (InvocationTargetException e) { throw e.getCause(); } } @RpcMinSdk(Build.VERSION_CODES.KITKAT) @Rpc(description = "Disable Bluetooth HCI snoop log.") public boolean btDisableHciSnoopLog() throws Throwable { try { return (boolean) mBluetoothAdapter .getClass() .getDeclaredMethod("configHciSnoopLog", boolean.class) .invoke(mBluetoothAdapter, false); } catch (InvocationTargetException e) { throw e.getCause(); } } @Override public void shutdown() {} private class BluetoothScanReceiver extends BroadcastReceiver { /** * The receiver gets an ACTION_FOUND intent whenever a new device is found. * ACTION_DISCOVERY_FINISHED intent is received when the discovery process ends. */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { mIsScanResultAvailable = true; } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); mDiscoveryResults.add(device); } } } }
Throw exceptions in case of failure to enable or disable HCI snoop log. (#42) Returning boolean is not consistent with our style and is not done for any other method in MBS.
src/main/java/com/google/android/mobly/snippet/bundled/BluetoothAdapterSnippet.java
Throw exceptions in case of failure to enable or disable HCI snoop log. (#42)
<ide><path>rc/main/java/com/google/android/mobly/snippet/bundled/BluetoothAdapterSnippet.java <ide> * <ide> * <p>The file can be pulled from `/sdcard/btsnoop_hci.log`. <ide> * <del> * @return false if enabling the snoop log failed, true otherwise. <ide> * @throws Throwable <ide> */ <ide> @RpcMinSdk(Build.VERSION_CODES.KITKAT) <ide> @Rpc(description = "Enable Bluetooth HCI snoop log for debugging.") <del> public boolean btEnableHciSnoopLog() throws Throwable { <add> public void btEnableHciSnoopLog() throws Throwable { <add> boolean success; <ide> try { <del> return (boolean) <del> mBluetoothAdapter <del> .getClass() <del> .getDeclaredMethod("configHciSnoopLog", boolean.class) <del> .invoke(mBluetoothAdapter, true); <add> success = <add> (boolean) <add> mBluetoothAdapter <add> .getClass() <add> .getDeclaredMethod("configHciSnoopLog", boolean.class) <add> .invoke(mBluetoothAdapter, true); <ide> } catch (InvocationTargetException e) { <ide> throw e.getCause(); <add> } <add> if (!success) { <add> throw new BluetoothAdapterSnippetException("Failed to enable HCI snoop log."); <ide> } <ide> } <ide> <ide> @RpcMinSdk(Build.VERSION_CODES.KITKAT) <ide> @Rpc(description = "Disable Bluetooth HCI snoop log.") <del> public boolean btDisableHciSnoopLog() throws Throwable { <add> public void btDisableHciSnoopLog() throws Throwable { <add> boolean success; <ide> try { <del> return (boolean) <del> mBluetoothAdapter <del> .getClass() <del> .getDeclaredMethod("configHciSnoopLog", boolean.class) <del> .invoke(mBluetoothAdapter, false); <add> success = <add> (boolean) <add> mBluetoothAdapter <add> .getClass() <add> .getDeclaredMethod("configHciSnoopLog", boolean.class) <add> .invoke(mBluetoothAdapter, false); <ide> } catch (InvocationTargetException e) { <ide> throw e.getCause(); <add> } <add> if (!success) { <add> throw new BluetoothAdapterSnippetException("Failed to disable HCI snoop log."); <ide> } <ide> } <ide>
Java
apache-2.0
2f83547d402c552be1e18074531385a6bf9ca14f
0
eFaps/eFapsApp-JMS
/* * Copyright 2003 - 2011 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.esjp.jms.attributes; import java.util.UUID; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.efaps.admin.datamodel.Status; import org.efaps.util.cache.CacheReloadException; /** * TODO comment! * * @author The eFaps Team * @version $Id$ */ @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = "attribute.status") public class StatusAttribute extends AbstractAttribute<Long> { /** * The actual value. */ @XmlAttribute private Long value; /** * The key to the Status. */ @XmlElement private String statusKey; /** * The UUID of the Status Type. */ @XmlElement private UUID statusUUID; /** * Standard Constructor. */ public StatusAttribute() { super(); } /** * Constructor setting the value. * @param _value value for this attribute */ public StatusAttribute(final Long _value) { super(); this.value = _value; } /** * Constructor setting the value. * @param _statusUUID UUID of the Status Type * @param _statusKey key of the Status */ public StatusAttribute(final UUID _statusUUID, final String _statusKey) { super(); this.value = Long.valueOf(0); this.statusUUID = _statusUUID; this.statusKey = _statusKey; } /** * Getter method for the instance variable {@link #statusKey}. * * @return value of instance variable {@link #statusKey} */ public String getStatusKey() { return this.statusKey; } /** * Setter method for instance variable {@link #statusKey}. * * @param _statusKey value for instance variable {@link #statusKey} */ public void setStatusKey(final String _statusKey) { this.statusKey = _statusKey; } /** * Getter method for the instance variable {@link #statusUUID}. * * @return value of instance variable {@link #statusUUID} */ public UUID getStatusUUID() { return this.statusUUID; } /** * Setter method for instance variable {@link #statusUUID}. * * @param _statusUUID value for instance variable {@link #statusUUID} */ public void setStatusUUID(final UUID _statusUUID) { this.statusUUID = _statusUUID; } /** * Getter method for the instance variable {@link #value}. * * @return value of instance variable {@link #value} */ public Long getValue() { Long ret = this.value; if (ret == 0) { Status status = null; try { status = Status.find(this.statusUUID, this.statusKey); } catch (final CacheReloadException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (status != null) { ret = status.getId(); } } return ret; } /** * Setter method for instance variable {@link #value}. * * @param _value value for instance variable {@link #value} */ public void setValue(final Object _value) { this.value = (Long) _value; } }
src/main/efaps/ESJP/org/efaps/esjp/jms/attributes/StatusAttribute.java
/* * Copyright 2003 - 2011 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Revision: $Rev$ * Last Changed: $Date$ * Last Changed By: $Author$ */ package org.efaps.esjp.jms.attributes; import java.util.UUID; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.efaps.admin.datamodel.Status; /** * TODO comment! * * @author The eFaps Team * @version $Id$ */ @XmlAccessorType(XmlAccessType.NONE) @XmlType(name = "attribute.status") public class StatusAttribute extends AbstractAttribute<Long> { /** * The actual value. */ @XmlAttribute private Long value; /** * The key to the Status. */ @XmlElement private String statusKey; /** * The UUID of the Status Type. */ @XmlElement private UUID statusUUID; /** * Standard Constructor. */ public StatusAttribute() { super(); } /** * Constructor setting the value. * @param _value value for this attribute */ public StatusAttribute(final Long _value) { super(); this.value = _value; } /** * Constructor setting the value. * @param _statusUUID UUID of the Status Type * @param _statusKey key of the Status */ public StatusAttribute(final UUID _statusUUID, final String _statusKey) { super(); this.value = Long.valueOf(0); this.statusUUID = _statusUUID; this.statusKey = _statusKey; } /** * Getter method for the instance variable {@link #statusKey}. * * @return value of instance variable {@link #statusKey} */ public String getStatusKey() { return this.statusKey; } /** * Setter method for instance variable {@link #statusKey}. * * @param _statusKey value for instance variable {@link #statusKey} */ public void setStatusKey(final String _statusKey) { this.statusKey = _statusKey; } /** * Getter method for the instance variable {@link #statusUUID}. * * @return value of instance variable {@link #statusUUID} */ public UUID getStatusUUID() { return this.statusUUID; } /** * Setter method for instance variable {@link #statusUUID}. * * @param _statusUUID value for instance variable {@link #statusUUID} */ public void setStatusUUID(final UUID _statusUUID) { this.statusUUID = _statusUUID; } /** * Getter method for the instance variable {@link #value}. * * @return value of instance variable {@link #value} */ public Long getValue() { Long ret = this.value; if (ret == 0) { final Status status = Status.find(this.statusUUID, this.statusKey); if (status != null) { ret = status.getId(); } } return ret; } /** * Setter method for instance variable {@link #value}. * * @param _value value for instance variable {@link #value} */ public void setValue(final Object _value) { this.value = (Long) _value; } }
- jms: correction of esjp to throw exception git-svn-id: b368d13e588665476b8ac787ee6203fb6ee534e1@8862 fee104cc-1dfa-8c0f-632d-d3b7e6b59fb0
src/main/efaps/ESJP/org/efaps/esjp/jms/attributes/StatusAttribute.java
- jms: correction of esjp to throw exception
<ide><path>rc/main/efaps/ESJP/org/efaps/esjp/jms/attributes/StatusAttribute.java <ide> import javax.xml.bind.annotation.XmlType; <ide> <ide> import org.efaps.admin.datamodel.Status; <add>import org.efaps.util.cache.CacheReloadException; <ide> <ide> <ide> /** <ide> { <ide> Long ret = this.value; <ide> if (ret == 0) { <del> final Status status = Status.find(this.statusUUID, this.statusKey); <add> Status status = null; <add> try { <add> status = Status.find(this.statusUUID, this.statusKey); <add> } catch (final CacheReloadException e) { <add> // TODO Auto-generated catch block <add> e.printStackTrace(); <add> } <ide> if (status != null) { <ide> ret = status.getId(); <ide> }
Java
lgpl-2.1
8c1e0132ae32d14c865414c6704bbc5ffba92f23
0
languagetool-org/languagetool,janissl/languagetool,languagetool-org/languagetool,lopescan/languagetool,janissl/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,meg0man/languagetool,meg0man/languagetool,jimregan/languagetool,meg0man/languagetool,jimregan/languagetool,jimregan/languagetool,janissl/languagetool,lopescan/languagetool,languagetool-org/languagetool,janissl/languagetool,jimregan/languagetool,lopescan/languagetool,lopescan/languagetool,meg0man/languagetool,meg0man/languagetool,janissl/languagetool,lopescan/languagetool,janissl/languagetool,jimregan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ /* * Created on 01.10.2010 */ package de.danielnaber.languagetool.tagging.eo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.danielnaber.languagetool.AnalyzedToken; import de.danielnaber.languagetool.AnalyzedTokenReadings; import de.danielnaber.languagetool.JLanguageTool; import de.danielnaber.languagetool.tagging.Tagger; /** * A part-of-speech tagger for Esperanto. * * @author Dominique Pellé */ public class EsperantoTagger implements Tagger { // These words don't need to be tagged. private final static String wordsNotTagged[] = { "ajn", "ĉi", "des", "do", "ja", "ju", "ke", "malpli", "ne", "nek", "ol", "pli" }; private final static Set setWordsNotTagged = new HashSet<String>(Arrays.asList(wordsNotTagged)); // Following preposition are never followed by accusative. private final static String prepositionsNoAccusative[] = { "al", "apud", "cis", "da", "de", "dum", "el", "far", "ĝis", "je", "kun", "laŭ", "malgraŭ", "na", "per", "po", "post", "por", "pri", "pro", "sen", "super", "tra" }; private final static Set setPrepositionsNoAccusative = new HashSet<String>(Arrays.asList(prepositionsNoAccusative)); // Following preposition may be followed by accusative. private final static String prepositionsAccusative[] = { "anstataŭ", "en", "kontraŭ", "krom", "sur", "sub", "trans", "preter", "ĉirkaŭ", "antaŭ", "malantaŭ", "ekster", "inter", "ĉe" }; private final Set setPrepositionsAccusative = new HashSet<String>(Arrays.asList(prepositionsAccusative)); // Conjunctions. private final static String conjunctions[] = { "ĉar", "kaj", "aŭ", "sed", "plus", "minus", "tamen" }; private final static Set setConjunctions = new HashSet<String>(Arrays.asList(conjunctions)); // Numbers. private final static String numbers[] = { "nul", "unu", "du", "tri", "kvar", "kvin", "ses", "sep", "ok", "naŭ", "dek", "cent", "mil" }; private final static Set setNumbers = new HashSet<String>(Arrays.asList(numbers)); // Adverbs which do not end in -e private final static String adverbs[] = { "ankoraŭ", "almenaŭ", "apenaŭ", "baldaŭ", "preskaŭ", "eĉ", "jam", "jen", "ĵus", "morgaŭ", "hodiaŭ", "hieraŭ", "nun", "nur", "plu", "tre", "tro", "tuj", "for" }; private final static Set setAdverbs = new HashSet<String>(Arrays.asList(adverbs)); // Set of transitive verbs and non-transitive verbs. private Set setTransitiveVerbs = null; private Set setNonTransitiveVerbs = null; // Verbs always end with this pattern. private final static Pattern patternVerb1 = Pattern.compile("(.*)(as|os|is|us|u|i)$"); private final static Pattern patternVerb2 = Pattern.compile(".*(ig|iĝ)(.s|.)$"); // Particips -ant-, -int, ont-, -it-, -it-, -ot- // TODO: this is not used yet. final Pattern patternParticiple = Pattern.compile("(.*)([aio])(n?)t([aoe])(j?)(n?)$"); // Groups 11 22222 33 44444 55 66 // Pattern 'tabelvortoj'. final Pattern patternTabelvorto = Pattern.compile("^(i|ti|ki|ĉi|neni)((([uoae])(j?)(n?))|(am|al|es|el|om))$"); // Groups 111111111111111 22222222222222222222222222222222 // 3333333333333333 77777777777 // 444444 55 66 /** * Load list of words from UTF-8 file (one word per line). */ private Set loadWords(final InputStream file) throws IOException { InputStreamReader isr = null; BufferedReader br = null; final Set<String> words = new HashSet<String>(); try { isr = new InputStreamReader(file, "UTF-8"); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() < 1) { continue; } if (line.charAt(0) == '#') { // ignore comments continue; } words.add(line); } } finally { if (br != null) { br.close(); } if (isr != null) { isr.close(); } } return words; } private void lazyInit() throws IOException { if (setTransitiveVerbs != null) { return; } // Load set of transitive and non-transitive verbs. Files don't contain // verbs with suffix -iĝ or -ig since transitivity is obvious for those verbs. // They also don't contain verbs with prefixes mal-, ek-, re-, mis- fi- and // suffixes -ad, -aĉ, -et, -eg since these affixes never alter transitivity. setTransitiveVerbs = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream("/eo/verb-tr.txt")); setNonTransitiveVerbs = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream("/eo/verb-ntr.txt")); } public List<AnalyzedTokenReadings> tag(final List<String> sentenceTokens) throws IOException { lazyInit(); Matcher matcher; final List<AnalyzedTokenReadings> tokenReadings = new ArrayList<AnalyzedTokenReadings>(); int pos = 0; for (String word : sentenceTokens) { final List<AnalyzedToken> l = new ArrayList<AnalyzedToken>(); final String lWord = word.toLowerCase(); if (lWord.equals(".")) { l.add(new AnalyzedToken(word, "M fino", lWord)); } else if (lWord.equals("?")) { l.add(new AnalyzedToken(word, "M fino dem", lWord)); } else if (lWord.equals("!")) { l.add(new AnalyzedToken(word, "M fino kri", lWord)); } else if (lWord.equals("la")) { l.add(new AnalyzedToken(word, "D", lWord)); } else if (setAdverbs.contains(lWord)) { l.add(new AnalyzedToken(word, "E nak", lWord)); } else if (setWordsNotTagged.contains(lWord)) { l.add(new AnalyzedToken(word, null, lWord)); // Pronouns. } else if (lWord.equals("mi") || lWord.equals("ci") || lWord.equals("li") || lWord.equals("ŝi") || lWord.equals("ĝi") || lWord.equals("si") || lWord.equals("oni")) { l.add(new AnalyzedToken(word, "R nak np", lWord)); } else if (lWord.equals("min") || lWord.equals("cin") || lWord.equals("lin") || lWord.equals("ŝin") || lWord.equals("ĝin") || lWord.equals("sin")) { l.add(new AnalyzedToken(word, "R akz np", lWord.substring(0, lWord.length() - 1))); } else if (lWord.equals("ni") || lWord.equals("ili")) { l.add(new AnalyzedToken(word, "R nak pl", lWord)); } else if (lWord.equals("nin") || lWord.equals("ilin")) { l.add(new AnalyzedToken(word, "R akz pl", lWord.substring(0, lWord.length() - 1))); } else if (lWord.equals("vi")) { l.add(new AnalyzedToken(word, "R nak pn", lWord)); } else if (lWord.equals("vin")) { l.add(new AnalyzedToken(word, "R akz pn", lWord.substring(0, lWord.length() - 1))); // Conjunctions (kaj, sed, ...) } else if (setConjunctions.contains(lWord)) { l.add(new AnalyzedToken(word, "K", lWord)); // Prepositions. } else if (setPrepositionsNoAccusative.contains(lWord)) { l.add(new AnalyzedToken(word, "P sak", lWord)); } else if (setPrepositionsAccusative.contains(lWord)) { l.add(new AnalyzedToken(word, "P kak", lWord)); } else if (setNumbers.contains(lWord)) { l.add(new AnalyzedToken(word, "N", lWord)); // Tiu, kiu (tabelvortoj). } else if ((matcher = patternTabelvorto.matcher(lWord)).find()) { final String type1Group = matcher.group(1).substring(0, 1).toLowerCase(); final String type2Group = matcher.group(4); final String plGroup = matcher.group(5); final String accGroup = matcher.group(6); final String type3Group = matcher.group(7); final String type; final String plural; final String accusative; if (accGroup == null) { accusative = "xxx"; } else { accusative = accGroup.toLowerCase().equals("n") ? "akz" : "nak"; } if (plGroup == null) { plural = " pn "; } else { plural = plGroup.toLowerCase().equals("j") ? " pl " : " np "; } type = ((type2Group == null) ? type3Group : type2Group).toLowerCase(); l.add(new AnalyzedToken(word, "T " + accusative + plural + type1Group + " " + type, null)); // Words ending in .*oj?n? are nouns. } else if (lWord.endsWith("o")) { l.add(new AnalyzedToken(word, "O nak np", lWord)); } else if (lWord.endsWith("oj")) { l.add(new AnalyzedToken(word, "O nak pl", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("on")) { l.add(new AnalyzedToken(word, "O akz np", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("ojn")) { l.add(new AnalyzedToken(word, "O akz pl", lWord.substring(0, lWord.length() - 2))); // Words ending in .*aj?n? are nouns. } else if (lWord.endsWith("a")) { l.add(new AnalyzedToken(word, "A nak np", lWord)); } else if (lWord.endsWith("aj")) { l.add(new AnalyzedToken(word, "A nak pl", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("an")) { l.add(new AnalyzedToken(word, "A akz np", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("ajn")) { l.add(new AnalyzedToken(word, "A akz pl", lWord.substring(0, lWord.length() - 2))); // Words ending in .*en? are adverbs. } else if (lWord.endsWith("e")) { l.add(new AnalyzedToken(word, "E nak", lWord)); } else if (lWord.endsWith("en")) { l.add(new AnalyzedToken(word, "E akz", lWord.substring(0, lWord.length() - 1))); // Verbs. } else if ((matcher = patternVerb1.matcher(lWord)).find()) { final String verb = matcher.group(1) + "i"; final String tense = matcher.group(2); final String transitive; final Matcher matcher2 = patternVerb2.matcher(lWord); if (matcher2.find()) { transitive = matcher2.group(1).equals("ig") ? "tr" : "nt"; } else { final boolean isTransitive = setTransitiveVerbs.contains(verb); final boolean isIntransitive = setNonTransitiveVerbs.contains(verb); if (isTransitive) { transitive = isIntransitive ? "tn" : "tr"; } else { transitive = isIntransitive ? "nt" : "tn"; } } l.add(new AnalyzedToken(word, "V " + transitive + " " + tense, verb)); // Irregular word (no tag). } else { l.add(new AnalyzedToken(word, null, null)); } // Participle (can be combined with other tags). if ((matcher = patternParticiple.matcher(lWord)).find()) { final String verb = matcher.group(1) + "i"; final String aio = matcher.group(2); final String antAt = matcher.group(3).equals("n") ? "n" : "-"; final String aoe = matcher.group(4); final String plural = matcher.group(5).equals("j") ? "pl" : "np"; final String accusative = matcher.group(6).equals("n") ? "akz" : "nak"; final String transitive; final Matcher matcher2 = patternVerb2.matcher(lWord); if (matcher2.find()) { transitive = matcher2.group(1).equals("ig") ? "tr" : "nt"; } else { final boolean isTransitive = setTransitiveVerbs.contains(verb); final boolean isIntransitive = setNonTransitiveVerbs.contains(verb); if (isTransitive) { transitive = isIntransitive ? "tn" : "tr"; } else { transitive = isIntransitive ? "nt" : "tn"; } } l.add(new AnalyzedToken(word, "C " + accusative + " " + plural + " " + transitive + " " + aio + " " + antAt + " " + aoe, verb)); } pos += word.length(); tokenReadings.add(new AnalyzedTokenReadings( l.toArray(new AnalyzedToken[0]), 0)); } return tokenReadings; } public AnalyzedTokenReadings createNullToken(String token, int startPos) { return new AnalyzedTokenReadings( new AnalyzedToken(token, null, null), startPos); } public AnalyzedToken createToken(String token, String posTag) { return new AnalyzedToken(token, posTag, null); } }
trunk/JLanguageTool/src/java/de/danielnaber/languagetool/tagging/eo/EsperantoTagger.java
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ /* * Created on 01.10.2010 */ package de.danielnaber.languagetool.tagging.eo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.ArrayList; import java.util.List; import java.util.HashSet; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.danielnaber.languagetool.AnalyzedToken; import de.danielnaber.languagetool.AnalyzedTokenReadings; import de.danielnaber.languagetool.JLanguageTool; import de.danielnaber.languagetool.tagging.Tagger; /** * A part-of-speech tagger for Esperanto. * * @author Dominique Pellé */ public class EsperantoTagger implements Tagger { // These words don't need to be tagged. private final static String wordsNotTagged[] = { "ajn", "ĉi", "des", "do", "ja", "ju", "ke", "malpli", "ne", "nek", "ol", "pli" }; private final static Set setWordsNotTagged = new HashSet<String>(Arrays.asList(wordsNotTagged)); // Following preposition are never followed by accusative. private final static String prepositionsNoAccusative[] = { "al", "apud", "cis", "da", "de", "dum", "el", "far", "ĝis", "je", "kun", "laŭ", "malgraŭ", "na", "per", "po", "post", "por", "pri", "pro", "sen", "super", "tra" }; private final static Set setPrepositionsNoAccusative = new HashSet<String>(Arrays.asList(prepositionsNoAccusative)); // Following preposition may be followed by accusative. private final static String prepositionsAccusative[] = { "anstataŭ", "en", "kontraŭ", "krom", "sur", "sub", "trans", "preter", "ĉirkaŭ", "antaŭ", "ekster", "inter", "ĉe" }; private final Set setPrepositionsAccusative = new HashSet<String>(Arrays.asList(prepositionsAccusative)); // Conjunctions. private final static String conjunctions[] = { "ĉar", "kaj", "aŭ", "sed", "plus", "minus", "tamen" }; private final static Set setConjunctions = new HashSet<String>(Arrays.asList(conjunctions)); // Numbers. private final static String numbers[] = { "nul", "unu", "du", "tri", "kvar", "kvin", "ses", "sep", "ok", "naŭ", "dek", "cent", "mil" }; private final static Set setNumbers = new HashSet<String>(Arrays.asList(numbers)); // Adverbs which do not end in -e private final static String adverbs[] = { "ankoraŭ", "almenaŭ", "apenaŭ", "baldaŭ", "preskaŭ", "eĉ", "jam", "jen", "ĵus", "morgaŭ", "hodiaŭ", "hieraŭ", "nun", "nur", "plu", "tre", "tro", "tuj", "for" }; private final static Set setAdverbs = new HashSet<String>(Arrays.asList(adverbs)); // Set of transitive verbs and non-transitive verbs. private Set setTransitiveVerbs = null; private Set setNonTransitiveVerbs = null; // Verbs always end with this pattern. private final static Pattern patternVerb1 = Pattern.compile("(.*)(as|os|is|us|u|i)$"); private final static Pattern patternVerb2 = Pattern.compile(".*(ig|iĝ)(.s|.)$"); // Particips -ant-, -int, ont-, -it-, -it-, -ot- // TODO: this is not used yet. final Pattern patternParticiple = Pattern.compile("(.*)([aio])(n?)t([aoe])(j?)(n?)$"); // Groups 11 22222 33 44444 55 66 // Pattern 'tabelvortoj'. final Pattern patternTabelvorto = Pattern.compile("^(i|ti|ki|ĉi|neni)((([uoae])(j?)(n?))|(am|al|es|el|om))$"); // Groups 111111111111111 22222222222222222222222222222222 // 3333333333333333 77777777777 // 444444 55 66 /** * Load list of words from UTF-8 file (one word per line). */ private Set loadWords(final InputStream file) throws IOException { InputStreamReader isr = null; BufferedReader br = null; final Set<String> words = new HashSet<String>(); try { isr = new InputStreamReader(file, "UTF-8"); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() < 1) { continue; } if (line.charAt(0) == '#') { // ignore comments continue; } words.add(line); } } finally { if (br != null) { br.close(); } if (isr != null) { isr.close(); } } return words; } private void lazyInit() throws IOException { if (setTransitiveVerbs != null) { return; } // Load set of transitive and non-transitive verbs. Files don't contain // verbs with suffix -iĝ or -ig since transitivity is obvious for those verbs. // They also don't contain verbs with prefixes mal-, ek-, re-, mis- fi- and // suffixes -ad, -aĉ, -et, -eg since these affixes never alter transitivity. setTransitiveVerbs = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream("/eo/verb-tr.txt")); setNonTransitiveVerbs = loadWords(JLanguageTool.getDataBroker().getFromRulesDirAsStream("/eo/verb-ntr.txt")); } public List<AnalyzedTokenReadings> tag(final List<String> sentenceTokens) throws IOException { lazyInit(); Matcher matcher; final List<AnalyzedTokenReadings> tokenReadings = new ArrayList<AnalyzedTokenReadings>(); int pos = 0; for (String word : sentenceTokens) { final List<AnalyzedToken> l = new ArrayList<AnalyzedToken>(); final String lWord = word.toLowerCase(); if (lWord.equals(".")) { l.add(new AnalyzedToken(word, "M fino", lWord)); } else if (lWord.equals("?")) { l.add(new AnalyzedToken(word, "M fino dem", lWord)); } else if (lWord.equals("!")) { l.add(new AnalyzedToken(word, "M fino kri", lWord)); } else if (lWord.equals("la")) { l.add(new AnalyzedToken(word, "D", lWord)); } else if (setAdverbs.contains(lWord)) { l.add(new AnalyzedToken(word, "E nak", lWord)); } else if (setWordsNotTagged.contains(lWord)) { l.add(new AnalyzedToken(word, null, lWord)); // Pronouns. } else if (lWord.equals("mi") || lWord.equals("ci") || lWord.equals("li") || lWord.equals("ŝi") || lWord.equals("ĝi") || lWord.equals("si") || lWord.equals("oni")) { l.add(new AnalyzedToken(word, "R nak np", lWord)); } else if (lWord.equals("min") || lWord.equals("cin") || lWord.equals("lin") || lWord.equals("ŝin") || lWord.equals("ĝin") || lWord.equals("sin")) { l.add(new AnalyzedToken(word, "R akz np", lWord.substring(0, lWord.length() - 1))); } else if (lWord.equals("ni") || lWord.equals("ili")) { l.add(new AnalyzedToken(word, "R nak pl", lWord)); } else if (lWord.equals("nin") || lWord.equals("ilin")) { l.add(new AnalyzedToken(word, "R akz pl", lWord.substring(0, lWord.length() - 1))); } else if (lWord.equals("vi")) { l.add(new AnalyzedToken(word, "R nak pn", lWord)); } else if (lWord.equals("vin")) { l.add(new AnalyzedToken(word, "R akz pn", lWord.substring(0, lWord.length() - 1))); // Conjunctions (kaj, sed, ...) } else if (setConjunctions.contains(lWord)) { l.add(new AnalyzedToken(word, "K", lWord)); // Prepositions. } else if (setPrepositionsNoAccusative.contains(lWord)) { l.add(new AnalyzedToken(word, "P sak", lWord)); } else if (setPrepositionsAccusative.contains(lWord)) { l.add(new AnalyzedToken(word, "P kak", lWord)); } else if (setNumbers.contains(lWord)) { l.add(new AnalyzedToken(word, "N", lWord)); // Tiu, kiu (tabelvortoj). } else if ((matcher = patternTabelvorto.matcher(lWord)).find()) { final String type1Group = matcher.group(1).substring(0, 1).toLowerCase(); final String type2Group = matcher.group(4); final String plGroup = matcher.group(5); final String accGroup = matcher.group(6); final String type3Group = matcher.group(7); final String type; final String plural; final String accusative; if (accGroup == null) { accusative = "xxx"; } else { accusative = accGroup.toLowerCase().equals("n") ? "akz" : "nak"; } if (plGroup == null) { plural = " pn "; } else { plural = plGroup.toLowerCase().equals("j") ? " pl " : " np "; } type = ((type2Group == null) ? type3Group : type2Group).toLowerCase(); l.add(new AnalyzedToken(word, "T " + accusative + plural + type1Group + " " + type, null)); // Words ending in .*oj?n? are nouns. } else if (lWord.endsWith("o")) { l.add(new AnalyzedToken(word, "O nak np", lWord)); } else if (lWord.endsWith("oj")) { l.add(new AnalyzedToken(word, "O nak pl", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("on")) { l.add(new AnalyzedToken(word, "O akz np", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("ojn")) { l.add(new AnalyzedToken(word, "O akz pl", lWord.substring(0, lWord.length() - 2))); // Words ending in .*aj?n? are nouns. } else if (lWord.endsWith("a")) { l.add(new AnalyzedToken(word, "A nak np", lWord)); } else if (lWord.endsWith("aj")) { l.add(new AnalyzedToken(word, "A nak pl", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("an")) { l.add(new AnalyzedToken(word, "A akz np", lWord.substring(0, lWord.length() - 1))); } else if (lWord.endsWith("ajn")) { l.add(new AnalyzedToken(word, "A akz pl", lWord.substring(0, lWord.length() - 2))); // Words ending in .*en? are adverbs. } else if (lWord.endsWith("e")) { l.add(new AnalyzedToken(word, "E nak", lWord)); } else if (lWord.endsWith("en")) { l.add(new AnalyzedToken(word, "E akz", lWord.substring(0, lWord.length() - 1))); // Verbs. } else if ((matcher = patternVerb1.matcher(lWord)).find()) { final String verb = matcher.group(1) + "i"; final String tense = matcher.group(2); final String transitive; final Matcher matcher2 = patternVerb2.matcher(lWord); if (matcher2.find()) { transitive = matcher2.group(1).equals("ig") ? "tr" : "nt"; } else { final boolean isTransitive = setTransitiveVerbs.contains(verb); final boolean isIntransitive = setNonTransitiveVerbs.contains(verb); if (isTransitive) { transitive = isIntransitive ? "tn" : "tr"; } else { transitive = isIntransitive ? "nt" : "tn"; } } l.add(new AnalyzedToken(word, "V " + transitive + " " + tense, verb)); // Irregular word (no tag). } else { l.add(new AnalyzedToken(word, null, null)); } // Participle (can be combined with other tags). if ((matcher = patternParticiple.matcher(lWord)).find()) { final String verb = matcher.group(1) + "i"; final String aio = matcher.group(2); final String antAt = matcher.group(3).equals("n") ? "n" : "-"; final String aoe = matcher.group(4); final String plural = matcher.group(5).equals("j") ? "pl" : "np"; final String accusative = matcher.group(6).equals("n") ? "akz" : "nak"; final String transitive; final Matcher matcher2 = patternVerb2.matcher(lWord); if (matcher2.find()) { transitive = matcher2.group(1).equals("ig") ? "tr" : "nt"; } else { final boolean isTransitive = setTransitiveVerbs.contains(verb); final boolean isIntransitive = setNonTransitiveVerbs.contains(verb); if (isTransitive) { transitive = isIntransitive ? "tn" : "tr"; } else { transitive = isIntransitive ? "nt" : "tn"; } } l.add(new AnalyzedToken(word, "C " + accusative + " " + plural + " " + transitive + " " + aio + " " + antAt + " " + aoe, verb)); } pos += word.length(); tokenReadings.add(new AnalyzedTokenReadings( l.toArray(new AnalyzedToken[0]), 0)); } return tokenReadings; } public AnalyzedTokenReadings createNullToken(String token, int startPos) { return new AnalyzedTokenReadings( new AnalyzedToken(token, null, null), startPos); } public AnalyzedToken createToken(String token, String posTag) { return new AnalyzedToken(token, posTag, null); } }
[eo] Esperanto preposition "malantaÅ­" was not tagged.
trunk/JLanguageTool/src/java/de/danielnaber/languagetool/tagging/eo/EsperantoTagger.java
[eo] Esperanto preposition "malantaÅ­" was not tagged.
<ide><path>runk/JLanguageTool/src/java/de/danielnaber/languagetool/tagging/eo/EsperantoTagger.java <ide> // Following preposition may be followed by accusative. <ide> private final static String prepositionsAccusative[] = { <ide> "anstataŭ", "en", "kontraŭ", "krom", "sur", "sub", "trans", <del> "preter", "ĉirkaŭ", "antaŭ", "ekster", "inter", "ĉe" <add> "preter", "ĉirkaŭ", "antaŭ", "malantaŭ", "ekster", "inter", "ĉe" <ide> }; <ide> <ide> private final Set setPrepositionsAccusative =
JavaScript
bsd-2-clause
edfd5db24fc8336003382f129f38287f6ca18053
0
bubenkoff/Arkestra,evildmp/Arkestra,bubenkoff/Arkestra,evildmp/Arkestra,evildmp/Arkestra,bubenkoff/Arkestra
/** * @name MarkerWithLabel for V3 * @version 1.1.8 [February 26, 2013] * @author Gary Little (inspired by code from Marc Ridey of Google). * @copyright Copyright 2012 Gary Little [gary at luxcentral.com] * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 * <code>google.maps.Marker</code> class. * <p> * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser:true */ /*global document,google */ /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. */ function inherits(childCtor, parentCtor) { /** @constructor */ function tempCtor() {}; tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @override */ childCtor.prototype.constructor = childCtor; } /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @param {string} crossURL The URL of the cross image =. * @param {string} handCursor The URL of the hand cursor. * @private */ function MarkerLabel_(marker, crossURL, handCursorURL) { this.marker_ = marker; this.handCursorURL_ = marker.handCursorURL; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); } inherits(MarkerLabel_, google.maps.OverlayView); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @param {string} crossURL The URL of the cross image =. * @private */ MarkerLabel_.getSharedCross = function (crossURL) { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = crossURL; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; this.labelDiv_.parentNode.removeChild(this.labelDiv_); this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] * The URL of the cross image to be displayed while dragging a marker. * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] * The URL of the cursor to be displayed while dragging a marker. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } inherits(MarkerWithLabel, google.maps.Marker); /** * Overrides the standard Marker setMap function. * @param {Map} theMap The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); };
arkestra_utilities/static/arkestra/js/maps/markerwithlabel.js
/** * @name MarkerWithLabel for V3 * @version 1.1.4 [April 13, 2011] * @author Gary Little (inspired by code from Marc Ridey of Google). * @copyright Copyright 2010 Gary Little [gary at luxcentral.com] * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 * <code>google.maps.Marker</code> class. * <p> * MarkerWithLabel allows you to define markers with associated labels. As you would expect, * if the marker is draggable, so too will be the label. In addition, a marker with a label * responds to all mouse events in the same manner as a regular marker. It also fires mouse * events and "property changed" events just as a regular marker would. Version 1.1 adds * support for the raiseOnDrag feature introduced in API V3.3. * <p> * If you drag a marker by its label, you can cancel the drag and return the marker to its * original position by pressing the <code>Esc</code> key. This doesn't work if you drag the marker * itself because this feature is not (yet) supported in the <code>google.maps.Marker</code> class. */ /*! * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint browser:true */ /*global document,google */ /** * This constructor creates a label and associates it with a marker. * It is for the private use of the MarkerWithLabel class. * @constructor * @param {Marker} marker The marker with which the label is to be associated. * @private */ function MarkerLabel_(marker) { this.marker_ = marker; this.labelDiv_ = document.createElement("div"); this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; // Set up the DIV for handling mouse events in the label. This DIV forms a transparent veil // in the "overlayMouseTarget" pane, a veil that covers just the label. This is done so that // events can be captured even if the label is in the shadow of a google.maps.InfoWindow. // Code is included here to ensure the veil is always exactly the same size as the label. this.eventDiv_ = document.createElement("div"); this.eventDiv_.style.cssText = this.labelDiv_.style.cssText; // This is needed for proper behavior on MSIE: this.eventDiv_.setAttribute("onselectstart", "return false;"); this.eventDiv_.setAttribute("ondragstart", "return false;"); // Get the DIV for the "X" to be displayed when the marker is raised. this.crossDiv_ = MarkerLabel_.getSharedCross(); } // MarkerLabel_ inherits from OverlayView: MarkerLabel_.prototype = new google.maps.OverlayView(); /** * Returns the DIV for the cross used when dragging a marker when the * raiseOnDrag parameter set to true. One cross is shared with all markers. * @private */ MarkerLabel_.getSharedCross = function () { var div; if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { div = document.createElement("img"); div.style.cssText = "position: absolute; z-index: 1000002; display: none;"; // Hopefully Google never changes the standard "X" attributes: div.style.marginLeft = "-8px"; div.style.marginTop = "-9px"; div.src = "http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; MarkerLabel_.getSharedCross.crossDiv = div; } return MarkerLabel_.getSharedCross.crossDiv; }; /** * Adds the DIV representing the label to the DOM. This method is called * automatically when the marker's <code>setMap</code> method is called. * @private */ MarkerLabel_.prototype.onAdd = function () { var me = this; var cMouseIsDown = false; var cDraggingLabel = false; var cSavedZIndex; var cLatOffset, cLngOffset; var cIgnoreClick; var cRaiseEnabled; var cStartPosition; var cStartCenter; // Constants: var cRaiseOffset = 20; var cDraggingCursor = "url(http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur)"; // Stops all processing of an event. // var cAbortEvent = function (e) { if (e.preventDefault) { e.preventDefault(); } e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }; var cStopBounce = function () { me.marker_.setAnimation(null); }; this.getPanes().overlayImage.appendChild(this.labelDiv_); this.getPanes().overlayMouseTarget.appendChild(this.eventDiv_); // One cross is shared with all markers, so only add it once: if (typeof MarkerLabel_.getSharedCross.processed === "undefined") { this.getPanes().overlayImage.appendChild(this.crossDiv_); MarkerLabel_.getSharedCross.processed = true; } this.listeners_ = [ google.maps.event.addDomListener(this.eventDiv_, "mouseover", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { this.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseover", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mouseout", function (e) { if ((me.marker_.getDraggable() || me.marker_.getClickable()) && !cDraggingLabel) { this.style.cursor = me.marker_.getCursor(); google.maps.event.trigger(me.marker_, "mouseout", e); } }), google.maps.event.addDomListener(this.eventDiv_, "mousedown", function (e) { cDraggingLabel = false; if (me.marker_.getDraggable()) { cMouseIsDown = true; this.style.cursor = cDraggingCursor; } if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "mousedown", e); cAbortEvent(e); // Prevent map pan when starting a drag on a label } }), google.maps.event.addDomListener(document, "mouseup", function (mEvent) { var position; if (cMouseIsDown) { cMouseIsDown = false; me.eventDiv_.style.cursor = "pointer"; google.maps.event.trigger(me.marker_, "mouseup", mEvent); } if (cDraggingLabel) { if (cRaiseEnabled) { // Lower the marker & label position = me.getProjection().fromLatLngToDivPixel(me.marker_.getPosition()); position.y += cRaiseOffset; me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); // This is not the same bouncing style as when the marker portion is dragged, // but it will have to do: try { // Will fail if running Google Maps API earlier than V3.3 me.marker_.setAnimation(google.maps.Animation.BOUNCE); setTimeout(cStopBounce, 1406); } catch (e) {} } me.crossDiv_.style.display = "none"; me.marker_.setZIndex(cSavedZIndex); cIgnoreClick = true; // Set flag to ignore the click event reported after a label drag cDraggingLabel = false; mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragend", mEvent); } }), google.maps.event.addListener(me.marker_.getMap(), "mousemove", function (mEvent) { var position; if (cMouseIsDown) { if (cDraggingLabel) { // Change the reported location from the mouse position to the marker position: mEvent.latLng = new google.maps.LatLng(mEvent.latLng.lat() - cLatOffset, mEvent.latLng.lng() - cLngOffset); position = me.getProjection().fromLatLngToDivPixel(mEvent.latLng); if (cRaiseEnabled) { me.crossDiv_.style.left = position.x + "px"; me.crossDiv_.style.top = position.y + "px"; me.crossDiv_.style.display = ""; position.y -= cRaiseOffset; } me.marker_.setPosition(me.getProjection().fromDivPixelToLatLng(position)); if (cRaiseEnabled) { // Don't raise the veil; this hack needed to make MSIE act properly me.eventDiv_.style.top = (position.y + cRaiseOffset) + "px"; } google.maps.event.trigger(me.marker_, "drag", mEvent); } else { // Calculate offsets from the click point to the marker position: cLatOffset = mEvent.latLng.lat() - me.marker_.getPosition().lat(); cLngOffset = mEvent.latLng.lng() - me.marker_.getPosition().lng(); cSavedZIndex = me.marker_.getZIndex(); cStartPosition = me.marker_.getPosition(); cStartCenter = me.marker_.getMap().getCenter(); cRaiseEnabled = me.marker_.get("raiseOnDrag"); cDraggingLabel = true; me.marker_.setZIndex(1000000); // Moves the marker & label to the foreground during a drag mEvent.latLng = me.marker_.getPosition(); google.maps.event.trigger(me.marker_, "dragstart", mEvent); } } }), google.maps.event.addDomListener(document, "keydown", function (e) { if (cDraggingLabel) { if (e.keyCode === 27) { // Esc key cRaiseEnabled = false; me.marker_.setPosition(cStartPosition); me.marker_.getMap().setCenter(cStartCenter); google.maps.event.trigger(document, "mouseup", e); } } }), google.maps.event.addDomListener(this.eventDiv_, "click", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { if (cIgnoreClick) { // Ignore the click reported when a label drag ends cIgnoreClick = false; } else { google.maps.event.trigger(me.marker_, "click", e); cAbortEvent(e); // Prevent click from being passed on to map } } }), google.maps.event.addDomListener(this.eventDiv_, "dblclick", function (e) { if (me.marker_.getDraggable() || me.marker_.getClickable()) { google.maps.event.trigger(me.marker_, "dblclick", e); cAbortEvent(e); // Prevent map zoom when double-clicking on a label } }), google.maps.event.addListener(this.marker_, "dragstart", function (mEvent) { if (!cDraggingLabel) { cRaiseEnabled = this.get("raiseOnDrag"); } }), google.maps.event.addListener(this.marker_, "drag", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(cRaiseOffset); // During a drag, the marker's z-index is temporarily set to 1000000 to // ensure it appears above all other markers. Also set the label's z-index // to 1000000 (plus or minus 1 depending on whether the label is supposed // to be above or below the marker). me.labelDiv_.style.zIndex = 1000000 + (this.get("labelInBackground") ? -1 : +1); } } }), google.maps.event.addListener(this.marker_, "dragend", function (mEvent) { if (!cDraggingLabel) { if (cRaiseEnabled) { me.setPosition(0); // Also restores z-index of label } } }), google.maps.event.addListener(this.marker_, "position_changed", function () { me.setPosition(); }), google.maps.event.addListener(this.marker_, "zindex_changed", function () { me.setZIndex(); }), google.maps.event.addListener(this.marker_, "visible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "labelvisible_changed", function () { me.setVisible(); }), google.maps.event.addListener(this.marker_, "title_changed", function () { me.setTitle(); }), google.maps.event.addListener(this.marker_, "labelcontent_changed", function () { me.setContent(); }), google.maps.event.addListener(this.marker_, "labelanchor_changed", function () { me.setAnchor(); }), google.maps.event.addListener(this.marker_, "labelclass_changed", function () { me.setStyles(); }), google.maps.event.addListener(this.marker_, "labelstyle_changed", function () { me.setStyles(); }) ]; }; /** * Removes the DIV for the label from the DOM. It also removes all event handlers. * This method is called automatically when the marker's <code>setMap(null)</code> * method is called. * @private */ MarkerLabel_.prototype.onRemove = function () { var i; this.labelDiv_.parentNode.removeChild(this.labelDiv_); this.eventDiv_.parentNode.removeChild(this.eventDiv_); // Remove event listeners: for (i = 0; i < this.listeners_.length; i++) { google.maps.event.removeListener(this.listeners_[i]); } }; /** * Draws the label on the map. * @private */ MarkerLabel_.prototype.draw = function () { this.setContent(); this.setTitle(); this.setStyles(); }; /** * Sets the content of the label. * The content can be plain text or an HTML DOM node. * @private */ MarkerLabel_.prototype.setContent = function () { var content = this.marker_.get("labelContent"); if (typeof content.nodeType === "undefined") { this.labelDiv_.innerHTML = content; this.eventDiv_.innerHTML = this.labelDiv_.innerHTML; } else { this.labelDiv_.innerHTML = ""; // Remove current content this.labelDiv_.appendChild(content); content = content.cloneNode(true); this.eventDiv_.appendChild(content); } }; /** * Sets the content of the tool tip for the label. It is * always set to be the same as for the marker itself. * @private */ MarkerLabel_.prototype.setTitle = function () { this.eventDiv_.title = this.marker_.getTitle() || ""; }; /** * Sets the style of the label by setting the style sheet and applying * other specific styles requested. * @private */ MarkerLabel_.prototype.setStyles = function () { var i, labelStyle; // Apply style values from the style sheet defined in the labelClass parameter: this.labelDiv_.className = this.marker_.get("labelClass"); this.eventDiv_.className = this.labelDiv_.className; // Clear existing inline style values: this.labelDiv_.style.cssText = ""; this.eventDiv_.style.cssText = ""; // Apply style values defined in the labelStyle parameter: labelStyle = this.marker_.get("labelStyle"); for (i in labelStyle) { if (labelStyle.hasOwnProperty(i)) { this.labelDiv_.style[i] = labelStyle[i]; this.eventDiv_.style[i] = labelStyle[i]; } } this.setMandatoryStyles(); }; /** * Sets the mandatory styles to the DIV representing the label as well as to the * associated event DIV. This includes setting the DIV position, z-index, and visibility. * @private */ MarkerLabel_.prototype.setMandatoryStyles = function () { this.labelDiv_.style.position = "absolute"; this.labelDiv_.style.overflow = "hidden"; // Make sure the opacity setting causes the desired effect on MSIE: if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; } this.eventDiv_.style.position = this.labelDiv_.style.position; this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE this.setAnchor(); this.setPosition(); // This also updates z-index, if necessary. this.setVisible(); }; /** * Sets the anchor point of the label. * @private */ MarkerLabel_.prototype.setAnchor = function () { var anchor = this.marker_.get("labelAnchor"); this.labelDiv_.style.marginLeft = -anchor.x + "px"; this.labelDiv_.style.marginTop = -anchor.y + "px"; this.eventDiv_.style.marginLeft = -anchor.x + "px"; this.eventDiv_.style.marginTop = -anchor.y + "px"; }; /** * Sets the position of the label. The z-index is also updated, if necessary. * @private */ MarkerLabel_.prototype.setPosition = function (yOffset) { var position = this.getProjection().fromLatLngToDivPixel(this.marker_.getPosition()); if (typeof yOffset === "undefined") { yOffset = 0; } this.labelDiv_.style.left = Math.round(position.x) + "px"; this.labelDiv_.style.top = Math.round(position.y - yOffset) + "px"; this.eventDiv_.style.left = this.labelDiv_.style.left; this.eventDiv_.style.top = this.labelDiv_.style.top; this.setZIndex(); }; /** * Sets the z-index of the label. If the marker's z-index property has not been defined, the z-index * of the label is set to the vertical coordinate of the label. This is in keeping with the default * stacking order for Google Maps: markers to the south are in front of markers to the north. * @private */ MarkerLabel_.prototype.setZIndex = function () { var zAdjust = (this.marker_.get("labelInBackground") ? -1 : +1); if (typeof this.marker_.getZIndex() === "undefined") { this.labelDiv_.style.zIndex = parseInt(this.labelDiv_.style.top, 10) + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } else { this.labelDiv_.style.zIndex = this.marker_.getZIndex() + zAdjust; this.eventDiv_.style.zIndex = this.labelDiv_.style.zIndex; } }; /** * Sets the visibility of the label. The label is visible only if the marker itself is * visible (i.e., its visible property is true) and the labelVisible property is true. * @private */ MarkerLabel_.prototype.setVisible = function () { if (this.marker_.get("labelVisible")) { this.labelDiv_.style.display = this.marker_.getVisible() ? "block" : "none"; } else { this.labelDiv_.style.display = "none"; } this.eventDiv_.style.display = this.labelDiv_.style.display; }; /** * @name MarkerWithLabelOptions * @class This class represents the optional parameter passed to the {@link MarkerWithLabel} constructor. * The properties available are the same as for <code>google.maps.Marker</code> with the addition * of the properties listed below. To change any of these additional properties after the labeled * marker has been created, call <code>google.maps.Marker.set(propertyName, propertyValue)</code>. * <p> * When any of these properties changes, a property changed event is fired. The names of these * events are derived from the name of the property and are of the form <code>propertyname_changed</code>. * For example, if the content of the label changes, a <code>labelcontent_changed</code> event * is fired. * <p> * @property {string|Node} [labelContent] The content of the label (plain text or an HTML DOM node). * @property {Point} [labelAnchor] By default, a label is drawn with its anchor point at (0,0) so * that its top left corner is positioned at the anchor point of the associated marker. Use this * property to change the anchor point of the label. For example, to center a 50px-wide label * beneath a marker, specify a <code>labelAnchor</code> of <code>google.maps.Point(25, 0)</code>. * (Note: x-values increase to the right and y-values increase to the top.) * @property {string} [labelClass] The name of the CSS class defining the styles for the label. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {Object} [labelStyle] An object literal whose properties define specific CSS * style values to be applied to the label. Style values defined here override those that may * be defined in the <code>labelClass</code> style sheet. If this property is changed after the * label has been created, all previously set styles (except those defined in the style sheet) * are removed from the label before the new style values are applied. * Note that style values for <code>position</code>, <code>overflow</code>, <code>top</code>, * <code>left</code>, <code>zIndex</code>, <code>display</code>, <code>marginLeft</code>, and * <code>marginTop</code> are ignored; these styles are for internal use only. * @property {boolean} [labelInBackground] A flag indicating whether a label that overlaps its * associated marker should appear in the background (i.e., in a plane below the marker). * The default is <code>false</code>, which causes the label to appear in the foreground. * @property {boolean} [labelVisible] A flag indicating whether the label is to be visible. * The default is <code>true</code>. Note that even if <code>labelVisible</code> is * <code>true</code>, the label will <i>not</i> be visible unless the associated marker is also * visible (i.e., unless the marker's <code>visible</code> property is <code>true</code>). * @property {boolean} [raiseOnDrag] A flag indicating whether the label and marker are to be * raised when the marker is dragged. The default is <code>true</code>. If a draggable marker is * being created and a version of Google Maps API earlier than V3.3 is being used, this property * must be set to <code>false</code>. * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, * so the value of this parameter is always forced to <code>false</code>. */ /** * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. * @constructor * @param {MarkerWithLabelOptions} [opt_options] The optional parameters. */ function MarkerWithLabel(opt_options) { opt_options = opt_options || {}; opt_options.labelContent = opt_options.labelContent || ""; opt_options.labelAnchor = opt_options.labelAnchor || new google.maps.Point(0, 0); opt_options.labelClass = opt_options.labelClass || "markerLabels"; opt_options.labelStyle = opt_options.labelStyle || {}; opt_options.labelInBackground = opt_options.labelInBackground || false; if (typeof opt_options.labelVisible === "undefined") { opt_options.labelVisible = true; } if (typeof opt_options.raiseOnDrag === "undefined") { opt_options.raiseOnDrag = true; } if (typeof opt_options.clickable === "undefined") { opt_options.clickable = true; } if (typeof opt_options.draggable === "undefined") { opt_options.draggable = false; } if (typeof opt_options.optimized === "undefined") { opt_options.optimized = false; } opt_options.optimized = false; // Optimized rendering is not supported this.label = new MarkerLabel_(this); // Bind the label to the marker // Call the parent constructor. It calls Marker.setValues to initialize, so all // the new parameters are conveniently saved and can be accessed with get/set. // Marker.set triggers a property changed event (called "propertyname_changed") // that the marker label listens for in order to react to state changes. google.maps.Marker.apply(this, arguments); } // MarkerWithLabel inherits from <code>Marker</code>: MarkerWithLabel.prototype = new google.maps.Marker(); /** * Overrides the standard Marker setMap function. * @param {Map} marker The map to which the marker is to be added. * @private */ MarkerWithLabel.prototype.setMap = function (theMap) { // Call the inherited function... google.maps.Marker.prototype.setMap.apply(this, arguments); // ... then deal with the label: this.label.setMap(theMap); };
fix maps issue with new JS script
arkestra_utilities/static/arkestra/js/maps/markerwithlabel.js
fix maps issue with new JS script
<ide><path>rkestra_utilities/static/arkestra/js/maps/markerwithlabel.js <ide> /** <ide> * @name MarkerWithLabel for V3 <del> * @version 1.1.4 [April 13, 2011] <add> * @version 1.1.8 [February 26, 2013] <ide> * @author Gary Little (inspired by code from Marc Ridey of Google). <del> * @copyright Copyright 2010 Gary Little [gary at luxcentral.com] <add> * @copyright Copyright 2012 Gary Little [gary at luxcentral.com] <ide> * @fileoverview MarkerWithLabel extends the Google Maps JavaScript API V3 <ide> * <code>google.maps.Marker</code> class. <ide> * <p> <ide> /*global document,google */ <ide> <ide> /** <add> * @param {Function} childCtor Child class. <add> * @param {Function} parentCtor Parent class. <add> */ <add>function inherits(childCtor, parentCtor) { <add> /** @constructor */ <add> function tempCtor() {}; <add> tempCtor.prototype = parentCtor.prototype; <add> childCtor.superClass_ = parentCtor.prototype; <add> childCtor.prototype = new tempCtor(); <add> /** @override */ <add> childCtor.prototype.constructor = childCtor; <add>} <add> <add>/** <ide> * This constructor creates a label and associates it with a marker. <ide> * It is for the private use of the MarkerWithLabel class. <ide> * @constructor <ide> * @param {Marker} marker The marker with which the label is to be associated. <del> * @private <del> */ <del>function MarkerLabel_(marker) { <add> * @param {string} crossURL The URL of the cross image =. <add> * @param {string} handCursor The URL of the hand cursor. <add> * @private <add> */ <add>function MarkerLabel_(marker, crossURL, handCursorURL) { <ide> this.marker_ = marker; <add> this.handCursorURL_ = marker.handCursorURL; <ide> <ide> this.labelDiv_ = document.createElement("div"); <ide> this.labelDiv_.style.cssText = "position: absolute; overflow: hidden;"; <ide> this.eventDiv_.setAttribute("ondragstart", "return false;"); <ide> <ide> // Get the DIV for the "X" to be displayed when the marker is raised. <del> this.crossDiv_ = MarkerLabel_.getSharedCross(); <add> this.crossDiv_ = MarkerLabel_.getSharedCross(crossURL); <ide> } <del> <del>// MarkerLabel_ inherits from OverlayView: <del>MarkerLabel_.prototype = new google.maps.OverlayView(); <add>inherits(MarkerLabel_, google.maps.OverlayView); <ide> <ide> /** <ide> * Returns the DIV for the cross used when dragging a marker when the <ide> * raiseOnDrag parameter set to true. One cross is shared with all markers. <del> * @private <del> */ <del>MarkerLabel_.getSharedCross = function () { <add> * @param {string} crossURL The URL of the cross image =. <add> * @private <add> */ <add>MarkerLabel_.getSharedCross = function (crossURL) { <ide> var div; <ide> if (typeof MarkerLabel_.getSharedCross.crossDiv === "undefined") { <ide> div = document.createElement("img"); <ide> // Hopefully Google never changes the standard "X" attributes: <ide> div.style.marginLeft = "-8px"; <ide> div.style.marginTop = "-9px"; <del> div.src = "http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; <add> div.src = crossURL; <ide> MarkerLabel_.getSharedCross.crossDiv = div; <ide> } <ide> return MarkerLabel_.getSharedCross.crossDiv; <ide> var cStartCenter; <ide> // Constants: <ide> var cRaiseOffset = 20; <del> var cDraggingCursor = "url(http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur)"; <add> var cDraggingCursor = "url(" + this.handCursorURL_ + ")"; <ide> <ide> // Stops all processing of an event. <ide> // <ide> this.labelDiv_.style.overflow = "hidden"; <ide> // Make sure the opacity setting causes the desired effect on MSIE: <ide> if (typeof this.labelDiv_.style.opacity !== "undefined" && this.labelDiv_.style.opacity !== "") { <add> this.labelDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")\""; <ide> this.labelDiv_.style.filter = "alpha(opacity=" + (this.labelDiv_.style.opacity * 100) + ")"; <ide> } <ide> <ide> this.eventDiv_.style.position = this.labelDiv_.style.position; <ide> this.eventDiv_.style.overflow = this.labelDiv_.style.overflow; <ide> this.eventDiv_.style.opacity = 0.01; // Don't use 0; DIV won't be clickable on MSIE <add> this.eventDiv_.style.MsFilter = "\"progid:DXImageTransform.Microsoft.Alpha(opacity=1)\""; <ide> this.eventDiv_.style.filter = "alpha(opacity=1)"; // For MSIE <ide> <ide> this.setAnchor(); <ide> * @property {boolean} [optimized] A flag indicating whether rendering is to be optimized for the <ide> * marker. <b>Important: The optimized rendering technique is not supported by MarkerWithLabel, <ide> * so the value of this parameter is always forced to <code>false</code>. <add> * @property {string} [crossImage="http://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"] <add> * The URL of the cross image to be displayed while dragging a marker. <add> * @property {string} [handCursor="http://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"] <add> * The URL of the cursor to be displayed while dragging a marker. <ide> */ <ide> /** <ide> * Creates a MarkerWithLabel with the options specified in {@link MarkerWithLabelOptions}. <ide> if (typeof opt_options.optimized === "undefined") { <ide> opt_options.optimized = false; <ide> } <add> opt_options.crossImage = opt_options.crossImage || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/drag_cross_67_16.png"; <add> opt_options.handCursor = opt_options.handCursor || "http" + (document.location.protocol === "https:" ? "s" : "") + "://maps.gstatic.com/intl/en_us/mapfiles/closedhand_8_8.cur"; <ide> opt_options.optimized = false; // Optimized rendering is not supported <ide> <del> this.label = new MarkerLabel_(this); // Bind the label to the marker <add> this.label = new MarkerLabel_(this, opt_options.crossImage, opt_options.handCursor); // Bind the label to the marker <ide> <ide> // Call the parent constructor. It calls Marker.setValues to initialize, so all <ide> // the new parameters are conveniently saved and can be accessed with get/set. <ide> // that the marker label listens for in order to react to state changes. <ide> google.maps.Marker.apply(this, arguments); <ide> } <del> <del>// MarkerWithLabel inherits from <code>Marker</code>: <del>MarkerWithLabel.prototype = new google.maps.Marker(); <add>inherits(MarkerWithLabel, google.maps.Marker); <ide> <ide> /** <ide> * Overrides the standard Marker setMap function. <del> * @param {Map} marker The map to which the marker is to be added. <add> * @param {Map} theMap The map to which the marker is to be added. <ide> * @private <ide> */ <ide> MarkerWithLabel.prototype.setMap = function (theMap) {
Java
apache-2.0
29d4cb63746d0f2a47f762b642d93bed5a1f06bd
0
sanyaade-g2g-repos/orientdb,alonsod86/orientdb,intfrr/orientdb,redox/OrientDB,alonsod86/orientdb,mmacfadden/orientdb,giastfader/orientdb,intfrr/orientdb,redox/OrientDB,mmacfadden/orientdb,wyzssw/orientdb,jdillon/orientdb,intfrr/orientdb,tempbottle/orientdb,wouterv/orientdb,wyzssw/orientdb,rprabhat/orientdb,orientechnologies/orientdb,joansmith/orientdb,allanmoso/orientdb,tempbottle/orientdb,orientechnologies/orientdb,tempbottle/orientdb,wouterv/orientdb,intfrr/orientdb,tempbottle/orientdb,giastfader/orientdb,allanmoso/orientdb,giastfader/orientdb,mbhulin/orientdb,alonsod86/orientdb,redox/OrientDB,wyzssw/orientdb,mbhulin/orientdb,rprabhat/orientdb,wouterv/orientdb,redox/OrientDB,rprabhat/orientdb,orientechnologies/orientdb,allanmoso/orientdb,alonsod86/orientdb,rprabhat/orientdb,orientechnologies/orientdb,jdillon/orientdb,allanmoso/orientdb,mbhulin/orientdb,cstamas/orientdb,cstamas/orientdb,joansmith/orientdb,cstamas/orientdb,wouterv/orientdb,jdillon/orientdb,joansmith/orientdb,wyzssw/orientdb,joansmith/orientdb,mbhulin/orientdb,sanyaade-g2g-repos/orientdb,giastfader/orientdb,sanyaade-g2g-repos/orientdb,sanyaade-g2g-repos/orientdb,mmacfadden/orientdb,cstamas/orientdb,mmacfadden/orientdb
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.common.parser; import java.util.ArrayList; /** * String parser utility class * * @author Luca Garulli * */ public class OStringParser { public static final String WHITE_SPACE = " "; public static final String COMMON_JUMP = " \r\n"; public static String getWordFromString(String iText, final int iBeginIndex, final String ioSeparatorChars) { return getWord(iText.trim(), iBeginIndex, ioSeparatorChars); } public static String getWord(final CharSequence iText, final int iBeginIndex, final String ioSeparatorChars) { final StringBuilder buffer = new StringBuilder(); char stringBeginChar = ' '; char c; for (int i = iBeginIndex; i < iText.length(); ++i) { c = iText.charAt(i); if (c == '\'' || c == '"') { if (stringBeginChar != ' ') { // CLOSE THE STRING? if (stringBeginChar == c) { // SAME CHAR AS THE BEGIN OF THE STRING: CLOSE IT AND PUSH stringBeginChar = ' '; } } else { // START STRING stringBeginChar = c; } } else if (stringBeginChar == ' ') { for (int sepIndex = 0; sepIndex < ioSeparatorChars.length(); ++sepIndex) { if (ioSeparatorChars.charAt(sepIndex) == c && buffer.length() > 0) // SEPARATOR (OUTSIDE A STRING): PUSH return buffer.toString(); } } buffer.append(c); } return buffer.toString(); } public static String[] getWords(String iRecord, final String iSeparatorChars) { return getWords(iRecord, iSeparatorChars, false); } public static String[] getWords(String iRecord, final String iSeparatorChars, final boolean iIncludeStringSep) { return getWords(iRecord, iSeparatorChars, " \n\r\t", iIncludeStringSep); } public static String[] getWords(String iText, final String iSeparatorChars, final String iJumpChars, final boolean iIncludeStringSep) { iText = iText.trim(); final ArrayList<String> fields = new ArrayList<String>(); final StringBuilder buffer = new StringBuilder(); char stringBeginChar = ' '; char c; int openBraket = 0; int openGraph = 0; boolean charFound; boolean escape = false; for (int i = 0; i < iText.length(); ++i) { c = iText.charAt(i); if (openBraket == 0 && openGraph == 0 && !escape && c == '\\' && ((i + 1) < iText.length())) { // ESCAPE CHARS final char nextChar = iText.charAt(i + 1); if (nextChar == 'u') { i = readUnicode(iText, i + 2, buffer); } else if (nextChar == 'n') { buffer.append("\n"); i++; } else if (nextChar == 'r') { buffer.append("\r"); i++; } else if (nextChar == 't') { buffer.append("\t"); i++; } else if (nextChar == 'f') { buffer.append("\f"); i++; } else escape = true; continue; } if (openBraket == 0 && openGraph == 0 && !escape && (c == '\'' || c == '"')) { if (stringBeginChar != ' ') { // CLOSE THE STRING? if (stringBeginChar == c) { // SAME CHAR AS THE BEGIN OF THE STRING: CLOSE IT AND PUSH stringBeginChar = ' '; if (iIncludeStringSep) buffer.append(c); fields.add(buffer.toString()); buffer.setLength(0); continue; } } else { // START STRING stringBeginChar = c; if (iIncludeStringSep) buffer.append(c); continue; } } else if (stringBeginChar == ' ') { if (c == '[') openBraket++; else if (c == ']') openBraket--; if (c == '{') openGraph++; else if (c == '}') openGraph--; else if (openBraket == 0 && openGraph == 0) { charFound = false; for (int sepIndex = 0; sepIndex < iSeparatorChars.length(); ++sepIndex) { if (iSeparatorChars.charAt(sepIndex) == c) { charFound = true; if (buffer.length() > 0) { // SEPARATOR (OUTSIDE A STRING): PUSH fields.add(buffer.toString()); buffer.setLength(0); } break; } } if (charFound) continue; } if (stringBeginChar == ' ') { // CHECK FOR CHAR TO JUMP charFound = false; for (int jumpIndex = 0; jumpIndex < iJumpChars.length(); ++jumpIndex) { if (iJumpChars.charAt(jumpIndex) == c) { charFound = true; break; } } if (charFound) continue; } } buffer.append(c); if (escape) escape = false; } if (buffer.length() > 0) // ADD THE LAST WORD IF ANY fields.add(buffer.toString()); String[] result = new String[fields.size()]; fields.toArray(result); return result; } public static String[] split(String iText, final char iSplitChar, String iJumpChars) { iText = iText.trim(); ArrayList<String> fields = new ArrayList<String>(); StringBuilder buffer = new StringBuilder(); char c; char stringChar = ' '; boolean escape = false; boolean jumpSplitChar = false; boolean charFound; for (int i = 0; i < iText.length(); i++) { c = iText.charAt(i); if (!escape && c == '\\' && ((i + 1) < iText.length())) { if (iText.charAt(i + 1) == 'u') { i = readUnicode(iText, i + 2, buffer); } else { escape = true; buffer.append(c); } continue; } if (c == '\'' || c == '"') { if (!jumpSplitChar) { jumpSplitChar = true; stringChar = c; } else { if (!escape && c == stringChar) jumpSplitChar = false; } } if (c == iSplitChar) { if (!jumpSplitChar) { fields.add(buffer.toString()); buffer.setLength(0); continue; } } // CHECK IF IT MUST JUMP THE CHAR if (buffer.length() == 0) { charFound = false; for (int jumpIndex = 0; jumpIndex < iJumpChars.length(); ++jumpIndex) { if (iJumpChars.charAt(jumpIndex) == c) { charFound = true; break; } } if (charFound) continue; } buffer.append(c); if (escape) escape = false; } if (buffer.length() > 0) { fields.add(buffer.toString()); buffer.setLength(0); } String[] result = new String[fields.size()]; fields.toArray(result); return result; } /** * Jump white spaces. * * @param iText * String to analyze * @param iCurrentPosition * Current position in text * @return The new offset inside the string analyzed */ public static int jumpWhiteSpaces(final CharSequence iText, final int iCurrentPosition) { return jump(iText, iCurrentPosition, WHITE_SPACE); } /** * Jump some characters reading from an offset of a String. * * @param iText * String to analyze * @param iCurrentPosition * Current position in text * @param iJumpChars * String as char array of chars to jump * @return The new offset inside the string analyzed */ public static int jump(final CharSequence iText, int iCurrentPosition, final String iJumpChars) { if (iCurrentPosition < 0) return -1; final int size = iText.length(); final int jumpCharSize = iJumpChars.length(); boolean found = true; char c; for (; iCurrentPosition < size; ++iCurrentPosition) { found = false; c = iText.charAt(iCurrentPosition); for (int jumpIndex = 0; jumpIndex < jumpCharSize; ++jumpIndex) { if (iJumpChars.charAt(jumpIndex) == c) { found = true; break; } } if (!found) break; } return iCurrentPosition >= size ? -1 : iCurrentPosition; } public static int readUnicode(String iText, int position, StringBuilder buffer) { // DECODE UNICODE CHAR final StringBuilder buff = new StringBuilder(); final int lastPos = position + 4; for (; position < lastPos; ++position) buff.append(iText.charAt(position)); buffer.append((char) Integer.parseInt(buff.toString(), 16)); return position - 1; } public static int readUnicode(char[] iText, int position, StringBuilder buffer) { // DECODE UNICODE CHAR final StringBuilder buff = new StringBuilder(); final int lastPos = position + 4; for (; position < lastPos; ++position) buff.append(iText[position]); buffer.append((char) Integer.parseInt(buff.toString(), 16)); return position - 1; } public static String replaceAll(String iText, String iToReplace, String iReplacement) { if (iText == null || iText.length() <= 0 || iToReplace == null || iToReplace.length() <= 0) return iText; int pos = iText.indexOf(iToReplace); int lastAppend = 0; final StringBuffer buffer = new StringBuffer(); while (pos > -1) { buffer.append(iText.substring(lastAppend, pos)); buffer.append(iReplacement); lastAppend = pos + iToReplace.length(); pos = iText.indexOf(iToReplace, lastAppend); } buffer.append(iText.substring(lastAppend)); return buffer.toString(); } }
commons/src/main/java/com/orientechnologies/common/parser/OStringParser.java
/* * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.orientechnologies.common.parser; import java.util.ArrayList; /** * String parser utility class * * @author Luca Garulli * */ public class OStringParser { public static final String WHITE_SPACE = " "; public static final String COMMON_JUMP = " \r\n"; public static String getWordFromString(String iText, final int iBeginIndex, final String ioSeparatorChars) { return getWord(iText.trim(), iBeginIndex, ioSeparatorChars); } public static String getWord(final CharSequence iText, final int iBeginIndex, final String ioSeparatorChars) { final StringBuilder buffer = new StringBuilder(); char stringBeginChar = ' '; char c; for (int i = iBeginIndex; i < iText.length(); ++i) { c = iText.charAt(i); if (c == '\'' || c == '"') { if (stringBeginChar != ' ') { // CLOSE THE STRING? if (stringBeginChar == c) { // SAME CHAR AS THE BEGIN OF THE STRING: CLOSE IT AND PUSH stringBeginChar = ' '; } } else { // START STRING stringBeginChar = c; } } else if (stringBeginChar == ' ') { for (int sepIndex = 0; sepIndex < ioSeparatorChars.length(); ++sepIndex) { if (ioSeparatorChars.charAt(sepIndex) == c && buffer.length() > 0) // SEPARATOR (OUTSIDE A STRING): PUSH return buffer.toString(); } } buffer.append(c); } return buffer.toString(); } public static String[] getWords(String iRecord, final String iSeparatorChars) { return getWords(iRecord, iSeparatorChars, false); } public static String[] getWords(String iRecord, final String iSeparatorChars, final boolean iIncludeStringSep) { return getWords(iRecord, iSeparatorChars, " \n\r\t", iIncludeStringSep); } public static String[] getWords(String iText, final String iSeparatorChars, final String iJumpChars, final boolean iIncludeStringSep) { iText = iText.trim(); final ArrayList<String> fields = new ArrayList<String>(); final StringBuilder buffer = new StringBuilder(); char stringBeginChar = ' '; char c; int openBraket = 0; int openGraph = 0; boolean charFound; boolean escape = false; for (int i = 0; i < iText.length(); ++i) { c = iText.charAt(i); if (openBraket == 0 && openGraph == 0 && !escape && c == '\\') { // ESCAPE CHARS final char nextChar = iText.charAt(i + 1); if (nextChar == 'u') { i = readUnicode(iText, i + 2, buffer); } else if (nextChar == 'n') { buffer.append("\n"); i++; } else if (nextChar == 'r') { buffer.append("\r"); i++; } else if (nextChar == 't') { buffer.append("\t"); i++; } else if (nextChar == 'f') { buffer.append("\f"); i++; } else escape = true; continue; } if (openBraket == 0 && openGraph == 0 && !escape && (c == '\'' || c == '"')) { if (stringBeginChar != ' ') { // CLOSE THE STRING? if (stringBeginChar == c) { // SAME CHAR AS THE BEGIN OF THE STRING: CLOSE IT AND PUSH stringBeginChar = ' '; if (iIncludeStringSep) buffer.append(c); fields.add(buffer.toString()); buffer.setLength(0); continue; } } else { // START STRING stringBeginChar = c; if (iIncludeStringSep) buffer.append(c); continue; } } else if (stringBeginChar == ' ') { if (c == '[') openBraket++; else if (c == ']') openBraket--; if (c == '{') openGraph++; else if (c == '}') openGraph--; else if (openBraket == 0 && openGraph == 0) { charFound = false; for (int sepIndex = 0; sepIndex < iSeparatorChars.length(); ++sepIndex) { if (iSeparatorChars.charAt(sepIndex) == c) { charFound = true; if (buffer.length() > 0) { // SEPARATOR (OUTSIDE A STRING): PUSH fields.add(buffer.toString()); buffer.setLength(0); } break; } } if (charFound) continue; } if (stringBeginChar == ' ') { // CHECK FOR CHAR TO JUMP charFound = false; for (int jumpIndex = 0; jumpIndex < iJumpChars.length(); ++jumpIndex) { if (iJumpChars.charAt(jumpIndex) == c) { charFound = true; break; } } if (charFound) continue; } } buffer.append(c); if (escape) escape = false; } if (buffer.length() > 0) // ADD THE LAST WORD IF ANY fields.add(buffer.toString()); String[] result = new String[fields.size()]; fields.toArray(result); return result; } public static String[] split(String iText, final char iSplitChar, String iJumpChars) { iText = iText.trim(); ArrayList<String> fields = new ArrayList<String>(); StringBuilder buffer = new StringBuilder(); char c; char stringChar = ' '; boolean escape = false; boolean jumpSplitChar = false; boolean charFound; for (int i = 0; i < iText.length(); i++) { c = iText.charAt(i); if (!escape && c == '\\') { if (iText.charAt(i + 1) == 'u') { i = readUnicode(iText, i + 2, buffer); } else { escape = true; buffer.append(c); } continue; } if (c == '\'' || c == '"') { if (!jumpSplitChar) { jumpSplitChar = true; stringChar = c; } else { if (!escape && c == stringChar) jumpSplitChar = false; } } if (c == iSplitChar) { if (!jumpSplitChar) { fields.add(buffer.toString()); buffer.setLength(0); continue; } } // CHECK IF IT MUST JUMP THE CHAR if (buffer.length() == 0) { charFound = false; for (int jumpIndex = 0; jumpIndex < iJumpChars.length(); ++jumpIndex) { if (iJumpChars.charAt(jumpIndex) == c) { charFound = true; break; } } if (charFound) continue; } buffer.append(c); if (escape) escape = false; } if (buffer.length() > 0) { fields.add(buffer.toString()); buffer.setLength(0); } String[] result = new String[fields.size()]; fields.toArray(result); return result; } /** * Jump white spaces. * * @param iText * String to analyze * @param iCurrentPosition * Current position in text * @return The new offset inside the string analyzed */ public static int jumpWhiteSpaces(final CharSequence iText, final int iCurrentPosition) { return jump(iText, iCurrentPosition, WHITE_SPACE); } /** * Jump some characters reading from an offset of a String. * * @param iText * String to analyze * @param iCurrentPosition * Current position in text * @param iJumpChars * String as char array of chars to jump * @return The new offset inside the string analyzed */ public static int jump(final CharSequence iText, int iCurrentPosition, final String iJumpChars) { if (iCurrentPosition < 0) return -1; final int size = iText.length(); final int jumpCharSize = iJumpChars.length(); boolean found = true; char c; for (; iCurrentPosition < size; ++iCurrentPosition) { found = false; c = iText.charAt(iCurrentPosition); for (int jumpIndex = 0; jumpIndex < jumpCharSize; ++jumpIndex) { if (iJumpChars.charAt(jumpIndex) == c) { found = true; break; } } if (!found) break; } return iCurrentPosition >= size ? -1 : iCurrentPosition; } public static int readUnicode(String iText, int position, StringBuilder buffer) { // DECODE UNICODE CHAR final StringBuilder buff = new StringBuilder(); final int lastPos = position + 4; for (; position < lastPos; ++position) buff.append(iText.charAt(position)); buffer.append((char) Integer.parseInt(buff.toString(), 16)); return position - 1; } public static int readUnicode(char[] iText, int position, StringBuilder buffer) { // DECODE UNICODE CHAR final StringBuilder buff = new StringBuilder(); final int lastPos = position + 4; for (; position < lastPos; ++position) buff.append(iText[position]); buffer.append((char) Integer.parseInt(buff.toString(), 16)); return position - 1; } public static String replaceAll(String iText, String iToReplace, String iReplacement) { if (iText == null || iText.length() <= 0 || iToReplace == null || iToReplace.length() <= 0) return iText; int pos = iText.indexOf(iToReplace); int lastAppend = 0; final StringBuffer buffer = new StringBuffer(); while (pos > -1) { buffer.append(iText.substring(lastAppend, pos)); buffer.append(iReplacement); lastAppend = pos + iToReplace.length(); pos = iText.indexOf(iToReplace, lastAppend); } buffer.append(iText.substring(lastAppend)); return buffer.toString(); } }
Fixed bug on String splits. Also fix for issue 706
commons/src/main/java/com/orientechnologies/common/parser/OStringParser.java
Fixed bug on String splits. Also fix for issue 706
<ide><path>ommons/src/main/java/com/orientechnologies/common/parser/OStringParser.java <ide> for (int i = 0; i < iText.length(); ++i) { <ide> c = iText.charAt(i); <ide> <del> if (openBraket == 0 && openGraph == 0 && !escape && c == '\\') { <add> if (openBraket == 0 && openGraph == 0 && !escape && c == '\\' && ((i + 1) < iText.length())) { <ide> // ESCAPE CHARS <ide> final char nextChar = iText.charAt(i + 1); <ide> <ide> for (int i = 0; i < iText.length(); i++) { <ide> c = iText.charAt(i); <ide> <del> if (!escape && c == '\\') { <add> if (!escape && c == '\\' && ((i + 1) < iText.length())) { <ide> if (iText.charAt(i + 1) == 'u') { <ide> i = readUnicode(iText, i + 2, buffer); <ide> } else {