method2testcases
stringlengths 118
3.08k
|
---|
### Question:
XQueryRunConfig { public String getDatabaseName() { return getExpressionValue(databaseNameExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnDatabaseNameValue() { String result = config.getDatabaseName(); assertThat(result, is(DATABASE_NAME)); } |
### Question:
XQueryRunConfig { public String getContextItemType() { return getExpressionValue(contextItemTypeExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnContextItemTypeValue() { String result = config.getContextItemType(); assertThat(result, is(CONTEXT_ITEM_TYPE)); } |
### Question:
OutputMethodFactory { public Properties getOutputMethodProperties() { Properties props = new Properties(); props.setProperty(METHOD_PROPERTY_NAME, OUTPUT_TYPE_XML); return props; } OutputMethodFactory(XQueryRunConfig config); Properties getOutputMethodProperties(); static final String METHOD_PROPERTY_NAME; static final String OUTPUT_TYPE_XML; }### Answer:
@Test public void shouldAlwaysReturnOutputMethodXml() { OutputMethodFactory outputMethodFactory = new OutputMethodFactory(mock(XQueryRunConfig.class)); Properties result = outputMethodFactory.getOutputMethodProperties(); assertThat(result.keySet().size(), is(1)); assertThat(result.getProperty(METHOD_PROPERTY_NAME), is(OUTPUT_TYPE_XML)); } |
### Question:
ConnectionFactory { public XQConnection getConnection(XQDataSource dataSource) throws Exception { XQConnection connection; if (config.getDataSourceType().connectionPropertiesAreSupported() && config.getUsername() != null && config.getUsername().length() > 0) { connection = dataSource.getConnection(config.getUsername(), config.getPassword()); } else { connection = dataSource.getConnection(); } return connection; } ConnectionFactory(XQueryRunConfig config); XQConnection getConnection(XQDataSource dataSource); }### Answer:
@Test public void shouldInvokeGetConnectionWithoutParametersWhenConnectionPropertiesNotSupported() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.SAXON); factory.getConnection(dataSource); verify(dataSource).getConnection(); }
@Test public void shouldInvokeGetConnectionWithParametersWhenConnectionPropertiesAreSupportedAndSet() throws Exception { given(config.getDataSourceType()).willReturn(XQueryDataSourceType.MARKLOGIC); given(config.getUsername()).willReturn(USER); given(config.getPassword()).willReturn(PASSWORD); factory.getConnection(dataSource); verify(dataSource).getConnection(USER, PASSWORD); }
@Test public void shouldInvokeGetConnectionWithoutParametersWhenConnectionPropertiesAreSupportedAndUsernameNotSet() throws Exception { given(config.getUsername()).willReturn(null); given(config.getDataSourceType()).willReturn(XQueryDataSourceType.MARKLOGIC); factory.getConnection(dataSource); verify(dataSource).getConnection(); }
@Test public void shouldInvokeGetConnectionWithoutParametersWhenConnectionPropertiesAreSupportedAndUsernameSetEmpty() throws Exception { given(config.getUsername()).willReturn(""); given(config.getDataSourceType()).willReturn(XQueryDataSourceType.MARKLOGIC); factory.getConnection(dataSource); verify(dataSource).getConnection(); } |
### Question:
XQueryRunConfig { public boolean isDebugEnabled() { return Boolean.parseBoolean(getExpressionValue(debugExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnDebugEnabledValue() { boolean result = config.isDebugEnabled(); assertThat(result, is(true)); } |
### Question:
XQueryRunConfig { public String getDebugPort() { return getExpressionValue(debugPortExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnDebugPortValue() { String result = config.getDebugPort(); assertThat(result, is("9000")); } |
### Question:
ExpressionFactory { public XQPreparedExpression getExpression(XQConnection connection) throws Exception { XQPreparedExpression preparedExpression = connection .prepareExpression(contentFactory.getXQueryContentAsStream()); contextItemBinder.bindContextItem(connection, preparedExpression); variablesBinder.bindVariables(connection, preparedExpression); return preparedExpression; } ExpressionFactory(XQueryRunConfig config, XQueryContentFactory contentFactory,
VariablesBinder variablesBinder, ContextItemBinder contextItemBinder); XQPreparedExpression getExpression(XQConnection connection); }### Answer:
@Test public void shouldPrepareExpressionUsingConnection() throws Exception { InputStream inputStream = mock(InputStream.class); given(contentFactory.getXQueryContentAsStream()).willReturn(inputStream); factory.getExpression(connection); verify(contentFactory).getXQueryContentAsStream(); verify(connection).prepareExpression(inputStream); }
@Test public void shouldBindContextItem() throws Exception { factory.getExpression(connection); verify(contextItemBinder).bindContextItem(connection, expression); }
@Test public void shouldBindVariables() throws Exception { factory.getExpression(connection); verify(variablesBinder).bindVariables(connection, expression); } |
### Question:
AttributeBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindNode(name, createAttributeNode(value), getType(connection)); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value,
String type); XQItemType getType(XQConnection connection); }### Answer:
@Test public void shouldCreateAttributeType() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(connection).createAttributeType(null, XQItemType.XQBASETYPE_ANYSIMPLETYPE); }
@Test public void shouldBindNode() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindNode(eq(qName), isA(Node.class), eq(xqItemType)); } |
### Question:
AtomicValueBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindAtomicValue(name, value, getType(connection, type)); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value,
String type); }### Answer:
@Test public void shouldCreateAtomicTypeUsingConnection() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(connection).createAtomicType(anyInt()); }
@Test public void shouldBindAtomicValue() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindAtomicValue(qName, VALUE, xqItemType); } |
### Question:
XQueryRunConfig { public boolean isContextItemEnabled() { return Boolean.parseBoolean(getExpressionValue(contextItemEnabledExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnContextItemEnabledValue() { boolean result = config.isContextItemEnabled(); assertThat(result, is(CONTEXT_ITEM_ENABLED)); } |
### Question:
TextBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindNode(name, createTextNode(value), getType(connection)); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value,
String type); XQItemType getType(XQConnection connection); }### Answer:
@Test public void shouldCreateDocumentTypeUsingConnection() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(connection).createTextType(); }
@Test public void shouldBindNode() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindNode(eq(qName), isA(Node.class), eq(xqItemType)); } |
### Question:
DocumentBinder implements TypeBinder { @Override public void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value, String type) throws Exception { expression.bindDocument(name, value, null, null); } @Override void bind(XQPreparedExpression expression, XQConnection connection, QName name, String value,
String type); }### Answer:
@Test public void shouldBindDocument() throws Exception { binder.bind(expression, connection, qName, VALUE, TYPE); verify(expression).bindDocument(qName, VALUE, null, null); } |
### Question:
XQueryRunConfig { public boolean isContextItemFromEditorEnabled() { return Boolean.parseBoolean(getExpressionValue(contextItemFromEditorEnabledExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnContextItemFromEditorEnabledValue() { boolean result = config.isContextItemFromEditorEnabled(); assertThat(result, is(CONTEXT_ITEM_FROM_EDITOR_ENABLED)); } |
### Question:
XQueryRunConfig { public String getContextItemFile() { return getExpressionValue(contextItemFileExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnContextItemFileValue() { String result = config.getContextItemFile(); assertThat(result, is(CONTEXT_ITEM_FILE_NAME)); } |
### Question:
XQueryRunConfig { public String getContextItemText() { return getExpressionValue(contextItemTextExpression); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnContextItemTextValue() { String result = config.getContextItemText(); assertThat(result, is(INNER_XML)); } |
### Question:
XQueryRunConfig { public List<XQueryRunnerVariable> getVariables() { String count = getExpressionValue(numberOfVariablesExpression); int numberOfVariables = Integer.valueOf(count); List<XQueryRunnerVariable> result = new ArrayList<XQueryRunnerVariable>(numberOfVariables); for (int i = 1; i <= numberOfVariables; i++) { String baseXPath = "/run/variables/list/variable[" + i + "]/"; XQueryRunnerVariable variable = new XQueryRunnerVariable(); variable.ACTIVE = Boolean.parseBoolean(getExpressionValue(getExpression(baseXPath + "@active"))); variable.NAME = getExpressionValue(getExpression(baseXPath + "@name")); variable.NAMESPACE = getExpressionValue(getExpression(baseXPath + "@namespace")); variable.TYPE = getExpressionValue(getExpression(baseXPath + "@type")); variable.VALUE = getExpressionValue(getExpression("string(" + baseXPath + "text())")); result.add(variable); } return result; } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnZeroVariables() throws Exception { config = new XQueryRunConfig("<run/>"); List<XQueryRunnerVariable> result = config.getVariables(); assertThat(result.size(), is(0)); }
@Test public void shouldReturnVariables() { List<XQueryRunnerVariable> result = config.getVariables(); assertThat(result.get(0).ACTIVE, is(VARIABLE_ACTIVE)); assertThat(result.get(0).NAME, is(VARIABLE_NAME)); assertThat(result.get(0).NAMESPACE, is(VARIABLE_NAMESPACE)); assertThat(result.get(0).TYPE, is(VARIABLE_TYPE)); assertThat(result.get(0).VALUE, is(INNER_XML)); } |
### Question:
XQueryRunConfig { public XQueryDataSourceType getDataSourceType() { return XQueryDataSourceType.getForName(getExpressionValue(dataSourceTypeExpression)); } XQueryRunConfig(String xml); String getMainFile(); boolean isContextItemEnabled(); boolean isContextItemFromEditorEnabled(); String getContextItemFile(); String getContextItemText(); List<XQueryRunnerVariable> getVariables(); XQueryDataSourceType getDataSourceType(); String getHost(); String getPort(); String getUsername(); String getPassword(); boolean isConfigFileEnabled(); String getConfigFile(); String getDatabaseName(); String getContextItemType(); boolean isDebugEnabled(); String getDebugPort(); }### Answer:
@Test public void shouldReturnDataSourceType() { XQueryDataSourceType result = config.getDataSourceType(); assertThat(result, is(DATA_SOURCE_TYPE)); } |
### Question:
TaskChain { public void doInvoke() { if (taskItemList.isEmpty()) { return; } for(TaskItem item : taskItemList) { BusinessWrapper<String> result = item.runTask(); callback.doNotify(result); if (!result.isSuccess()) { logger.warn("run task={} failure, result={}", item.getTaskName(), result.getMsg()); break; } else { logger.info("run task={} success, result={}", item.getTaskName(), result.getBody()); } } } TaskChain(String chainName, TaskCallback callback, List<TaskItem> taskItemList); void doInvoke(); }### Answer:
@Test public void test() { TaskCallback callback = new TaskCallback() { @Override public void doNotify(Object notify) { System.err.println(JSON.toJSONString(notify)); } }; List list = new ArrayList(); TaskItem taskItem = new TaskItem("asas") { @Override public BusinessWrapper<String> runTask() { return null; } }; list.add(taskItem); TaskChain taskChain = new TaskChain("initSystem", callback, list); taskChain.doInvoke(); } |
### Question:
AliyunLogManageServiceImpl implements AliyunLogManageService { private List<Project> queryListProject(String project) { Client client = aliyunLogService.acqClient(); int offset = 0; int size = 100; String logStoreSubName = ""; ListProjectRequest req = new ListProjectRequest(project, offset, size); List<Project> projects = new ArrayList<>(); try { projects = client.ListProject(req).getProjects(); } catch (LogException lg) { } return projects; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer:
@Test public void testQuerListProject() { List<String> projects = aliyunLogManageServiceImpl.queryListProject(); System.err.println("Projects:" + projects.toString() + "\n"); } |
### Question:
AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public List<String> queryListLogStores(String project) { Client client = aliyunLogService.acqClient(); int offset = 0; int size = 100; String logStoreSubName = ""; ListLogStoresRequest req = new ListLogStoresRequest(project, offset, size, logStoreSubName); ArrayList<String> logStores = new ArrayList<>(); try { logStores = client.ListLogStores(req).GetLogStores(); } catch (LogException lg) { } return logStores; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer:
@Test public void testQuerListLogStores() { List<String> logStores = aliyunLogManageServiceImpl.queryListLogStores("collect-web-service-logs"); System.err.println("ListLogs:" + logStores.toString() + "\n"); } |
### Question:
AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public List<String> queryListMachineGroup(String project, String groupName) { Client client = aliyunLogService.acqClient(); int offset = 0; int size = 50; ListMachineGroupRequest req = new ListMachineGroupRequest(project, groupName, offset, size); List<String> machineGroups = new ArrayList<>(); try { machineGroups = client.ListMachineGroup(req).GetMachineGroups(); } catch (LogException lg) { } return machineGroups; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer:
@Test public void testQueryListLogs() { List<String> list = aliyunLogManageServiceImpl.queryListMachineGroup("collect-web-service-logs",""); System.err.println("MachineGroups:" + list.toString() + "\n"); } |
### Question:
AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public MachineGroup getMachineGroup(String project, String groupName) { Client client = aliyunLogService.acqClient(); GetMachineGroupRequest req = new GetMachineGroupRequest(project, groupName); MachineGroup machineGroup = new MachineGroup(); try { machineGroup = client.GetMachineGroup(req).GetMachineGroup(); } catch (LogException lg) { } return machineGroup; } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer:
@Test public void testGetMachineGroup() { MachineGroup mg = aliyunLogManageServiceImpl.getMachineGroup("collect-web-service-logs","group_trade"); System.err.println("MachineGroup:" + mg.toString() + "\n"); } |
### Question:
AliyunLogManageServiceImpl implements AliyunLogManageService { @Override public BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO) { if (StringUtils.isEmpty(cfgVO.getTopic())) cfgVO.setTopic(cfgVO.getServerGroupDO().getName()); if (StringUtils.isEmpty(cfgVO.getServerGroupName())) cfgVO.setServerGroupName(cfgVO.getServerGroupDO().getName()); if (cfgVO.getServerGroupId() == 0) cfgVO.setServerGroupId(cfgVO.getServerGroupDO().getId()); if (!saveMachineGroup(cfgVO)) return new BusinessWrapper<>(false); try { if (cfgVO.getId() == 0) { logServiceDao.addLogServiceServerGroupCfg(cfgVO); } else { logServiceDao.updateLogServiceServerGroupCfg(cfgVO); } } catch (Exception e) { e.printStackTrace(); return new BusinessWrapper<>(false); } return new BusinessWrapper<>(true); } @Override List<String> queryListProject(); @Override List<String> queryListLogStores(String project); @Override List<String> queryListMachineGroup(String project, String groupName); @Override MachineGroup getMachineGroup(String project, String groupName); @Override MachineGroupVO getMachineGroupVO(String project, String groupName); boolean updateMachineGroup(LogServiceServerGroupCfgVO cfgVO); boolean addMachineGroup(LogServiceServerGroupCfgVO cfgVO); @Override BusinessWrapper<Boolean> saveServerGroupCfg(LogServiceServerGroupCfgVO cfgVO); @Override LogServiceStatusVO logServiceStatus(); static final String LOG_SERVICE_CONFIG_NAME; }### Answer:
@Test public void testSaveServerGroupCfg() { ServerGroupDO serverGroupDO = serverGroupDao.queryServerGroupByName("group_member"); LogServiceServerGroupCfgVO cfgVO = new LogServiceServerGroupCfgVO(serverGroupDO); cfgVO.setProject("collect-web-service-logs"); cfgVO.setLogstore("logstore_apps"); System.err.println(aliyunLogManageServiceImpl.saveServerGroupCfg(cfgVO)); } |
### Question:
IP { public String getIPSection(){ if(ip==null) return null; if(netmask == null || netmask.equals("32")){ return ip; } else{ return ip+"/"+netmask; } } IP(String ip); IP(String ip, String netmask); IP(String ip, String netmask, String getway); String getIp(); Boolean isPublicIP(); String toString(); String getIPSection(); }### Answer:
@Test public void test() { IP ip=new IP("10.100.1.0"); System.err.println(ip.getIPSection()); IP ip2=new IP("10.100.1.0/32"); System.err.println(ip2.getIPSection()); IP ip3=new IP("10.100.1.0/255.255.255.250"); System.err.println(ip3.getIPSection()); IP ip4=new IP("10.100.1.a"); System.err.println(ip4.getIPSection()); } |
### Question:
ExplainServiceImpl implements ExplainService { @Override public Set<String> doScanRepo(ExplainDTO explainDTO) { try { Git git = GitProcessor.cloneRepository(localPath + "/explain/" + explainDTO.getId() + "/", explainDTO.getRepo(), username, pwd, Collections.EMPTY_LIST); Set<String> refSet = GitProcessor.getRefList(git.getRepository()); refSet.remove("HEAD"); refSet.remove("head"); return refSet; } catch (Exception e) { logger.error(e.getMessage(), e); } return Collections.EMPTY_SET; } @Override void addRepoExplainSub(ExplainDTO explainDTO); @Override void delRepoExplainSub(long id); @Override TableVO<List<ExplainDTO>> queryRepoExplainSubList(String repo, int page, int length); @Override Set<String> doScanRepo(ExplainDTO explainDTO); @Override TableVO<List<String>> queryRepoList(String repo, int page, int length); @Override ExplainDTO getRepoSubById(long id); @Override TableVO<List<ExplainJob>> queryJobs(ExplainJob explainJob, int page, int length); @Override boolean subJob(ExplainJob explainJob); @Override boolean unsubJob(ExplainJob explainJob); }### Answer:
@Test public void testdoScanRepoAndTransRemote() { ExplainInfo explainInfo = new ExplainInfo(); explainInfo.setRepo("http: explainInfo.setScanPath(JSON.toJSONString(Arrays.asList("cmdb/cmdb-service/src/main/resources/sql"))); explainInfo.setNotifyEmails(JSON.toJSONString(Arrays.asList("xiaozhenxing@net"))); ExplainDTO explainDTO = new ExplainDTO(explainInfo); explainService.doScanRepo(explainDTO); } |
### Question:
IptablesRule { public String getRule() { buildRuleByType(); return getDesc() + getRuleHead() + ruleBody; } IptablesRule(String port, List<IP> ips, int ruleType, String desc); IptablesRule(String port, List<IP> ips, String desc); IptablesRule(String port, String desc); IptablesRule(List<IP> ips, String desc); String getDesc(); void setDesc(String desc); String getRule(); final static int ruleTypeAllowIP4Port; final static int ruleTypeOpenPort; final static int ruleTypeAllowIP; }### Answer:
@Test public void test() { IptablesRule ir = new IptablesRule("80", "HTTP/NGINX"); System.err.println(ir.getRule()); List<IP> ipList = new ArrayList<IP>(); ipList.add(new IP("10.17.0.0/8")); IptablesRule ir2 = new IptablesRule(ipList, "内网"); System.err.println(ir2.getRule()); ipList.add(new IP("192.168.0.0/16")); ipList.add(new IP("10.0.0.0/8")); IptablesRule ir3 = new IptablesRule(ipList, "多个内网"); System.err.println(ir3.getRule()); IptablesRule ir4 = new IptablesRule("8080",ipList,"HTTP/TOMCAT"); System.err.println(ir4.getRule()); IptablesRule ir5 = new IptablesRule("8080:8090",ipList,"HTTP/TOMCAT"); System.err.println(ir5.getRule()); } |
### Question:
Iptables { public String toBody() { body = getInfo(); body = body + getDesc(); for (IptablesRule ir : irList) { body = body + ir.getRule() +"\n"; } return body; } Iptables(List<IptablesRule> irList, String desc); Iptables(IptablesRule ir, String desc); String toBody(); }### Answer:
@Test public void test() { Iptables i = new Iptables(buildRules(),"测试规则"); System.err.println(i.toBody()); } |
### Question:
Getway { public Getway() { } Getway(); Getway(UserDO userDO, List<ServerGroupDO> serverGroups); Getway(List<ServerGroupDO> serverGroups, Map<String, List<ServerDO>> servers); String getPath(); void addUser(UserDO userDO); void addServerGroup(List<ServerGroupDO> serverGroups); void addServers(Map<String, List<ServerDO>> servers); @Override String toString(); }### Answer:
@Test public void testGetway() { List<UserDO> userDOList = authDao.getLoginUsers(); if (userDOList.isEmpty()) { return; } UserDO userDO = userDOList.get(0); ServerGroupDO serverGroupDO = serverGroupService.queryServerGroupByName("group_trade"); ServerGroupDO serverGroupDO2 = serverGroupService.queryServerGroupByName("group_member"); ServerGroupDO serverGroupDO3 = serverGroupService.queryServerGroupByName("group_wms"); List<ServerGroupDO> serverGroups = new ArrayList<>(); serverGroups.add(serverGroupDO); serverGroups.add(serverGroupDO2); serverGroups.add(serverGroupDO3); Map<String, List<ServerDO>> servers = new HashMap<>(); Getway gw = new Getway(userDO, serverGroups); System.err.println("生成用户getway.conf---------------------------------------"); System.err.println(gw.toString()); System.err.println("生成全局列表getway_host.conf---------------------------------------"); Getway gw2 = new Getway(serverGroups ,servers); System.err.println(gw2.toString()); System.err.println("---------------------------------------"); } |
### Question:
CmdUtils { public static String run(CommandLine commandline) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60*1000); exec.setWatchdog(watchdog); exec.setExitValues(null); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream); exec.setStreamHandler(streamHandler); exec.execute(commandline); String out = outputStream.toString("utf8"); String error = errorStream.toString("utf8"); return out + error; } catch (Exception e) { logger.error(e.getMessage(), e); return e.toString(); } } static String run(CommandLine commandline); static String runCmd(String cmd); static String run(String[] cmd); static String callShell(String cmd); }### Answer:
@Test public void test() { CommandLine cmd =new CommandLine("ps"); cmd.addArgument("-ef"); String rt=CmdUtils.run(cmd); System.err.println(rt); } |
### Question:
TimeViewUtils { public static String format(Date date) { long delta = new Date().getTime() - date.getTime(); if (delta < 1L * ONE_MINUTE) { long seconds = toSeconds(delta); return (seconds <= 0 ? 1 : seconds) + ONE_SECOND_AGO; } if (delta < 45L * ONE_MINUTE) { long minutes = toMinutes(delta); return (minutes <= 0 ? 1 : minutes) + ONE_MINUTE_AGO; } if (delta < 24L * ONE_HOUR) { long hours = toHours(delta); return (hours <= 0 ? 1 : hours) + ONE_HOUR_AGO; } if (delta < 48L * ONE_HOUR) { return "昨天"; } if (delta < 30L * ONE_DAY) { long days = toDays(delta); return (days <= 0 ? 1 : days) + ONE_DAY_AGO; } if (delta < 12L * 4L * ONE_WEEK) { long months = toMonths(delta); return (months <= 0 ? 1 : months) + ONE_MONTH_AGO; } else { long years = toYears(delta); return (years <= 0 ? 1 : years) + ONE_YEAR_AGO; } } static String format(Date date); }### Answer:
@Test public void test() { try{ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:m:s"); Date date = format.parse("2017-09-08 08:35:35"); System.out.println(TimeViewUtils.format(date)); }catch (Exception e){ } } |
### Question:
IOUtils { public static String getPath( String path){ if(path == null || path.equals("") ) return ""; String[] a = path.split("\\/"); path=path.replace(a[a.length-1],""); return path; } IOUtils(String body, String path); void setPath(String path); void setBody(String body); static void createDir(String path); static void writeFile(String body, String path); static String readFile(String path); static String getPath( String path); static boolean delFile(String path); }### Answer:
@Test public void test() { String p=IOUtils.getPath("/data/www/ROOT/1.txt"); System.out.println(p); } |
### Question:
EntityFinder { public <T, ID> T findById(CrudRepository<T, ID> repository, ID id, String notFoundMessage) { Optional<T> findResult = repository.findById(id); return getEntity(findResult, notFoundMessage); } T findById(CrudRepository<T, ID> repository,
ID id,
String notFoundMessage); T findOne(QuerydslPredicateExecutor<T> predicateExecutor,
Predicate predicate,
String notFoundMessage); }### Answer:
@Test public void findByIdShouldReturnResultWhenIsPresent() throws Exception { String processInstanceId = "5"; ProcessInstanceEntity processInstanceEntity = mock(ProcessInstanceEntity.class); given(repository.findById(processInstanceId)).willReturn(Optional.of(processInstanceEntity)); ProcessInstanceEntity retrieveProcessInstanceEntity = entityFinder.findById(repository, processInstanceId, "error"); assertThat(retrieveProcessInstanceEntity).isEqualTo(processInstanceEntity); }
@Test public void findByIdShouldThrowExceptionWhenNotPresent() throws Exception { String processInstanceId = "5"; given(repository.findById(processInstanceId)).willReturn(Optional.empty()); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Error"); entityFinder.findById(repository, processInstanceId, "Error"); } |
### Question:
QueryRelProvider implements RelProvider { @Override public String getCollectionResourceRelFor(Class<?> aClass) { return resourceRelationDescriptors.get(aClass).getCollectionResourceRel(); } QueryRelProvider(); @Override String getItemResourceRelFor(Class<?> aClass); @Override String getCollectionResourceRelFor(Class<?> aClass); @Override boolean supports(Class<?> aClass); }### Answer:
@Test public void getCollectionResourceRelForShouldReturnProcessInstancesWhenIsProcessInstanceEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(ProcessInstanceEntity.class); assertThat(collectionResourceRel).isEqualTo("processInstances"); }
@Test public void getCollectionResourceRelForShouldReturnTasksWhenIsTaskEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(TaskEntity.class); assertThat(collectionResourceRel).isEqualTo("tasks"); }
@Test public void getCollectionResourceRelForShouldReturnVariablesWhenIsProcessVariableEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(ProcessVariableEntity.class); assertThat(collectionResourceRel).isEqualTo("variables"); }
@Test public void getCollectionResourceRelForShouldReturnVariablesWhenIsTaskVariableEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(TaskVariableEntity.class); assertThat(collectionResourceRel).isEqualTo("variables"); }
@Test public void getCollectionResourceRelForShouldReturnProcessDefinitionsWhenIsProcessDefinitionEntity() { String collectionResourceRel = relProvider.getCollectionResourceRelFor(ProcessDefinitionEntity.class); assertThat(collectionResourceRel).isEqualTo("processDefinitions"); } |
### Question:
QueryRelProvider implements RelProvider { @Override public boolean supports(Class<?> aClass) { return resourceRelationDescriptors.keySet().contains(aClass); } QueryRelProvider(); @Override String getItemResourceRelFor(Class<?> aClass); @Override String getCollectionResourceRelFor(Class<?> aClass); @Override boolean supports(Class<?> aClass); }### Answer:
@Test public void shouldSupportProcessDefinitionEntity() { boolean supports = relProvider.supports(ProcessDefinitionEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportProcessInstanceEntity() { boolean supports = relProvider.supports(ProcessInstanceEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportTaskEntity() { boolean supports = relProvider.supports(TaskEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportProcessVariableEntity() { boolean supports = relProvider.supports(ProcessVariableEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldSupportTaskVariableEntity() { boolean supports = relProvider.supports(TaskVariableEntity.class); assertThat(supports).isTrue(); }
@Test public void shouldNotSupportUncoveredClasses() { boolean supports = relProvider.supports(ActivitiEntityMetadata.class); assertThat(supports).isFalse(); } |
### Question:
ProcessStartedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_STARTED.name(); } ProcessStartedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessStartedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_STARTED.name()); } |
### Question:
QueryEventHandlerContext { public void handle(CloudRuntimeEvent<?, ?>... events) { if (events != null) { for (CloudRuntimeEvent<?, ?> event : events) { QueryEventHandler handler = handlers.get(event.getEventType().name()); if (handler != null) { LOGGER.debug("Handling event: " + handler.getHandledEvent()); handler.handle(event); } else { LOGGER.info("No handler found for event: " + event.getEventType().name() + ". Ignoring event"); } } } } QueryEventHandlerContext(Set<QueryEventHandler> handlers); void handle(CloudRuntimeEvent<?, ?>... events); }### Answer:
@Test public void handleShouldSelectHandlerBasedOnEventType() { CloudTaskCreatedEvent event = new CloudTaskCreatedEventImpl(); context.handle(event); verify(handler).handle(event); }
@Test public void handleShouldDoNothingWhenNoHandlerIsFoundForTheGivenEvent() { CloudTaskCompletedEvent event = new CloudTaskCompletedEventImpl(); context.handle(event); verify(handler, never()).handle(any()); } |
### Question:
ProcessSuspendedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessSuspendedEvent suspendedEvent = (CloudProcessSuspendedEvent) event; String processInstanceId = suspendedEvent.getEntity().getId(); ProcessInstanceEntity processInstanceEntity = processInstanceRepository.findById(processInstanceId) .orElseThrow( () -> new QueryException("Unable to find process instance with the given id: " + processInstanceId) ); processInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.SUSPENDED); processInstanceEntity.setLastModified(new Date(suspendedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } ProcessSuspendedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstanceStateToSuspended() { CloudProcessSuspendedEvent event = buildProcessSuspendedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.SUSPENDED); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { CloudProcessSuspendedEvent event = buildProcessSuspendedEvent(); given(processInstanceRepository.findById("200")).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
ProcessSuspendedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_SUSPENDED.name(); } ProcessSuspendedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessSuspendedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_SUSPENDED.name()); } |
### Question:
ProcessCompletedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessCompletedEvent completedEvent = (CloudProcessCompletedEvent) event; String processInstanceId = completedEvent.getEntity().getId(); Optional<ProcessInstanceEntity> findResult = processInstanceRepository.findById(processInstanceId); if (findResult.isPresent()) { ProcessInstanceEntity processInstanceEntity = findResult.get(); processInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.COMPLETED); processInstanceEntity.setLastModified(new Date(completedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } else { throw new QueryException("Unable to find process instance with the given id: " + processInstanceId); } } ProcessCompletedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstanceStateToCompleted() { CloudProcessCompletedEvent event = createProcessCompletedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.COMPLETED); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { CloudProcessCompletedEvent event = createProcessCompletedEvent(); given(processInstanceRepository.findById("200")).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
EntityFinder { public <T> T findOne(QuerydslPredicateExecutor<T> predicateExecutor, Predicate predicate, String notFoundMessage) { Optional<T> findResult = predicateExecutor.findOne(predicate); return getEntity(findResult, notFoundMessage); } T findById(CrudRepository<T, ID> repository,
ID id,
String notFoundMessage); T findOne(QuerydslPredicateExecutor<T> predicateExecutor,
Predicate predicate,
String notFoundMessage); }### Answer:
@Test public void findOneShouldReturnResultWhenIsPresent() throws Exception { Predicate predicate = mock(Predicate.class); ProcessInstanceEntity processInstanceEntity = mock(ProcessInstanceEntity.class); given(repository.findOne(predicate)).willReturn(Optional.of(processInstanceEntity)); ProcessInstanceEntity retrievedProcessInstanceEntity = entityFinder.findOne(repository, predicate, "error"); assertThat(retrievedProcessInstanceEntity).isEqualTo(processInstanceEntity); }
@Test public void findOneShouldThrowExceptionWhenNotPresent() throws Exception { Predicate predicate = mock(Predicate.class); given(repository.findOne(predicate)).willReturn(Optional.empty()); expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Error"); entityFinder.findOne(repository, predicate, "Error"); } |
### Question:
ProcessCompletedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_COMPLETED.name(); } ProcessCompletedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessCompletedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_COMPLETED.name()); } |
### Question:
ProcessUpdatedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessUpdatedEvent updatedEvent = (CloudProcessUpdatedEvent) event; ProcessInstance eventProcessInstance = updatedEvent.getEntity(); ProcessInstanceEntity processInstanceEntity = processInstanceRepository.findById(eventProcessInstance.getId()) .orElseThrow( () -> new QueryException("Unable to find process instance with the given id: " + eventProcessInstance.getId()) ); processInstanceEntity.setBusinessKey(eventProcessInstance.getBusinessKey()); processInstanceEntity.setName(eventProcessInstance.getName()); processInstanceEntity.setLastModified(new Date(updatedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } ProcessUpdatedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstance() { CloudProcessUpdatedEvent event = buildProcessUpdatedEvent(); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(event.getEntity().getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setBusinessKey(event.getEntity().getBusinessKey()); verify(currentProcessInstanceEntity).setName(event.getEntity().getName()); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); verifyNoMoreInteractions(currentProcessInstanceEntity); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { CloudProcessUpdatedEvent event = buildProcessUpdatedEvent(); String id = event.getEntity().getId(); given(processInstanceRepository.findById(id)).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
ProcessUpdatedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_UPDATED.name(); } ProcessUpdatedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessUpdatedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_UPDATED.name()); } |
### Question:
ProcessDeployedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessDefinitionEvent.ProcessDefinitionEvents.PROCESS_DEPLOYED.name(); } ProcessDeployedEventHandler(ProcessDefinitionRepository processDefinitionRepository,
ProcessModelRepository processModelRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessDeployedEvent() { String handledEvent = handler.getHandledEvent(); Assertions.assertThat(handledEvent).isEqualTo(ProcessDefinitionEvent.ProcessDefinitionEvents.PROCESS_DEPLOYED.name()); } |
### Question:
ProcessResumedEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessResumedEvent processResumedEvent = (CloudProcessResumedEvent) event; String processInstanceId = processResumedEvent.getEntity().getId(); Optional<ProcessInstanceEntity> findResult = processInstanceRepository.findById(processInstanceId); ProcessInstanceEntity processInstanceEntity = findResult.orElseThrow(() -> new QueryException("Unable to find process instance with the given id: " + processInstanceId)); processInstanceEntity.setStatus(ProcessInstance.ProcessInstanceStatus.RUNNING); processInstanceEntity.setLastModified(new Date(processResumedEvent.getTimestamp())); processInstanceRepository.save(processInstanceEntity); } ProcessResumedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void handleShouldUpdateCurrentProcessInstanceStateToRunning() { ProcessInstanceImpl eventProcessInstance = new ProcessInstanceImpl(); eventProcessInstance.setId(UUID.randomUUID().toString()); CloudProcessResumedEvent event = new CloudProcessResumedEventImpl(eventProcessInstance); ProcessInstanceEntity currentProcessInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById(eventProcessInstance.getId())).willReturn(Optional.of(currentProcessInstanceEntity)); handler.handle(event); verify(processInstanceRepository).save(currentProcessInstanceEntity); verify(currentProcessInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.RUNNING); verify(currentProcessInstanceEntity).setLastModified(any(Date.class)); }
@Test public void handleShouldThrowExceptionWhenRelatedProcessInstanceIsNotFound() { ProcessInstanceImpl eventProcessInstance = new ProcessInstanceImpl(); eventProcessInstance.setId(UUID.randomUUID().toString()); CloudProcessResumedEvent event = new CloudProcessResumedEventImpl(eventProcessInstance); given(processInstanceRepository.findById(eventProcessInstance.getId())).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(event); } |
### Question:
ProcessResumedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_RESUMED.name(); } ProcessResumedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessResumedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_RESUMED.name()); } |
### Question:
ProcessCancelledEventHandler implements QueryEventHandler { @Override public void handle(CloudRuntimeEvent<?, ?> event) { CloudProcessCancelledEvent cancelledEvent = (CloudProcessCancelledEvent) event; LOGGER.debug("Handling cancel of process Instance " + cancelledEvent.getEntity().getId()); updateProcessInstanceStatus( processInstanceRepository .findById(cancelledEvent.getEntity().getId()) .orElseThrow(() -> new QueryException( "Unable to find process instance with the given id: " + cancelledEvent.getEntity().getId())), cancelledEvent.getTimestamp()); } ProcessCancelledEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void testUpdateExistingProcessInstanceWhenCancelled() { ProcessInstanceEntity processInstanceEntity = mock(ProcessInstanceEntity.class); given(processInstanceRepository.findById("200")).willReturn(Optional.of(processInstanceEntity)); handler.handle(createProcessCancelledEvent("200" )); verify(processInstanceRepository).save(processInstanceEntity); verify(processInstanceEntity).setStatus(ProcessInstance.ProcessInstanceStatus.CANCELLED); verify(processInstanceEntity).setLastModified(any(Date.class)); }
@Test public void testThrowExceptionWhenProcessInstanceNotFound() { given(processInstanceRepository.findById("200")).willReturn(Optional.empty()); expectedException.expect(QueryException.class); expectedException.expectMessage("Unable to find process instance with the given id: "); handler.handle(createProcessCancelledEvent("200")); } |
### Question:
ProcessCancelledEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_CANCELLED.name(); } ProcessCancelledEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessCancelledEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_CANCELLED.name()); } |
### Question:
ProcessCreatedEventHandler implements QueryEventHandler { @Override public String getHandledEvent() { return ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name(); } ProcessCreatedEventHandler(ProcessInstanceRepository processInstanceRepository); @Override void handle(CloudRuntimeEvent<?, ?> event); @Override String getHandledEvent(); }### Answer:
@Test public void getHandledEventShouldReturnProcessCreatedEvent() { String handledEvent = handler.getHandledEvent(); assertThat(handledEvent).isEqualTo(ProcessRuntimeEvent.ProcessEvents.PROCESS_CREATED.name()); } |
### Question:
VariableValueJsonConverter implements AttributeConverter<VariableValue<?>, String> { @Override public String convertToDatabaseColumn(VariableValue<?> variableValue) { try { return objectMapper.writeValueAsString(variableValue); } catch (JsonProcessingException e) { throw new QueryException("Unable to serialize variable.", e); } } VariableValueJsonConverter(); VariableValueJsonConverter(ObjectMapper objectMapper); @Override String convertToDatabaseColumn(VariableValue<?> variableValue); @Override VariableValue<?> convertToEntityAttribute(String dbData); }### Answer:
@Test public void convertToDatabaseColumnShouldConvertToJson() throws Exception { given(objectMapper.writeValueAsString(ENTITY_REPRESENTATION)).willReturn(JSON_REPRESENTATION); String convertedValue = converter.convertToDatabaseColumn(ENTITY_REPRESENTATION); assertThat(convertedValue).isEqualTo(JSON_REPRESENTATION); }
@Test public void convertToDatabaseColumnShouldThrowQueryExceptionWhenAnExceptionOccursWhileProcessing() throws Exception { MockJsonProcessingException exception = new MockJsonProcessingException("any"); given(objectMapper.writeValueAsString(ENTITY_REPRESENTATION)).willThrow(exception); Throwable thrown = catchThrowable(() -> converter.convertToDatabaseColumn(ENTITY_REPRESENTATION)); assertThat(thrown) .isInstanceOf(QueryException.class) .hasMessage("Unable to serialize variable.") .hasCause(exception); } |
### Question:
VariableValueJsonConverter implements AttributeConverter<VariableValue<?>, String> { @Override public VariableValue<?> convertToEntityAttribute(String dbData) { try { return objectMapper.readValue(dbData, VariableValue.class); } catch (IOException e) { throw new QueryException("Unable to deserialize variable.", e); } } VariableValueJsonConverter(); VariableValueJsonConverter(ObjectMapper objectMapper); @Override String convertToDatabaseColumn(VariableValue<?> variableValue); @Override VariableValue<?> convertToEntityAttribute(String dbData); }### Answer:
@Test public void convertToEntityAttributeShouldConvertFromJson() throws Exception { given(objectMapper.readValue(JSON_REPRESENTATION, VariableValue.class)).willReturn(ENTITY_REPRESENTATION); VariableValue<?> convertedValue = converter.convertToEntityAttribute(JSON_REPRESENTATION); assertThat(convertedValue).isEqualTo(ENTITY_REPRESENTATION); }
@Test public void convertToEntityAttributeShouldThrowExceptionWhenExceptionOccursWhileReading() throws Exception { IOException ioException = new IOException(); given(objectMapper.readValue(JSON_REPRESENTATION, VariableValue.class)).willThrow(ioException); Throwable thrown = catchThrowable(() -> converter.convertToEntityAttribute(JSON_REPRESENTATION)); assertThat(thrown) .isInstanceOf(QueryException.class) .hasMessage("Unable to deserialize variable.") .hasCause(ioException); } |
### Question:
QueryRelProvider implements RelProvider { @Override public String getItemResourceRelFor(Class<?> aClass) { return resourceRelationDescriptors.get(aClass).getItemResourceRel(); } QueryRelProvider(); @Override String getItemResourceRelFor(Class<?> aClass); @Override String getCollectionResourceRelFor(Class<?> aClass); @Override boolean supports(Class<?> aClass); }### Answer:
@Test public void getItemResourceRelForShouldReturnProcessDefinitionWhenIsProcessDefinitionEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(ProcessDefinitionEntity.class); assertThat(itemResourceRel).isEqualTo("processDefinition"); }
@Test public void getItemResourceRelForShouldReturnProcessInstanceWhenIsProcessInstanceEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(ProcessInstanceEntity.class); assertThat(itemResourceRel).isEqualTo("processInstance"); }
@Test public void getItemResourceRelForShouldReturnTaskWhenIsTaskEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(TaskEntity.class); assertThat(itemResourceRel).isEqualTo("task"); }
@Test public void getItemResourceRelForShouldReturnVariableWhenIsProcessVariableEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(ProcessVariableEntity.class); assertThat(itemResourceRel).isEqualTo("variable"); }
@Test public void getItemResourceRelForShouldReturnVariableWhenIsTaskVariableEntity() { String itemResourceRel = relProvider.getItemResourceRelFor(TaskVariableEntity.class); assertThat(itemResourceRel).isEqualTo("variable"); } |
### Question:
CloudSignalReceivedProducer implements BPMNElementEventListener<BPMNSignalReceivedEvent> { @Override public void onEvent(BPMNSignalReceivedEvent event) { eventsAggregator.add(eventConverter.from(event)); } CloudSignalReceivedProducer(ToCloudProcessRuntimeEventConverter eventConverter,
ProcessEngineEventsAggregator eventsAggregator); @Override void onEvent(BPMNSignalReceivedEvent event); }### Answer:
@Test public void onEventShouldConvertEventToCloudEventAndAddToAggregator() { BPMNSignalReceivedEventImpl event = new BPMNSignalReceivedEventImpl(new BPMNSignalImpl()); CloudBPMNSignalReceivedEventImpl cloudEvent = new CloudBPMNSignalReceivedEventImpl(); given(eventConverter.from(event)).willReturn(cloudEvent); cloudSignalReceivedProducer.onEvent(event); verify(eventsAggregator).add(cloudEvent); } |
### Question:
RuntimeBundleInfoMessageBuilderAppender implements MessageBuilderAppender { @Override public <P> MessageBuilder<P> apply(MessageBuilder<P> request) { Assert.notNull(request, "request must not be null"); return request.setHeader(RuntimeBundleInfoMessageHeaders.APP_NAME, properties.getAppName()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, properties.getServiceName()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_FULL_NAME, properties.getServiceFullName()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_TYPE, properties.getServiceType()) .setHeader(RuntimeBundleInfoMessageHeaders.SERVICE_VERSION, properties.getServiceVersion()); } RuntimeBundleInfoMessageBuilderAppender(RuntimeBundleProperties properties); @Override MessageBuilder<P> apply(MessageBuilder<P> request); }### Answer:
@Test public void testApply() { MessageBuilder<CloudRuntimeEvent<?,?>> request = MessageBuilder.withPayload(new IgnoredRuntimeEvent()); subject.apply(request); Message<CloudRuntimeEvent<?,?>> message = request.build(); assertThat(message.getHeaders()) .containsEntry(RuntimeBundleInfoMessageHeaders.APP_NAME, APP_NAME) .containsEntry(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, SPRING_APP_NAME) .containsEntry(RuntimeBundleInfoMessageHeaders.SERVICE_TYPE, SERVICE_TYPE) .containsEntry(RuntimeBundleInfoMessageHeaders.SERVICE_VERSION, SERVICE_VERSION); } |
### Question:
MQServiceTaskBehavior extends AbstractBpmnActivityBehavior implements TriggerableActivityBehavior { @Override public void trigger(DelegateExecution execution, String signalEvent, Object signalData) { leave(execution); } MQServiceTaskBehavior(IntegrationContextManager integrationContextManager,
ApplicationEventPublisher eventPublisher,
IntegrationContextBuilder integrationContextBuilder,
RuntimeBundleInfoAppender runtimeBundleInfoAppender,
DefaultServiceTaskBehavior defaultServiceTaskBehavior); @Override void execute(DelegateExecution execution); @Override void trigger(DelegateExecution execution,
String signalEvent,
Object signalData); }### Answer:
@Test public void triggerShouldCallLeave() { DelegateExecution execution = mock(DelegateExecution.class); doNothing().when(behavior).leave(execution); behavior.trigger(execution, null, null); verify(behavior).leave(execution); } |
### Question:
IntegrationContextRoutingKeyResolver extends AbstractMessageHeadersRoutingKeyResolver { @Override public String resolve(Map<String, Object> headers) { return build(headers, HEADER_KEYS); } @Override String resolve(Map<String, Object> headers); @Override String getPrefix(); final String[] HEADER_KEYS; }### Answer:
@Test public void testResolveRoutingKeyFromValidHeadersInAnyOrder() { Map<String, Object> headers = MapBuilder.<String, Object> map(RuntimeBundleInfoMessageHeaders.SERVICE_NAME, "service-name") .with(IntegrationContextMessageHeaders.PROCESS_INSTANCE_ID, "process-instance-id") .with(RuntimeBundleInfoMessageHeaders.APP_NAME, "app-name") .with(IntegrationContextMessageHeaders.CONNECTOR_TYPE, "connector-type") .with(IntegrationContextMessageHeaders.BUSINESS_KEY, "business-key"); String routingKey = subject.resolve(headers); assertThat(routingKey).isEqualTo("integrationContext.service-name.app-name.connector-type.process-instance-id.business-key"); } |
### Question:
SuspendProcessInstanceCmdExecutor extends AbstractCommandExecutor<SuspendProcessPayload> { public SuspendProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime) { this.processAdminRuntime = processAdminRuntime; } SuspendProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override ProcessInstanceResult execute(SuspendProcessPayload suspendProcessPayload); }### Answer:
@Test public void suspendProcessInstanceCmdExecutorTest() { SuspendProcessPayload suspendProcessInstanceCmd = new SuspendProcessPayload("x"); assertThat(suspendProcessInstanceCmdExecutor.getHandledType()).isEqualTo(SuspendProcessPayload.class.getName()); suspendProcessInstanceCmdExecutor.execute(suspendProcessInstanceCmd); verify(processAdminRuntime).suspend(suspendProcessInstanceCmd); } |
### Question:
CompleteTaskCmdExecutor extends AbstractCommandExecutor<CompleteTaskPayload> { public CompleteTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime) { this.taskAdminRuntime = taskAdminRuntime; } CompleteTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime); @Override TaskResult execute(CompleteTaskPayload completeTaskPayload); }### Answer:
@Test public void completeTaskCmdExecutorTest() { Map<String, Object> variables = new HashMap<>(); CompleteTaskPayload completeTaskPayload = new CompleteTaskPayload("taskId", variables); assertThat(completeTaskCmdExecutor.getHandledType()).isEqualTo(CompleteTaskPayload.class.getName()); completeTaskCmdExecutor.execute(completeTaskPayload); verify(taskAdminRuntime).complete(completeTaskPayload); } |
### Question:
DeleteProcessInstanceCmdExecutor extends AbstractCommandExecutor<DeleteProcessPayload> { @Override public EmptyResult execute(DeleteProcessPayload deleteProcessPayload) { ProcessInstance processInstance = processAdminRuntime.delete(deleteProcessPayload); if (processInstance != null) { return new EmptyResult(deleteProcessPayload); } else { throw new IllegalStateException("Failed to delete processInstance"); } } DeleteProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override EmptyResult execute(DeleteProcessPayload deleteProcessPayload); }### Answer:
@Test public void startProcessInstanceCmdExecutorTest() { DeleteProcessPayload payload = ProcessPayloadBuilder.delete() .withProcessInstanceId("def key") .build(); ProcessInstance fakeProcessInstance = mock(ProcessInstance.class); given(processAdminRuntime.delete(payload)).willReturn(fakeProcessInstance); assertThat(subject.getHandledType()).isEqualTo(DeleteProcessPayload.class.getName()); subject.execute(payload); verify(processAdminRuntime).delete(payload); } |
### Question:
ClaimTaskCmdExecutor extends AbstractCommandExecutor<ClaimTaskPayload> { public ClaimTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime) { this.taskAdminRuntime = taskAdminRuntime; } ClaimTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime); @Override TaskResult execute(ClaimTaskPayload claimTaskPayload); }### Answer:
@Test public void claimTaskCmdExecutorTest() { ClaimTaskPayload claimTaskPayload = new ClaimTaskPayload("taskId", "assignee"); assertThat(claimTaskCmdExecutor.getHandledType()).isEqualTo(ClaimTaskPayload.class.getName()); claimTaskCmdExecutor.execute(claimTaskPayload); verify(taskAdminRuntime).claim(claimTaskPayload); } |
### Question:
ReceiveMessageCmdExecutor extends AbstractCommandExecutor<ReceiveMessagePayload> { @Override public EmptyResult execute(ReceiveMessagePayload command) { processAdminRuntime.receive(command); return new EmptyResult(command); } ReceiveMessageCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override EmptyResult execute(ReceiveMessagePayload command); }### Answer:
@Test public void signalProcessInstancesCmdExecutorTest() { ReceiveMessagePayload payload = new ReceiveMessagePayload("messageName", "correlationKey", Collections.emptyMap()); assertThat(subject.getHandledType()).isEqualTo(ReceiveMessagePayload.class.getName()); subject.execute(payload); verify(processAdminRuntime).receive(payload); } |
### Question:
StartProcessInstanceCmdExecutor extends AbstractCommandExecutor<StartProcessPayload> { public StartProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime) { this.processAdminRuntime = processAdminRuntime; } StartProcessInstanceCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override ProcessInstanceResult execute(StartProcessPayload startProcessPayload); }### Answer:
@Test public void startProcessInstanceCmdExecutorTest() { StartProcessPayload startProcessInstanceCmd = ProcessPayloadBuilder.start() .withProcessDefinitionKey("def key") .withName("name") .withBusinessKey("business key") .build(); ProcessInstance fakeProcessInstance = mock(ProcessInstance.class); given(processAdminRuntime.start(startProcessInstanceCmd)).willReturn(fakeProcessInstance); assertThat(startProcessInstanceCmdExecutor.getHandledType()).isEqualTo(StartProcessPayload.class.getName()); startProcessInstanceCmdExecutor.execute(startProcessInstanceCmd); verify(processAdminRuntime).start(startProcessInstanceCmd); } |
### Question:
StartMessageCmdExecutor extends AbstractCommandExecutor<StartMessagePayload> { @Override public ProcessInstanceResult execute(StartMessagePayload command) { ProcessInstance result = processAdminRuntime.start(command); return new ProcessInstanceResult(command, result); } StartMessageCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override ProcessInstanceResult execute(StartMessagePayload command); }### Answer:
@Test public void signalProcessInstancesCmdExecutorTest() { StartMessagePayload payload = new StartMessagePayload("messageName", "businessKey", Collections.emptyMap()); assertThat(subject.getHandledType()).isEqualTo(StartMessagePayload.class.getName()); subject.execute(payload); verify(processAdminRuntime).start(payload); } |
### Question:
SignalCmdExecutor extends AbstractCommandExecutor<SignalPayload> { @Override public EmptyResult execute(SignalPayload signalPayload) { processAdminRuntime.signal(signalPayload); return new EmptyResult(signalPayload); } SignalCmdExecutor(ProcessAdminRuntime processAdminRuntime); @Override EmptyResult execute(SignalPayload signalPayload); }### Answer:
@Test public void signalProcessInstancesCmdExecutorTest() { SignalPayload signalPayload = new SignalPayload("x", null); assertThat(signalCmdExecutor.getHandledType()).isEqualTo(SignalPayload.class.getName()); signalCmdExecutor.execute(signalPayload); verify(processAdminRuntime).signal(signalPayload); } |
### Question:
ReleaseTaskCmdExecutor extends AbstractCommandExecutor<ReleaseTaskPayload> { public ReleaseTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime) { this.taskAdminRuntime = taskAdminRuntime; } ReleaseTaskCmdExecutor(TaskAdminRuntime taskAdminRuntime); @Override TaskResult execute(ReleaseTaskPayload releaseTaskPayload); }### Answer:
@Test public void releaseTaskCmdExecutorTest() { ReleaseTaskPayload releaseTaskPayload = new ReleaseTaskPayload("taskId"); assertThat(releaseTaskCmdExecutor.getHandledType()).isEqualTo(ReleaseTaskPayload.class.getName()); releaseTaskCmdExecutor.execute(releaseTaskPayload); verify(taskAdminRuntime).release(releaseTaskPayload); } |
### Question:
BasicAuthenticationProvider implements AuthenticationProvider { @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); UserDetails userDetails = userDetailsService.loadUserByUsername(name); boolean authenticated = userDetails.getPassword().equals(password) && userDetails.isAccountNonExpired() && userDetails.isEnabled() && userDetails.isCredentialsNonExpired(); if (authenticated) { org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(name); return new UsernamePasswordAuthenticationToken(name, password, userDetails.getAuthorities()); } else { throw new BadCredentialsException("Authentication failed for this username and password"); } } @Autowired BasicAuthenticationProvider(UserDetailsService userDetailsService); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> authentication); }### Answer:
@Test public void testAuthenticate() { Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("testrole")); User user = new User("test", "pass", authorities); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("test", "pass", authorities); when(userDetailsService.loadUserByUsername("test")) .thenReturn(user); assertThat(basicAuthenticationProvider.authenticate(authentication)).isNotNull(); }
@Test public void testAuthenticationFailure() { Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("testrole")); User user = new User("test", "pass", authorities); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("differentuser", "differentpass", authorities); when(userDetailsService.loadUserByUsername("differentuser")) .thenReturn(user); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> basicAuthenticationProvider.authenticate(authentication)); } |
### Question:
BasicAuthenticationProvider implements AuthenticationProvider { @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } @Autowired BasicAuthenticationProvider(UserDetailsService userDetailsService); @Override Authentication authenticate(Authentication authentication); @Override boolean supports(Class<?> authentication); }### Answer:
@Test public void testSupports() { assertThat(basicAuthenticationProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); assertThat(basicAuthenticationProvider.supports(Integer.class)).isFalse(); } |
### Question:
ToCandidateUserConverter { public List<CandidateUser> from (List<String> users){ List<CandidateUser> list = new ArrayList<>(); users.forEach(user -> list.add(new CandidateUser(user))); return list; } List<CandidateUser> from(List<String> users); }### Answer:
@Test public void shouldConvertStringUsersToCanidateUsers(){ String user = "user1"; List<String> userList = new ArrayList<>(); userList.add(user); List<CandidateUser> convertedUserList = toCandidateUserConverter.from(userList); assertThat(convertedUserList.get(0)).isInstanceOf(CandidateUser.class); assertThat(convertedUserList.get(0).getUser()).isEqualTo(user); } |
### Question:
ToCandidateGroupConverter { public List<CandidateGroup> from (List<String> users){ List<CandidateGroup> list = new ArrayList<>(); users.forEach(user -> list.add(new CandidateGroup(user))); return list; } List<CandidateGroup> from(List<String> users); }### Answer:
@Test public void shouldConvertStringGroupsToCanidateGroups(){ String group = "group1"; List<String> groupList = new ArrayList<>(); groupList.add(group); List<CandidateGroup> convertedGroupList = toCandidateGroupConverter.from(groupList); assertThat(convertedGroupList.get(0)).isInstanceOf(CandidateGroup.class); assertThat(convertedGroupList.get(0).getGroup()).isEqualTo(group); } |
### Question:
ProcessInstanceResourceAssembler implements ResourceAssembler<ProcessInstance, Resource<CloudProcessInstance>> { @Override public Resource<CloudProcessInstance> toResource(ProcessInstance processInstance) { CloudProcessInstance cloudProcessInstance = toCloudProcessInstanceConverter.from(processInstance); Link processInstancesRel = linkTo(methodOn(ProcessInstanceControllerImpl.class).getProcessInstances(null)) .withRel("processInstances"); Link selfLink = linkTo(methodOn(ProcessInstanceControllerImpl.class).getProcessInstanceById(cloudProcessInstance.getId())).withSelfRel(); Link variablesLink = linkTo(methodOn(ProcessInstanceVariableControllerImpl.class).getVariables(cloudProcessInstance.getId())).withRel("variables"); Link homeLink = linkTo(HomeControllerImpl.class).withRel("home"); return new Resource<>(cloudProcessInstance, selfLink, variablesLink, processInstancesRel, homeLink); } ProcessInstanceResourceAssembler(ToCloudProcessInstanceConverter toCloudProcessInstanceConverter); @Override Resource<CloudProcessInstance> toResource(ProcessInstance processInstance); }### Answer:
@Test public void toResourceShouldReturnResourceWithSelfLinkContainingResourceId() { CloudProcessInstance cloudModel = mock(CloudProcessInstance.class); given(cloudModel.getId()).willReturn("my-identifier"); ProcessInstance model = mock(ProcessInstance.class); given(toCloudProcessInstanceConverter.from(model)).willReturn(cloudModel); Resource<CloudProcessInstance> resource = resourceAssembler.toResource(model); Link selfResourceLink = resource.getLink("self"); assertThat(selfResourceLink).isNotNull(); assertThat(selfResourceLink.getHref()).contains("my-identifier"); } |
### Question:
ProcessDefinitionResourceAssembler implements ResourceAssembler<ProcessDefinition, Resource<CloudProcessDefinition>> { @Override public Resource<CloudProcessDefinition> toResource(ProcessDefinition processDefinition) { CloudProcessDefinition cloudProcessDefinition = converter.from(processDefinition); Link selfRel = linkTo(methodOn(ProcessDefinitionControllerImpl.class).getProcessDefinition(cloudProcessDefinition.getId())).withSelfRel(); Link startProcessLink = linkTo(methodOn(ProcessInstanceControllerImpl.class).startProcess(null)).withRel("startProcess"); Link homeLink = linkTo(HomeControllerImpl.class).withRel("home"); return new Resource<>(cloudProcessDefinition, selfRel, startProcessLink, homeLink); } ProcessDefinitionResourceAssembler(ToCloudProcessDefinitionConverter converter); @Override Resource<CloudProcessDefinition> toResource(ProcessDefinition processDefinition); }### Answer:
@Test public void toResourceShouldReturnResourceWithSelfLinkContainingResourceId() { ProcessDefinitionImpl processDefinition = new ProcessDefinitionImpl(); processDefinition.setId("my-identifier"); given(converter.from(processDefinition)).willReturn(new CloudProcessDefinitionImpl(processDefinition)); Resource<CloudProcessDefinition> processDefinitionResource = resourceAssembler.toResource(processDefinition); Link selfResourceLink = processDefinitionResource.getLink("self"); assertThat(selfResourceLink).isNotNull(); assertThat(selfResourceLink.getHref()).contains("my-identifier"); } |
### Question:
ProcessDefinitionMetaResourceAssembler implements ResourceAssembler<ProcessDefinitionMeta, Resource<ProcessDefinitionMeta>> { @Override public Resource<ProcessDefinitionMeta> toResource(ProcessDefinitionMeta processDefinitionMeta) { Link metadata = linkTo(methodOn(ProcessDefinitionMetaControllerImpl.class).getProcessDefinitionMetadata(processDefinitionMeta.getId())).withRel("meta"); Link selfRel = linkTo(methodOn(ProcessDefinitionControllerImpl.class).getProcessDefinition(processDefinitionMeta.getId())).withSelfRel(); Link startProcessLink = linkTo(methodOn(ProcessInstanceControllerImpl.class).startProcess(null)).withRel("startProcess"); Link homeLink = linkTo(HomeControllerImpl.class).withRel("home"); return new Resource<>(processDefinitionMeta, metadata, selfRel, startProcessLink, homeLink); } @Override Resource<ProcessDefinitionMeta> toResource(ProcessDefinitionMeta processDefinitionMeta); }### Answer:
@Test public void toResourceShouldReturnResourceWithSelfLinkContainingResourceId() { ProcessDefinitionMeta model = mock(ProcessDefinitionMeta.class); when(model.getId()).thenReturn("my-identifier"); Resource<ProcessDefinitionMeta> resource = resourceAssembler.toResource(model); Link selfResourceLink = resource.getLink("self"); assertThat(selfResourceLink).isNotNull(); assertThat(selfResourceLink.getHref()).contains("my-identifier"); Link metaResourceLink = resource.getLink("meta"); assertThat(metaResourceLink).isNotNull(); assertThat(metaResourceLink.getHref()).contains("my-identifier"); } |
### Question:
ProcessEngineEventsAggregator extends BaseCommandContextEventsAggregator<CloudRuntimeEvent<?,?>, MessageProducerCommandContextCloseListener> { @Override protected Class<MessageProducerCommandContextCloseListener> getCloseListenerClass() { return MessageProducerCommandContextCloseListener.class; } ProcessEngineEventsAggregator(MessageProducerCommandContextCloseListener closeListener); @Override void add(CloudRuntimeEvent<?, ?> element); }### Answer:
@Test public void getCloseListenerClassShouldReturnMessageProducerCommandContextCloseListenerClass() { Class<MessageProducerCommandContextCloseListener> listenerClass = eventsAggregator.getCloseListenerClass(); assertThat(listenerClass).isEqualTo(MessageProducerCommandContextCloseListener.class); } |
### Question:
ProcessEngineEventsAggregator extends BaseCommandContextEventsAggregator<CloudRuntimeEvent<?,?>, MessageProducerCommandContextCloseListener> { @Override protected MessageProducerCommandContextCloseListener getCloseListener() { return closeListener; } ProcessEngineEventsAggregator(MessageProducerCommandContextCloseListener closeListener); @Override void add(CloudRuntimeEvent<?, ?> element); }### Answer:
@Test public void getCloseListenerShouldReturnTheCloserListenerPassedInTheConstructor() { MessageProducerCommandContextCloseListener retrievedCloseListener = eventsAggregator.getCloseListener(); assertThat(retrievedCloseListener).isEqualTo(closeListener); } |
### Question:
ProcessEngineEventsAggregator extends BaseCommandContextEventsAggregator<CloudRuntimeEvent<?,?>, MessageProducerCommandContextCloseListener> { @Override protected String getAttributeKey() { return MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS; } ProcessEngineEventsAggregator(MessageProducerCommandContextCloseListener closeListener); @Override void add(CloudRuntimeEvent<?, ?> element); }### Answer:
@Test public void getAttributeKeyShouldReturnProcessEngineEvents() { String attributeKey = eventsAggregator.getAttributeKey(); assertThat(attributeKey).isEqualTo(MessageProducerCommandContextCloseListener.PROCESS_ENGINE_EVENTS); } |
### Question:
Score { public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("Usage java " + Score.class.getName() + " <FILENAME>.csv <SCORE.csv>"); return; } final String csvFileName = args[0]; File csvFile = new File(csvFileName); if (!csvFile.exists()) { System.err.println("File " + csvFileName + " was not found"); return; } final String csvScoreFileName = args[1]; File csvScoreFile = new File(csvScoreFileName); if (csvScoreFile.exists()) { log("Deleting existing " + csvScoreFileName); csvScoreFile.delete(); } Map<ToolBudgetKey, Double> scoreMap = computeScore(csvFile); PrintStream writer = new PrintStream(csvScoreFile); log("Writing results to new file " + csvScoreFileName); printScore(writer, scoreMap); } static void log(String msg); static void main(String[] args); static Map<ToolBudgetKey, Double> aggregateScorePerTool(
Map<ToolBudgetBenchmarkKey, Double> scorePerBenchmark); }### Answer:
@Test public void testOutputFile() throws FileNotFoundException, IOException { final String csvFileName = System.getProperty("user.dir") + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + BLANK_LINE_CSV; final String outFileName = System.getProperty("user.dir") + File.separator + "out.csv"; File csvFile = new File(csvFileName); Assume.assumeTrue(csvFile.exists()); File outFile = new File(outFileName); try { if (outFile.exists()) { outFile.delete(); } Score.main(new String[] { csvFileName, outFileName }); assertTrue(outFile.exists()); } finally { outFile.delete(); } } |
### Question:
CheckerMain extends AbstractMojo implements PluginBase { void setExcludes(final String[] excludes) { this.excludes = excludes; } @Override void execute(); @Override PrettyPrintValidationResults.PluginLogger getPluginLogger(); @Override List<String> getExcludeList(); @Override List<String> getSearchPathList(); @Override String[] getValidatorPackages(); @Override String[] getValidatorClasses(); void loadProjectclasspath(); }### Answer:
@Test void shouldSkipFileIfItsExcluded() { final String ignoredFilename = "empty-as-well.dmn"; testee.setExcludes(new String[] { ignoredFilename }); final List<File> filesToTest = testee.fetchFilesToTestFromSearchPaths(Collections.singletonList(Paths.get(""))); Assertions.assertTrue(filesToTest.stream().noneMatch(file -> file.getName().equals(ignoredFilename))); } |
### Question:
CheckerMain extends AbstractMojo implements PluginBase { void setSearchPaths(final String[] searchPaths) { this.searchPaths = searchPaths; } @Override void execute(); @Override PrettyPrintValidationResults.PluginLogger getPluginLogger(); @Override List<String> getExcludeList(); @Override List<String> getSearchPathList(); @Override String[] getValidatorPackages(); @Override String[] getValidatorClasses(); void loadProjectclasspath(); }### Answer:
@Test void shouldDetectIfFileIsOnSearchPath() { testee.setSearchPaths(new String[] {"src/"}); final MojoExecutionException assertionError = Assertions.assertThrows(MojoExecutionException.class, testee::execute); Assertions.assertTrue(assertionError.getMessage().contains("Some files are not valid, see previous logs.")); }
@Test void shouldDetectIfFileIsOnSearchPathWithMultiplePaths() { testee.setSearchPaths(new String[] {"src/main/java","src/"}); final MojoExecutionException assertionError = Assertions.assertThrows(MojoExecutionException.class, testee::execute); Assertions.assertTrue(assertionError.getMessage().contains("Some files are not valid, see previous logs.")); } |
### Question:
RequirementGraph extends DirectedAcyclicGraph<DrgElement, DefaultEdge> { public static RequirementGraph from(final DmnModelInstance dmnModelInstance) throws IllegalArgumentException { final Collection<Decision> decisions = dmnModelInstance.getModelElementsByType(Decision.class); final Collection<KnowledgeSource> knowledgeSources = dmnModelInstance.getModelElementsByType(KnowledgeSource.class); final Collection<InputData> inputData = dmnModelInstance.getModelElementsByType(InputData.class); final RequirementGraph drg = new RequirementGraph(DefaultEdge.class, dmnModelInstance.getDefinitions()); Stream.of(decisions, knowledgeSources, inputData).flatMap(Collection::stream).forEach(drg::addVertex); for (Decision decision : decisions) { decision.getInformationRequirements().stream() .flatMap(RequirementGraph::collectDrgElements) .forEach(drgElement -> drg.addEdge(drgElement, decision)); decision.getAuthorityRequirements().stream() .flatMap(RequirementGraph::collectDrgElements) .forEach(drgElement -> drg.addEdge(drgElement, decision)); } for (KnowledgeSource knowledgeSource : knowledgeSources) { knowledgeSource.getAuthorityRequirement().stream() .flatMap(RequirementGraph::collectDrgElements) .forEach(drgElement -> drg.addEdge(drgElement, knowledgeSource)); } return drg; } RequirementGraph(Class<? extends DefaultEdge> edgeClass, Definitions definitions); Definitions getDefinitions(); static RequirementGraph from(final DmnModelInstance dmnModelInstance); }### Answer:
@Test void emptyGraphFromEmptyModel() { final DmnModelInstance emptyModel = Dmn.createEmptyModel(); final RequirementGraph requirementGraph = RequirementGraph.from(emptyModel); assertTrue(requirementGraph.vertexSet().isEmpty()); assertTrue(requirementGraph.edgeSet().isEmpty()); } |
### Question:
AggregateTrustManager implements X509TrustManager { public static void initialize(KeyStore... keyStores) throws Exception { TrustManager[] trustManagers = new TrustManager[] { new AggregateTrustManager(keyStores) }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustManagers, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } private AggregateTrustManager(KeyStore... keyStores); static void initialize(KeyStore... keyStores); @Override void checkClientTrusted(X509Certificate[] chain, String authType); @Override void checkServerTrusted(X509Certificate[] chain, String authType); @Override X509Certificate[] getAcceptedIssuers(); }### Answer:
@Test public void testWithDefault_usingBothCacertsAndRioKeyStore() throws Exception { AggregateTrustManager.initialize(keyStore); URL locationURL = new URL("https: URLConnection urlConnection = locationURL.openConnection(); urlConnection.connect(); }
@Test(expected= SSLHandshakeException.class) public void testWithJustRioKeystore_shouldFail() throws Exception { System.setProperty("javax.net.ssl.trustStore", keyStoreFile.getPath()); AggregateTrustManager.initialize(keyStore); URL locationURL = new URL("https: URLConnection urlConnection = locationURL.openConnection(); urlConnection.connect(); } |
### Question:
IdleServiceManager { public IdleServiceManager(final Long maxIdleTime, final ServiceElement serviceElement) { this.maxIdleTime = maxIdleTime; this.serviceElement = serviceElement; long delay = TimeUtil.computeLeaseRenewalTime(maxIdleTime); if(logger.isDebugEnabled()) { logger.debug("Service [{}] idle time: {}, computed delay time for checking idle status: {}.", LoggingUtil.getLoggingName(serviceElement), TimeUtil.format(maxIdleTime), TimeUtil.format(delay)); } scheduledExecutorService.scheduleWithFixedDelay(new IdleChecker(delay), delay, delay, TimeUnit.MILLISECONDS); } IdleServiceManager(final Long maxIdleTime, final ServiceElement serviceElement); void addService(final ServiceActivityProvider service); void removeService(final ServiceActivityProvider service); void terminate(); }### Answer:
@Test public void testIdleServiceManager() throws InterruptedException { ServiceElement serviceElement = TestUtil.makeServiceElement("bar", "foo", 2); IdleServiceManager idleServiceManager = new IdleServiceManager(3000L, serviceElement); TestServiceActivityProvider sap1 = new TestServiceActivityProvider(); TestServiceActivityProvider sap2 = new TestServiceActivityProvider(); idleServiceManager.addService(sap1); Listener l = new Listener(); ServiceChannel.getInstance().subscribe(l, serviceElement, ServiceChannelEvent.Type.IDLE); Thread.sleep(1000); idleServiceManager.addService(sap2); sap1.active = false; Thread.sleep(1000); sap2.active = false; int i = 0; long t0 = System.currentTimeMillis(); while(l.notified==0 && i<10) { Thread.sleep(500); i++; } System.out.println("Waited "+(System.currentTimeMillis()-t0)+" millis"); Assert.assertTrue(l.notified == 1); } |
### Question:
ServiceChannel { public void subscribe(final ServiceChannelListener listener, final AssociationDescriptor associationDescriptor, final ServiceChannelEvent.Type type) { subscribe(listener, associationDescriptor.getName(), associationDescriptor.getInterfaceNames(), associationDescriptor.getOperationalStringName(), type); } static ServiceChannel getInstance(); void subscribe(final ServiceChannelListener listener,
final AssociationDescriptor associationDescriptor,
final ServiceChannelEvent.Type type); void subscribe(final ServiceChannelListener listener,
final ServiceElement serviceElement,
final ServiceChannelEvent.Type type); void unsubscribe(final ServiceChannelListener listener); void broadcast(final ServiceChannelEvent event); }### Answer:
@Test public void testSubscribe() { ServiceChannel serviceChannel = ServiceChannel.getInstance(); ServiceElement serviceElement = TestUtil.makeServiceElement("bar", "foo"); Listener l1 = new Listener(); serviceChannel.subscribe(l1, serviceElement, ServiceChannelEvent.Type.PROVISIONED); Listener l2 = new Listener(); serviceChannel.subscribe(l2, serviceElement, ServiceChannelEvent.Type.FAILED); Listener l3 = new Listener(); serviceChannel.subscribe(l3, serviceElement, ServiceChannelEvent.Type.IDLE); serviceChannel.broadcast(new ServiceChannelEvent(new Object(), serviceElement, ServiceChannelEvent.Type.PROVISIONED)); Assert.assertTrue(l1.notified); Assert.assertFalse(l2.notified); Assert.assertFalse(l3.notified); l1.notified = false; serviceChannel.broadcast(new ServiceChannelEvent(new Object(), serviceElement, ServiceChannelEvent.Type.FAILED)); Assert.assertFalse(l1.notified); Assert.assertTrue(l2.notified); Assert.assertFalse(l3.notified); l2.notified = false; serviceChannel.broadcast(new ServiceChannelEvent(new Object(), serviceElement, ServiceChannelEvent.Type.IDLE)); Assert.assertFalse(l1.notified); Assert.assertFalse(l2.notified); Assert.assertTrue(l3.notified); l3.notified = false; } |
### Question:
DeploymentVerifier { RemoteRepository[] mergeRepositories(final RemoteRepository[] r1, final RemoteRepository[] r2) { Set<RemoteRepository> remoteRepositories = new HashSet<>(); Collections.addAll(remoteRepositories, r1); Collections.addAll(remoteRepositories, r2); return remoteRepositories.toArray(new RemoteRepository[0]); } DeploymentVerifier(final Configuration config, final DiscoveryManagement discoveryManagement); void verifyDeploymentRequest(final DeployRequest request); void verifyOperationalString(final OperationalString opString, final RemoteRepository[] repositories); void verifyOperationalStringService(final ServiceElement service,
final Resolver resolver,
final RemoteRepository[] repositories); }### Answer:
@Test public void testMergeRepositories() throws Exception { RemoteRepository[] r1 = new RemoteRepository[]{createRR("http: createRR("http: RemoteRepository[] r2 = new RemoteRepository[]{createRR("http: createRR("http: RemoteRepository[] repositories = deploymentVerifier.mergeRepositories(r1, r2); Assert.assertTrue(repositories.length==3); } |
### Question:
TransientServiceStatementManager implements ServiceStatementManager { public void terminate() { statementMap.clear(); } TransientServiceStatementManager(Configuration config); void terminate(); ServiceStatement[] get(); ServiceStatement get(ServiceElement sElem); void record(ServiceStatement statement); }### Answer:
@Test public void testTerminate() throws Exception { serviceStatementManager.terminate(); Assert.assertTrue(serviceStatementManager.get().length==0); } |
### Question:
TransientServiceStatementManager implements ServiceStatementManager { public ServiceStatement[] get() { ServiceStatement[] statements; synchronized (statementMap) { statements = statementMap.values().toArray(new ServiceStatement[statementMap.values().size()]); } return statements; } TransientServiceStatementManager(Configuration config); void terminate(); ServiceStatement[] get(); ServiceStatement get(ServiceElement sElem); void record(ServiceStatement statement); }### Answer:
@Test public void testGetActiveServiceStatements() throws Exception { ServiceStatement[] statements = serviceStatementManager.get(); List<ServiceRecord> list = new ArrayList<ServiceRecord>(); for (ServiceStatement statement : statements) { ServiceRecord[] records = statement.getServiceRecords(recordingUuid, ServiceRecord.ACTIVE_SERVICE_RECORD); list.addAll(Arrays.asList(records)); } Assert.assertEquals(names.length, list.size()); }
@Test public void testRecordAndRetrieve() throws Exception { Assert.assertEquals(statements.size(), serviceStatementManager.get().length); for(ServiceStatement statement : statements) { ServiceStatement s = serviceStatementManager.get(statement.getServiceElement()); Assert.assertEquals(statement, s); Assert.assertEquals(1, s.getServiceRecords(ServiceRecord.ACTIVE_SERVICE_RECORD).length); Assert.assertEquals(0, s.getServiceRecords(ServiceRecord.INACTIVE_SERVICE_RECORD).length); } } |
### Question:
SettingsUtil { public static String getLocalRepositoryLocation(final Settings settings) { if(settings==null) throw new IllegalArgumentException("settings must not be null"); String localRepositoryLocation = settings.getLocalRepository(); if (localRepositoryLocation == null) { StringBuilder locationBuilder = new StringBuilder(); locationBuilder.append(System.getProperty("user.home")).append(File.separator); locationBuilder.append(".m2").append(File.separator); locationBuilder.append("repository"); localRepositoryLocation = locationBuilder.toString(); } return localRepositoryLocation; } private SettingsUtil(); static Settings getSettings(); static String getLocalRepositoryLocation(final Settings settings); }### Answer:
@Test public void testGetLocalRepositoryLocation() throws Exception { Settings settings = SettingsUtil.getSettings(); String localRepositoryLocation = SettingsUtil.getLocalRepositoryLocation(settings); Assert.assertNotNull(localRepositoryLocation); } |
### Question:
LocalRepositoryWorkspaceReader implements WorkspaceReader { public LocalRepositoryWorkspaceReader() throws SettingsBuildingException { localRepositoryDir = SettingsUtil.getLocalRepositoryLocation(SettingsUtil.getSettings()); } LocalRepositoryWorkspaceReader(); WorkspaceRepository getRepository(); File findArtifact(Artifact artifact); List<String> findVersions(Artifact artifact); }### Answer:
@Test public void testLocalRepositoryWorkspaceReader() throws SettingsBuildingException { LocalRepositoryWorkspaceReader workspaceReader = new LocalRepositoryWorkspaceReader(); Artifact a = new DefaultArtifact("something.something:darkside-deathstar:pom:2.1"); String path = workspaceReader.getArtifactPath(a); System.out.println(path); assertEquals(getArtifactPath(a, workspaceReader), path); } |
### Question:
StagedData implements Serializable { public long getDownloadSize() throws IOException { getLocationURL(); return locationURL.openConnection().getContentLengthLong(); } long getDownloadSize(); URL getLocationURL(); String getLocation(); void setLocation(String location); String getInstallRoot(); void setInstallRoot(String installRoot); void setUnarchive(boolean unarchive); void setRemoveOnDestroy(boolean removeOnDestroy); void setOverwrite(boolean overwrite); void setPerms(String perms); boolean unarchive(); boolean removeOnDestroy(); boolean overwrite(); String getPerms(); String toString(); }### Answer:
@Test public void testGetDownloadSize() throws IOException { StagedData stagedData = new StagedData(); stagedData.setLocation("https: long size = stagedData.getDownloadSize(); assertTrue(size != -1); } |
### Question:
ServiceStatement implements Serializable { public String getOrganization() { String organization = sElem.getServiceBeanConfig().getOrganization(); organization = (organization==null ? "" : organization); return (organization); } ServiceStatement(final ServiceElement sElem); ServiceElement getServiceElement(); String getOrganization(); boolean hasActiveServiceRecords(); void putServiceRecord(final Uuid instantiatorID, final ServiceRecord record); ServiceRecord[] getServiceRecords(); ServiceRecord[] getServiceRecords(final int type); ServiceRecord[] getServiceRecords(final Uuid instantiatorID, final int type); ServiceRecord[] getServiceRecords(final Uuid sbid); ServiceRecord[] getServiceRecords(final Uuid sbid, final Uuid instantiatorID); }### Answer:
@Test public void testGetOrganization() { ServiceElement element = makeServiceElement("Foo"); Uuid uuid = UuidFactory.generate(); ServiceRecord record = new ServiceRecord(uuid, element, "hostname"); ServiceStatement statement = new ServiceStatement(element); statement.putServiceRecord(recordingUuid, record); String organization = statement.getOrganization(); Assert.assertNotNull(organization); } |
### Question:
JMXConnectionUtil { public static String getPlatformMBeanServerAgentId() throws Exception { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); final String SERVER_DELEGATE = "JMImplementation:type=MBeanServerDelegate"; final String MBEAN_SERVER_ID_KEY = "MBeanServerId"; ObjectName delegateObjName = new ObjectName(SERVER_DELEGATE); return (String) mbs.getAttribute(delegateObjName, MBEAN_SERVER_ID_KEY ); } static String getPlatformMBeanServerAgentId(); static MBeanServerConnection attach(final String id); }### Answer:
@Test public void testGetPlatformMBeanAgentID() throws Exception { String agentID = JMXConnectionUtil.getPlatformMBeanServerAgentId(); Assert.assertNotNull(agentID); } |
### Question:
OpStringLoader { public OpStringLoader() { this(null); } OpStringLoader(); OpStringLoader(ClassLoader loader); void setDefaultGroups(String... groups); OperationalString[] parseOperationalString(File file); OperationalString[] parseOperationalString(URL url); static final String DEFAULT_FDH; }### Answer:
@Test public void testOpStringLoader() throws Exception { OpStringLoader opStringLoader = new OpStringLoader(); opStringLoader.setDefaultGroups("banjo"); String baseDir = System.getProperty("user.dir"); File calculator = new File(baseDir, "src/test/resources/opstrings/opstringloadertest.groovy"); OperationalString[] opStrings = opStringLoader.parseOperationalString(calculator); Assert.assertNotNull(opStrings); Assert.assertEquals("Should have only 1 opstring", 1, opStrings.length); Assert.assertEquals("Should have 1 service", 1, opStrings[0].getServices().length); Assert.assertEquals(1, opStrings[0].getServices()[0].getServiceBeanConfig().getGroups().length); Assert.assertEquals("banjo", opStrings[0].getServices()[0].getServiceBeanConfig().getGroups()[0]); } |
### Question:
StopWatch extends ThresholdWatch implements StopWatchMBean { public void setElapsedTime(long elapsed) { setElapsedTime(elapsed, System.currentTimeMillis()); } StopWatch(String id); StopWatch(String id, Configuration config); @SuppressWarnings("unused") StopWatch(WatchDataSource watchDataSource, String id); void startTiming(); void stopTiming(); void stopTiming(String detail); void setElapsedTime(long elapsed); void setElapsedTime(long elapsed, String detail); void setElapsedTime(long elapsed, long now); void setElapsedTime(long elapsed, long now, String detail); long getStartTime(); void setStartTime(long startTime); static final String VIEW; }### Answer:
@Test public void testSetElapsedTime1() throws RemoteException { StopWatch watch = new StopWatch("watch"); List<Long> expected = new ArrayList<Long>(); checkData(expected, watch); for (int i = 0; i < 10; i++) { long value = Math.round(Math.random() * 100); watch.setElapsedTime(value); expected.add(value); checkData(expected, watch); } Utils.close(watch.getWatchDataSource()); }
@Test public void testSetElapsedTime2() throws RemoteException { StopWatch watch = new StopWatch("watch"); List<Long> expectedValues = new ArrayList<Long>(); List<Long> expectedStamps = new ArrayList<Long>(); checkData(expectedValues, expectedStamps, watch); for (int i = 0; i < 10; i++) { long value = Math.round(Math.random() * 100); long stamp = Math.round(Math.random() * 100); watch.setElapsedTime(value, stamp); expectedValues.add(value); expectedStamps.add(stamp); checkData(expectedValues, expectedStamps, watch); } Utils.close(watch.getWatchDataSource()); } |
### Question:
StopWatch extends ThresholdWatch implements StopWatchMBean { public void startTiming() { setStartTime(System.currentTimeMillis()); } StopWatch(String id); StopWatch(String id, Configuration config); @SuppressWarnings("unused") StopWatch(WatchDataSource watchDataSource, String id); void startTiming(); void stopTiming(); void stopTiming(String detail); void setElapsedTime(long elapsed); void setElapsedTime(long elapsed, String detail); void setElapsedTime(long elapsed, long now); void setElapsedTime(long elapsed, long now, String detail); long getStartTime(); void setStartTime(long startTime); static final String VIEW; }### Answer:
@Test public void testStartTiming() throws RemoteException { StopWatch watch = new StopWatch("watch"); Assert.assertEquals(0, watch.getStartTime()); long prevStartTime = -1; for (int i = 0; i < 10; i++) { Utils.sleep(100); watch.startTiming(); long startTime = watch.getStartTime(); Assert.assertTrue(startTime >= 0); if (prevStartTime != -1) { Assert.assertTrue(startTime > prevStartTime); } prevStartTime = startTime; } checkData(0, watch); for (int i = 0; i < 10; i++) { watch.startTiming(); Utils.sleep(100); watch.stopTiming(); checkData(i + 1, watch); } Utils.close(watch.getWatchDataSource()); } |
### Question:
StopWatch extends ThresholdWatch implements StopWatchMBean { public void stopTiming() { long now = System.currentTimeMillis(); long startTime = getStartTime(); long elapsed = now - startTime; setElapsedTime(elapsed, now); } StopWatch(String id); StopWatch(String id, Configuration config); @SuppressWarnings("unused") StopWatch(WatchDataSource watchDataSource, String id); void startTiming(); void stopTiming(); void stopTiming(String detail); void setElapsedTime(long elapsed); void setElapsedTime(long elapsed, String detail); void setElapsedTime(long elapsed, long now); void setElapsedTime(long elapsed, long now, String detail); long getStartTime(); void setStartTime(long startTime); static final String VIEW; }### Answer:
@Test public void testStopTiming() throws RemoteException { StopWatch watch = new StopWatch("watch"); DataSourceMonitor mon = new DataSourceMonitor(watch); checkData(0, watch); for (int i = 0; i < 10; i++) { Utils.sleep(100); watch.stopTiming(); mon.waitFor(i + 1); Calculable[] calcs = watch.getWatchDataSource().getCalculable(); Assert.assertEquals(i + 1, calcs.length); Assert.assertTrue(calcs[0].getValue() > 0); for (int j = 1; j < calcs.length; j++) { Assert.assertTrue(calcs[j].getValue() >= calcs[j - 1].getValue()); } } for (int i = 0; i < 10; i++) { watch.startTiming(); Utils.sleep(100); watch.stopTiming(); checkData(10 + i + 1, watch); } Utils.close(watch.getWatchDataSource()); } |
### Question:
Statistics { public void clearAll() { v.clear(); } Statistics(); Statistics(Iterable<Double> values); void clearAll(); int count(); double max(); double min(); double mean(); double median(); double mode(); int modeOccurrenceCount(); double range(); double standardDeviation(); Vector getValues(); void addValue(Double double1); void addValue(double d); void setValues(Iterable<Double> vals); void setValues(Calculable[] calcs); void removeValues(double d, boolean removeAll); void removeValues(Double double1, boolean removeAll); void removeValue(int location); void removeValues(Double low, Double high); void removeValues(double low, double high); double sum(); }### Answer:
@Test public void testClearAll() { Statistics stat = new Statistics(); for (int i = 0; i < 5; i++) { stat.clearAll(); assertClean(stat); } List<Double> list = new ArrayList<>(); list.add((double) 0); list.add((double) 1); list.add((double) 2); stat.setValues(list); assertCorrect(list, stat); for (int i = 0; i < 5; i++) { stat.clearAll(); assertClean(stat); } } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public String getID() { return (id); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetID() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); Assert.assertEquals("watch", impl.getID()); impl.setID("aaa"); Assert.assertEquals("aaa", impl.getID()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void setID(String id) { if(id==null) throw new IllegalArgumentException("id is null"); this.id = id; } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testSetID() throws Exception { WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("aaa"); Assert.assertEquals("aaa", impl.getID()); impl.setID(""); Assert.assertEquals("", impl.getID()); try { impl.setID("bbb"); impl.setID(null); Assert.fail("IllegalArgumentException expected but not thrown"); } catch (IllegalArgumentException e) { } Assert.assertEquals("bbb", impl.getID()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public void clear() { synchronized(history) { history.clear(); } } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testClear() throws Exception { final int DCS = WatchDataSourceImpl.DEFAULT_COLLECTION_SIZE; WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); for (int j = 0; j < DCS; j++) { impl.addCalculable(new Calculable()); } DataSourceMonitor mon = new DataSourceMonitor(impl); mon.waitFor(DCS); int expected = Math.min(DCS, DCS); Assert.assertEquals(expected, impl.getCalculable().length); impl.clear(); Assert.assertEquals(0, impl.getCalculable().length); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { public int getCurrentSize() { int size; synchronized(history) { size = history.size(); } return (size); } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testGetCurrentSize() throws Exception { final int DCS = WatchDataSourceImpl.DEFAULT_COLLECTION_SIZE; WatchDataSourceImpl impl = new WatchDataSourceImpl(); impl.setID("watch"); impl.setConfiguration(EmptyConfiguration.INSTANCE); for (int j = 0; j < DCS; j++) { impl.addCalculable(new Calculable()); } DataSourceMonitor mon = new DataSourceMonitor(impl); mon.waitFor(DCS); int expected = Math.min(DCS, DCS); Assert.assertEquals(expected, impl.getCurrentSize()); impl.close(); } |
### Question:
WatchDataSourceImpl implements WatchDataSource, ServerProxyTrust { @SuppressWarnings("unchecked") public void addCalculable(Calculable calculable) { if(calculable==null) throw new IllegalArgumentException("calculable is null"); if(!closed) { addToHistory(calculable); for(WatchDataReplicator replicator : getWatchDataReplicators()) { if(logger.isTraceEnabled()) logger.trace("Replicating [{}] to {} {}", calculable.toString(), replicator, replicator.getClass().getName()); replicator.addCalculable(calculable); } } } WatchDataSourceImpl(); WatchDataSourceImpl(String id, Configuration config); void initialize(); WatchDataSource export(); WatchDataSource getProxy(); void setConfiguration(Configuration config); void unexport(boolean force); String getID(); void setID(String id); void setMaxSize(int size); void clear(); int getMaxSize(); int getCurrentSize(); @SuppressWarnings("unchecked") void addCalculable(Calculable calculable); Calculable[] getCalculable(); Calculable[] getCalculable(String id); Calculable[] getCalculable(long from, long to); Calculable getLastCalculable(); ThresholdValues getThresholdValues(); void setThresholdValues(ThresholdValues tValues); void close(); void setView(String viewClass); String getView(); TrustVerifier getProxyVerifier(); boolean addWatchDataReplicator(WatchDataReplicator replicator); boolean removeWatchDataReplicator(WatchDataReplicator replicator); WatchDataReplicator[] getWatchDataReplicators(); final static int DEFAULT_COLLECTION_SIZE; final static int MAX_COLLECTION_SIZE; }### Answer:
@Test public void testAddCalculable() throws Exception { doTestAddCalculable(LoggingWatchDataReplicator.class.getName()); doTestAddCalculable(RemoteWDR.class.getName()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.