target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testWithInstanceCount() { final Deployment deploy = new Deployment(); deploy.withInstanceCount(3); assertEquals(3, (int) deploy.getInstanceCount()); } | public Deployment withInstanceCount(Integer instanceCount) { this.instanceCount = instanceCount; return this; } | Deployment { public Deployment withInstanceCount(Integer instanceCount) { this.instanceCount = instanceCount; return this; } } | Deployment { public Deployment withInstanceCount(Integer instanceCount) { this.instanceCount = instanceCount; return this; } } | Deployment { public Deployment withInstanceCount(Integer instanceCount) { this.instanceCount = instanceCount; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } | Deployment { public Deployment withInstanceCount(Integer instanceCount) { this.instanceCount = instanceCount; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } |
@Test public void testWithDeploymentName() { final Deployment deploy = new Deployment(); deploy.withDeploymentName("deploymentName1"); assertEquals("deploymentName1", deploy.getDeploymentName()); } | public Deployment withDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } | Deployment { public Deployment withDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } } | Deployment { public Deployment withDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } } | Deployment { public Deployment withDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } | Deployment { public Deployment withDeploymentName(String deploymentName) { this.deploymentName = deploymentName; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } |
@Test public void testWithJvmOptions() { final Deployment deploy = new Deployment(); deploy.withJvmOptions("jvmOptions1"); assertEquals("jvmOptions1", deploy.getJvmOptions()); } | public Deployment withJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; return this; } | Deployment { public Deployment withJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; return this; } } | Deployment { public Deployment withJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; return this; } } | Deployment { public Deployment withJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } | Deployment { public Deployment withJvmOptions(String jvmOptions) { this.jvmOptions = jvmOptions; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } |
@Test public void doExecute() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); doNothing().when(mojoSpy).checkStageDirectoryExistence(); doNothing().when(mojoSpy).checkRuntimeExistence(any(CommandHandler.class)); doNothing().when(mojoSpy).runFunctions(any(CommandHandler.class)); mojoSpy.doExecute(); verify(mojoSpy, times(1)).checkStageDirectoryExistence(); verify(mojoSpy, times(1)).checkRuntimeExistence(any(CommandHandler.class)); verify(mojoSpy, times(1)).runFunctions(any(CommandHandler.class)); } | @Override protected void doExecute() throws AzureExecutionException { final CommandHandler commandHandler = new CommandHandlerImpl(); checkStageDirectoryExistence(); checkRuntimeExistence(commandHandler); checkRuntimeCompatibility(commandHandler); runFunctions(commandHandler); } | RunMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { final CommandHandler commandHandler = new CommandHandlerImpl(); checkStageDirectoryExistence(); checkRuntimeExistence(commandHandler); checkRuntimeCompatibility(commandHandler); runFunctions(commandHandler); } } | RunMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { final CommandHandler commandHandler = new CommandHandlerImpl(); checkStageDirectoryExistence(); checkRuntimeExistence(commandHandler); checkRuntimeCompatibility(commandHandler); runFunctions(commandHandler); } } | RunMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { final CommandHandler commandHandler = new CommandHandlerImpl(); checkStageDirectoryExistence(); checkRuntimeExistence(commandHandler); checkRuntimeCompatibility(commandHandler); runFunctions(commandHandler); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | RunMojo extends AbstractFunctionMojo { @Override protected void doExecute() throws AzureExecutionException { final CommandHandler commandHandler = new CommandHandlerImpl(); checkStageDirectoryExistence(); checkRuntimeExistence(commandHandler); checkRuntimeCompatibility(commandHandler); runFunctions(commandHandler); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } |
@Test public void testWithEnvironment() { final Deployment deploy = new Deployment(); deploy.withEnvironment(Collections.singletonMap("foo", "bar")); assertEquals("bar", deploy.getEnvironment().get("foo")); } | public Deployment withEnvironment(Map<String, String> environment) { this.environment = environment; return this; } | Deployment { public Deployment withEnvironment(Map<String, String> environment) { this.environment = environment; return this; } } | Deployment { public Deployment withEnvironment(Map<String, String> environment) { this.environment = environment; return this; } } | Deployment { public Deployment withEnvironment(Map<String, String> environment) { this.environment = environment; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } | Deployment { public Deployment withEnvironment(Map<String, String> environment) { this.environment = environment; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } |
@Test public void testWithResources() { final Deployment deploy = new Deployment(); deploy.withResources(ResourcesUtils.getDefaultResources()); assertEquals(1, deploy.getResources().size()); assertEquals("*.jar", deploy.getResources().get(0).getIncludes().get(0)); } | public Deployment withResources(List<Resource> resources) { this.resources = resources; return this; } | Deployment { public Deployment withResources(List<Resource> resources) { this.resources = resources; return this; } } | Deployment { public Deployment withResources(List<Resource> resources) { this.resources = resources; return this; } } | Deployment { public Deployment withResources(List<Resource> resources) { this.resources = resources; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } | Deployment { public Deployment withResources(List<Resource> resources) { this.resources = resources; return this; } Integer getCpu(); Integer getMemoryInGB(); Integer getInstanceCount(); String getDeploymentName(); Map<String, String> getEnvironment(); List<Resource> getResources(); Boolean isEnablePersistentStorage(); String getJvmOptions(); String getRuntimeVersion(); Deployment withCpu(Integer cpu); Deployment withMemoryInGB(Integer memoryInGB); Deployment withInstanceCount(Integer instanceCount); Deployment withJvmOptions(String jvmOptions); Deployment withEnvironment(Map<String, String> environment); Deployment withDeploymentName(String deploymentName); Deployment withResources(List<Resource> resources); Deployment withEnablePersistentStorage(Boolean enablePersistentStorage); Deployment withRuntimeVersion(String runtimeVersion); } |
@Test public void testSetSubscriptionId() { final AppSettings app = new AppSettings(); app.setSubscriptionId("subscriptionId1"); assertEquals("subscriptionId1", app.getSubscriptionId()); } | public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } | AppSettings extends BaseSettings { public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } } | AppSettings extends BaseSettings { public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } } | AppSettings extends BaseSettings { public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); } | AppSettings extends BaseSettings { public void setSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); } |
@Test public void testSetClusterName() { final AppSettings app = new AppSettings(); app.setClusterName("clusterName1"); assertEquals("clusterName1", app.getClusterName()); } | public void setClusterName(String clusterName) { this.clusterName = clusterName; } | AppSettings extends BaseSettings { public void setClusterName(String clusterName) { this.clusterName = clusterName; } } | AppSettings extends BaseSettings { public void setClusterName(String clusterName) { this.clusterName = clusterName; } } | AppSettings extends BaseSettings { public void setClusterName(String clusterName) { this.clusterName = clusterName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); } | AppSettings extends BaseSettings { public void setClusterName(String clusterName) { this.clusterName = clusterName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); } |
@Test public void testSetAppName() { final AppSettings app = new AppSettings(); app.setAppName("appName1"); assertEquals("appName1", app.getAppName()); } | public void setAppName(String appName) { this.appName = appName; } | AppSettings extends BaseSettings { public void setAppName(String appName) { this.appName = appName; } } | AppSettings extends BaseSettings { public void setAppName(String appName) { this.appName = appName; } } | AppSettings extends BaseSettings { public void setAppName(String appName) { this.appName = appName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); } | AppSettings extends BaseSettings { public void setAppName(String appName) { this.appName = appName; } String getSubscriptionId(); void setSubscriptionId(String subscriptionId); String getClusterName(); void setClusterName(String clusterName); String getAppName(); void setAppName(String appName); String isPublic(); void setPublic(String isPublic); } |
@Test public void testHandle() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "defaultValueForUnitTest"), new DefaultMapEntry<>("property", "appName"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); wrapper.putCommonVariable("global_property1", "value1"); when(reader.readLine()).thenReturn(""); String result = wrapper.handle("testId1", false); assertEquals("defaultValueForUnitTest", result); when(reader.readLine()).thenReturn("abcd"); result = wrapper.handle("testId1", false); assertEquals("abcd", result); when(reader.readLine()).thenReturn("^^&$").thenReturn("wxyz"); result = wrapper.handle("testId1", false, null); assertEquals("wxyz", result); when(reader.readLine()).thenReturn("${expr}"); when(mockEval.evaluate("${expr}")).thenReturn("evaluated"); result = wrapper.handle("testId1", false); assertEquals("${expr}", result); when(reader.readLine()).thenReturn("${expr1}").thenReturn("${expr").thenReturn("${expr}"); when(mockEval.evaluate("${expr}")).thenReturn("evaluated"); when(mockEval.evaluate("${expr1}")).thenReturn("evaluated~!!"); when(mockEval.evaluate("${expr")).thenThrow(new ExpressionEvaluationException("bad expr")); result = wrapper.handle("testId1", false); assertEquals("${expr}", result); } | public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testEvaluateDefault() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "${public}"), new DefaultMapEntry<>("property", "isPublic"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); when(mockEval.evaluate("${public}")).thenReturn("true"); when(reader.readLine()).thenReturn(""); assertEquals("${public}", wrapper.handle("testId1", false)); } | public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testBadTemplate() throws Exception { try { wrapper.handle("", true); fail("Should report IAE when template cannot be found."); } catch (IllegalArgumentException e) { } try { wrapper.handle("badId", true); fail("Should report IAE when template cannot be found."); } catch (IllegalArgumentException e) { } final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("resource", "ResourceNotFound"), new DefaultMapEntry<>("property", "cpu"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); try { wrapper.handle("testId1", true); fail("Should report IAE when resource cannot be found."); } catch (IllegalArgumentException e) { } map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("property", "cpu2"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); try { wrapper.handle("testId1", true); fail("Should report IAE when property cannot be found."); } catch (IllegalArgumentException e) { } } | public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testHandleBadConfiguration() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("default", "false"), new DefaultMapEntry<>("required", false), }); templates.put("testId1", map); map.put("property", ""); try { wrapper.handle("testId1", true, "foo"); fail("Should throw InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { } map.put("property", "appName"); try { wrapper.handle("testId1", true, "foo"); fail("Should throw InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { } map.put("resource", ""); try { wrapper.handle("testId1", true, "foo"); fail("Should throw InvalidConfigurationException"); } catch (InvalidConfigurationException ex) { } map.put("resource", "App"); wrapper.handle("testId1", true, "foo"); } | public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public String handle(String templateId, boolean autoApplyDefault) throws InvalidConfigurationException, IOException { return handle(templateId, autoApplyDefault, null); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test public void testHandleSelectOne() throws Exception { final Map<String, Map<String, Object>> templates = (Map<String, Map<String, Object>>) FieldUtils.readField(wrapper, "templates", true); final Map<String, Object> map = MapUtils.putAll(new LinkedHashMap<>(), new Map.Entry[] { new DefaultMapEntry<>("id", "testId1"), new DefaultMapEntry<>("promote", "Input the {{global_property1}} value(***{{default}}***):"), new DefaultMapEntry<>("resource", "App"), new DefaultMapEntry<>("default", "false"), new DefaultMapEntry<>("property", "isPublic"), new DefaultMapEntry<>("required", true), }); templates.put("testId1", map); when(reader.readLine()).thenReturn(""); String result = wrapper.handleSelectOne("testId1", Arrays.asList("foo", "bar"), "foo", String::toString); assertEquals("foo", result); map.put("required", false); result = wrapper.handleSelectOne("testId1", Arrays.asList("foo", "bar"), null, String::toString); assertNull(result); map.put("required", true); when(reader.readLine()).thenReturn("").thenReturn("1").thenReturn("2").thenReturn("3").thenReturn("2"); result = wrapper.handleSelectOne("testId1", Arrays.asList("foo", "bar"), null, String::toString); assertEquals("foo", result); result = wrapper.handleSelectOne("testId1", Arrays.asList("foo", "bar"), null, String::toString); assertEquals("bar", result); result = wrapper.handleSelectOne("testId1", Arrays.asList("foo", "bar"), null, String::toString); assertEquals("bar", result); map.put("required", true); map.put("message", Collections.singletonMap("empty_options", "Option is empty")); try { wrapper.handleSelectOne("testId1", Collections.emptyList(), null, String::toString); fail("Should report error when required resources are not available."); } catch (NoResourcesAvailableException ex) { } map.put("required", false); assertNull(wrapper.handleSelectOne("testId1", Collections.emptyList(), null, String::toString)); map.put("auto_select", true); result = wrapper.handleSelectOne("testId1", Collections.singletonList("foo"), null, String::toString); assertEquals("foo", result); } | public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } | PromptWrapper { public <T> T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc) throws IOException, SpringConfigurationException { final Map<String, Object> variables = createVariableTables(templateId); final boolean isRequired = TemplateUtils.evalBoolean("required", variables); if (options.size() == 0) { if (isRequired) { throw new NoResourcesAvailableException(TemplateUtils.evalText("message.empty_options", variables)); } final String warningMessage = TemplateUtils.evalText("message.empty_options", variables); if (StringUtils.isNotBlank(warningMessage)) { log.warn(warningMessage); } return null; } final boolean autoSelect = TemplateUtils.evalBoolean("auto_select", variables); if (options.size() == 1) { if (autoSelect) { log.info(TemplateUtils.evalText("message.auto_select", variables)); return options.get(0); } if (!this.prompt.promoteYesNo(TemplateUtils.evalText("promote.one", variables), isRequired, isRequired)) { if (isRequired) { throw new SpringConfigurationException(TemplateUtils.evalText("message.select_none", variables)); } return null; } return options.get(0); } if (defaultEntity == null && variables.containsKey("default_index")) { defaultEntity = options.get((Integer) variables.get("default_index")); } return prompt.promoteSingleEntity(TemplateUtils.evalText("promote.header", variables), TemplateUtils.evalText("promote.many", variables), options, defaultEntity, getNameFunc, isRequired); } PromptWrapper(ExpressionEvaluator expressionEvaluator, Log log); void initialize(); void putCommonVariable(String key, Object obj); T handleSelectOne(String templateId, List<T> options, T defaultEntity, Function<T, String> getNameFunc); List<T> handleMultipleCase(String templateId, List<T> options, Function<T, String> getNameFunc); String handle(String templateId, boolean autoApplyDefault); String handle(String templateId, boolean autoApplyDefault, Object cliParameter); void confirmChanges(Map<String, String> changesToConfirm, Supplier<Integer> confirmedAction); void close(); } |
@Test(expected = AzureExecutionException.class) public void checkStageDirectoryExistenceWhenIsNotDirectory() throws Exception { final RunMojo mojo = getMojoFromPom(); final RunMojo mojoSpy = spy(mojo); doReturn("./RunMojoTest.java").when(mojoSpy).getDeploymentStagingDirectoryPath(); mojoSpy.checkStageDirectoryExistence(); } | protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } | RunMojo extends AbstractFunctionMojo { protected void checkStageDirectoryExistence() throws AzureExecutionException { final File file = new File(getDeploymentStagingDirectoryPath()); if (!file.exists() || !file.isDirectory()) { throw new AzureExecutionException(STAGE_DIR_NOT_FOUND); } Log.info(STAGE_DIR_FOUND + getDeploymentStagingDirectoryPath()); } String getLocalDebugConfig(); void setLocalDebugConfig(String localDebugConfig); } |
@Test public void testRead_errors () { assertThrows(IllegalStateException.class, () -> RequestParams.builder(resource).value("x")); } | public static Builder builder (String resource) { return new Builder(resource); } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams(
String resource,
String primaryKey,
String primaryKeyValue,
String column,
String columnValue,
String query,
List<NameValuePair> queryArgs,
List<NameValuePair> insert,
List<NameValuePair> update,
Integer page,
Integer limit,
Integer offset,
String sort,
String direction); } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams(
String resource,
String primaryKey,
String primaryKeyValue,
String column,
String columnValue,
String query,
List<NameValuePair> queryArgs,
List<NameValuePair> insert,
List<NameValuePair> update,
Integer page,
Integer limit,
Integer offset,
String sort,
String direction); static Builder builder(String resource); String getPath(final String root, final String alias); NameValuePair[] getParameters(); String getParametersAsQueryParams(); UrlEncodedFormEntity getFormBody(); StringEntity getJSONBody(); String toJSON(final List<NameValuePair> params); String getColumn(); String getColumnValue(); String getResource(); String getPrimaryKey(); String getPrimaryKeyValue(); Integer getPage(); Integer getLimit(); Integer getOffset(); String getSort(); String getDirection(); String getQuery(); List<NameValuePair> getQueryArgs(); List<NameValuePair> getInsert(); List<NameValuePair> getUpdate(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams(
String resource,
String primaryKey,
String primaryKeyValue,
String column,
String columnValue,
String query,
List<NameValuePair> queryArgs,
List<NameValuePair> insert,
List<NameValuePair> update,
Integer page,
Integer limit,
Integer offset,
String sort,
String direction); static Builder builder(String resource); String getPath(final String root, final String alias); NameValuePair[] getParameters(); String getParametersAsQueryParams(); UrlEncodedFormEntity getFormBody(); StringEntity getJSONBody(); String toJSON(final List<NameValuePair> params); String getColumn(); String getColumnValue(); String getResource(); String getPrimaryKey(); String getPrimaryKeyValue(); Integer getPage(); Integer getLimit(); Integer getOffset(); String getSort(); String getDirection(); String getQuery(); List<NameValuePair> getQueryArgs(); List<NameValuePair> getInsert(); List<NameValuePair> getUpdate(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void testDynamicQuery_errors () { assertThrows(IllegalArgumentException.class, () -> RequestParams.builder(resource).dynamicQuery("invalid")); assertThrows(IllegalArgumentException.class, () -> RequestParams.builder(resource).dynamicQuery("Find")); assertThrows(IllegalStateException.class, () -> RequestParams.builder(resource).addQueryParam("bar")); } | public static Builder builder (String resource) { return new Builder(resource); } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams(
String resource,
String primaryKey,
String primaryKeyValue,
String column,
String columnValue,
String query,
List<NameValuePair> queryArgs,
List<NameValuePair> insert,
List<NameValuePair> update,
Integer page,
Integer limit,
Integer offset,
String sort,
String direction); } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams(
String resource,
String primaryKey,
String primaryKeyValue,
String column,
String columnValue,
String query,
List<NameValuePair> queryArgs,
List<NameValuePair> insert,
List<NameValuePair> update,
Integer page,
Integer limit,
Integer offset,
String sort,
String direction); static Builder builder(String resource); String getPath(final String root, final String alias); NameValuePair[] getParameters(); String getParametersAsQueryParams(); UrlEncodedFormEntity getFormBody(); StringEntity getJSONBody(); String toJSON(final List<NameValuePair> params); String getColumn(); String getColumnValue(); String getResource(); String getPrimaryKey(); String getPrimaryKeyValue(); Integer getPage(); Integer getLimit(); Integer getOffset(); String getSort(); String getDirection(); String getQuery(); List<NameValuePair> getQueryArgs(); List<NameValuePair> getInsert(); List<NameValuePair> getUpdate(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } | RequestParams { public static Builder builder (String resource) { return new Builder(resource); } RequestParams(
String resource,
String primaryKey,
String primaryKeyValue,
String column,
String columnValue,
String query,
List<NameValuePair> queryArgs,
List<NameValuePair> insert,
List<NameValuePair> update,
Integer page,
Integer limit,
Integer offset,
String sort,
String direction); static Builder builder(String resource); String getPath(final String root, final String alias); NameValuePair[] getParameters(); String getParametersAsQueryParams(); UrlEncodedFormEntity getFormBody(); StringEntity getJSONBody(); String toJSON(final List<NameValuePair> params); String getColumn(); String getColumnValue(); String getResource(); String getPrimaryKey(); String getPrimaryKeyValue(); Integer getPage(); Integer getLimit(); Integer getOffset(); String getSort(); String getDirection(); String getQuery(); List<NameValuePair> getQueryArgs(); List<NameValuePair> getInsert(); List<NameValuePair> getUpdate(); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); } |
@Test public void buildsPngImage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(new URN(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkFriend(base).act( new RqRegex.Fake( new RqWithAuth(urn), "(.*)", alias ) ) ), Matchers.notNullValue() ); } | @Override public Response act(final RqRegex req) throws IOException { final User user = new RqAlias(this.base, req).user(); final String alias = req.matcher().group(1); final Iterable<Friend> opts = user.friends(alias); if (Iterables.isEmpty(opts)) { throw new RsFailure( String.format("alias \"%s\" not found", alias) ); } final Friend friend = opts.iterator().next(); if (!friend.alias().equals(alias)) { throw new RsFailure( String.format("alias \"%s\" is not found", alias) ); } final byte[] img = new JdkRequest(friend.photo()) .through(AutoRedirectingWire.class) .through(RetryWire.class) .through(OneMinuteWire.class) .header(HttpHeaders.ACCEPT, "image/*") .header(HttpHeaders.USER_AGENT, "Netbout.com") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .binary(); BufferedImage image = ImageIO.read(new ByteArrayInputStream(img)); if (image == null) { image = ImageIO.read(new URL("http: } final Image thumb = image.getScaledInstance( Tv.HUNDRED, -1, Image.SCALE_SMOOTH ); final BufferedImage bthumb = new BufferedImage( thumb.getWidth(null), thumb.getHeight(null), BufferedImage.TYPE_INT_RGB ); bthumb.getGraphics().drawImage(thumb, 0, 0, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bthumb, "png", baos); return new RsFluent() .withType("image/png") .withHeader( "Cache-Control", String.format( "private, max-age=%d", TimeUnit.DAYS.toSeconds(1L) ) ) .withBody(new ByteArrayInputStream(baos.toByteArray())); } | TkFriend implements TkRegex { @Override public Response act(final RqRegex req) throws IOException { final User user = new RqAlias(this.base, req).user(); final String alias = req.matcher().group(1); final Iterable<Friend> opts = user.friends(alias); if (Iterables.isEmpty(opts)) { throw new RsFailure( String.format("alias \"%s\" not found", alias) ); } final Friend friend = opts.iterator().next(); if (!friend.alias().equals(alias)) { throw new RsFailure( String.format("alias \"%s\" is not found", alias) ); } final byte[] img = new JdkRequest(friend.photo()) .through(AutoRedirectingWire.class) .through(RetryWire.class) .through(OneMinuteWire.class) .header(HttpHeaders.ACCEPT, "image/*") .header(HttpHeaders.USER_AGENT, "Netbout.com") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .binary(); BufferedImage image = ImageIO.read(new ByteArrayInputStream(img)); if (image == null) { image = ImageIO.read(new URL("http: } final Image thumb = image.getScaledInstance( Tv.HUNDRED, -1, Image.SCALE_SMOOTH ); final BufferedImage bthumb = new BufferedImage( thumb.getWidth(null), thumb.getHeight(null), BufferedImage.TYPE_INT_RGB ); bthumb.getGraphics().drawImage(thumb, 0, 0, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bthumb, "png", baos); return new RsFluent() .withType("image/png") .withHeader( "Cache-Control", String.format( "private, max-age=%d", TimeUnit.DAYS.toSeconds(1L) ) ) .withBody(new ByteArrayInputStream(baos.toByteArray())); } } | TkFriend implements TkRegex { @Override public Response act(final RqRegex req) throws IOException { final User user = new RqAlias(this.base, req).user(); final String alias = req.matcher().group(1); final Iterable<Friend> opts = user.friends(alias); if (Iterables.isEmpty(opts)) { throw new RsFailure( String.format("alias \"%s\" not found", alias) ); } final Friend friend = opts.iterator().next(); if (!friend.alias().equals(alias)) { throw new RsFailure( String.format("alias \"%s\" is not found", alias) ); } final byte[] img = new JdkRequest(friend.photo()) .through(AutoRedirectingWire.class) .through(RetryWire.class) .through(OneMinuteWire.class) .header(HttpHeaders.ACCEPT, "image/*") .header(HttpHeaders.USER_AGENT, "Netbout.com") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .binary(); BufferedImage image = ImageIO.read(new ByteArrayInputStream(img)); if (image == null) { image = ImageIO.read(new URL("http: } final Image thumb = image.getScaledInstance( Tv.HUNDRED, -1, Image.SCALE_SMOOTH ); final BufferedImage bthumb = new BufferedImage( thumb.getWidth(null), thumb.getHeight(null), BufferedImage.TYPE_INT_RGB ); bthumb.getGraphics().drawImage(thumb, 0, 0, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bthumb, "png", baos); return new RsFluent() .withType("image/png") .withHeader( "Cache-Control", String.format( "private, max-age=%d", TimeUnit.DAYS.toSeconds(1L) ) ) .withBody(new ByteArrayInputStream(baos.toByteArray())); } TkFriend(final Base bse); } | TkFriend implements TkRegex { @Override public Response act(final RqRegex req) throws IOException { final User user = new RqAlias(this.base, req).user(); final String alias = req.matcher().group(1); final Iterable<Friend> opts = user.friends(alias); if (Iterables.isEmpty(opts)) { throw new RsFailure( String.format("alias \"%s\" not found", alias) ); } final Friend friend = opts.iterator().next(); if (!friend.alias().equals(alias)) { throw new RsFailure( String.format("alias \"%s\" is not found", alias) ); } final byte[] img = new JdkRequest(friend.photo()) .through(AutoRedirectingWire.class) .through(RetryWire.class) .through(OneMinuteWire.class) .header(HttpHeaders.ACCEPT, "image/*") .header(HttpHeaders.USER_AGENT, "Netbout.com") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .binary(); BufferedImage image = ImageIO.read(new ByteArrayInputStream(img)); if (image == null) { image = ImageIO.read(new URL("http: } final Image thumb = image.getScaledInstance( Tv.HUNDRED, -1, Image.SCALE_SMOOTH ); final BufferedImage bthumb = new BufferedImage( thumb.getWidth(null), thumb.getHeight(null), BufferedImage.TYPE_INT_RGB ); bthumb.getGraphics().drawImage(thumb, 0, 0, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bthumb, "png", baos); return new RsFluent() .withType("image/png") .withHeader( "Cache-Control", String.format( "private, max-age=%d", TimeUnit.DAYS.toSeconds(1L) ) ) .withBody(new ByteArrayInputStream(baos.toByteArray())); } TkFriend(final Base bse); @Override Response act(final RqRegex req); } | TkFriend implements TkRegex { @Override public Response act(final RqRegex req) throws IOException { final User user = new RqAlias(this.base, req).user(); final String alias = req.matcher().group(1); final Iterable<Friend> opts = user.friends(alias); if (Iterables.isEmpty(opts)) { throw new RsFailure( String.format("alias \"%s\" not found", alias) ); } final Friend friend = opts.iterator().next(); if (!friend.alias().equals(alias)) { throw new RsFailure( String.format("alias \"%s\" is not found", alias) ); } final byte[] img = new JdkRequest(friend.photo()) .through(AutoRedirectingWire.class) .through(RetryWire.class) .through(OneMinuteWire.class) .header(HttpHeaders.ACCEPT, "image/*") .header(HttpHeaders.USER_AGENT, "Netbout.com") .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .binary(); BufferedImage image = ImageIO.read(new ByteArrayInputStream(img)); if (image == null) { image = ImageIO.read(new URL("http: } final Image thumb = image.getScaledInstance( Tv.HUNDRED, -1, Image.SCALE_SMOOTH ); final BufferedImage bthumb = new BufferedImage( thumb.getWidth(null), thumb.getHeight(null), BufferedImage.TYPE_INT_RGB ); bthumb.getGraphics().drawImage(thumb, 0, 0, null); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bthumb, "png", baos); return new RsFluent() .withType("image/png") .withHeader( "Cache-Control", String.format( "private, max-age=%d", TimeUnit.DAYS.toSeconds(1L) ) ) .withBody(new ByteArrayInputStream(baos.toByteArray())); } TkFriend(final Base bse); @Override Response act(final RqRegex req); } |
@Test public void formatsTextToHtml() throws Exception { final String meta = new MarkdownTxtmark().html( Joiner.on(MarkdownTxtmarkTest.EOL).join( "**hi**, _dude_!\r", "", " b**o", " ", " ", " o**m", "" ) ); MatcherAssert.assertThat( String.format("<x>%s</x>", meta), Matchers.describedAs( meta, XhtmlMatchers.hasXPaths( "/x/p/strong[.='hi']", "/x/p/em[.='dude']", Joiner.on(MarkdownTxtmarkTest.EOL).join( "/x/pre/code[.=' b**o", "", "", "o**m", "']" ) ) ) ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void handlesBrokenFormattingGracefully() throws Exception { final String[] texts = { Joiner.on(MarkdownTxtmarkTest.EOL).join("**", ""), "__", "", "**hi there! {{{", Joiner.on(MarkdownTxtmarkTest.EOL).join( " ", " ", " ", " ", "" ), }; for (final String text : texts) { MatcherAssert.assertThat( String.format("<z>%s</z>", new MarkdownTxtmark().html(text)), XhtmlMatchers.hasXPath("/z") ); } } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void handlesReferenceLinks() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "Reference-style: \n![alt text][logo]\n\n[logo]: https: ), Matchers.equalTo( "<p>Reference-style:<br />\n<img src=\"https: ) ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void handlesScriptViolation() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "<script>alert()</script>" ), Matchers.equalTo( "<p><script>alert()</script></p>\n" ) ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void formatsTextFragmentsToHtml() throws Exception { final String[][] texts = { new String[] {"hi, *dude*!", "<p>hi, <em>dude</em>!</p>"}, new String[] { "hello, **dude**!", "<p>hello, <strong>dude</strong>!</p>", }, new String[] { "wazzup, ***dude***!", "<p>wazzup, <strong><em>dude</em></strong>!</p>", }, new String[] { "hey, _man_!", "<p>hey, <em>man</em>!</p>", }, new String[] { "x: `oops`", "<p>x: <code>oops</code></p>", }, new String[] { "[a](http: "<p><a href=\"http: }, new String[] {"}}}", "<p>}}}</p>"}, }; for (final String[] pair : texts) { MatcherAssert.assertThat( new MarkdownTxtmark().html(pair[0]).trim(), Matchers.equalTo(pair[1]) ); } } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void formatsCodeFragmentsToHtml() throws Exception { final String[][] texts = { new String[] { "```\ncode\nanother line of code\n```", "<p><pre><code>code\nanother line of code</code></pre></p>", }, new String[] { "``code span not block\nextra line``", "<p><code>code span not block\nextra line</code></p>", }, new String[] { "`single char\nextra line with eol\n`", "<p><code>single char\nextra line with eol\n</code></p>", }, }; for (final String[] pair : texts) { MatcherAssert.assertThat( new MarkdownTxtmark().html(pair[0]).trim(), Matchers.equalTo(pair[1]) ); } } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void formatsBulletsToHtml() throws Exception { final String meta = new MarkdownTxtmark().html( Joiner.on(MarkdownTxtmarkTest.EOL).join( "my list:", "", "* line one", "* line two", "", "normal text now" ) ); MatcherAssert.assertThat( String.format("<r>%s</r>", meta), Matchers.describedAs( meta, XhtmlMatchers.hasXPaths( "/r/p[text()='my list:']", "/r/ul[count(li) = 2]", "/r/ul/li[text()='line one']", "/r/ul/li[text()='line two']", "/r/p[.='normal text now']" ) ) ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void breaksSingleLine() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( Joiner.on(MarkdownTxtmarkTest.EOL) .join("line1 line", "line2", "", "line3").trim() ), Matchers.equalTo( Joiner.on(MarkdownTxtmarkTest.EOL).join( "<p>line1 line<br />", "line2<br /></p>", "<p>line3</p>", "" ) ) ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void leavesDivUntouched() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html("<div>hey<svg viewBox='444'/></div>"), XhtmlMatchers.hasXPaths( "/div/svg[@viewBox]" ) ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void detectsLinks() throws Exception { final String[][] texts = { new String[] { "<a href=\"http: "<p><a href=\"http: }, new String[] { "http: "<p><a href=\"http: }, new String[]{ "(http: "<p>(<a href=\"http: }, new String[] { "(http: "<p>(<a href=\"http: }, new String[] { "(https: "<p>(<a href=\"https: }, new String[] { "[foo](http: "<p><a href=\"http: }, new String[] { "[http: "<p><a href=\"http: }, new String[] { "[http: "<p>[<a href=\"http: }, new String[] { "[google](http: "<p><a href=\"http: }, new String[] { Joiner.on(MarkdownTxtmarkTest.EOL).join( "http: "http: ), Joiner.on(MarkdownTxtmarkTest.EOL).join( "<p><a href=\"http: "<a href=\"http: ), }, new String[] { "![logo] (http: "<p><img src=\"http: }, new String[] { " { MatcherAssert.assertThat( new MarkdownTxtmark().html(pair[0]).trim(), Matchers.equalTo(pair[1]) ); } } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void rendersPage() throws Exception { final Base base = new MkBase(); final String alias = "test"; final String urn = "urn:test:1"; base.user(URN.create(urn)).aliases().add(alias); MatcherAssert.assertThat( new RsPrint( new TkIndex(base).act(new RqWithAuth(urn)) ).printBody(), XhtmlMatchers.hasXPaths( "/page/alias/email", "/page/links/link[@rel='save-email']/@href" ) ); } | @Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); } | TkIndex implements Take { @Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); } } | TkIndex implements Take { @Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); } TkIndex(final Base bse); } | TkIndex implements Take { @Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); } TkIndex(final Base bse); @Override Response act(final Request req); } | TkIndex implements Take { @Override public Response act(final Request req) throws IOException { return new RsPage( "/xsl/account.xsl", this.base, new RqWithDefaultHeader(req, HttpHeaders.ACCEPT, "text/xml"), new XeLink("save-email", "/acc/save") ); } TkIndex(final Base bse); @Override Response act(final Request req); } |
@Test public void escapesReplacement() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html("backslash \\ and group reference $3\n"), Matchers.is("<p>backslash \\ and group reference $3<br /></p>\n") ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void returnsSecondIdentity() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(true), new PsLogout() ).enter(new RqFake()).get(), Matchers.is(Identity.ANONYMOUS) ); } | @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response,
final Identity identity); } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response,
final Identity identity); } |
@Test public void returnsEmptyIdentity() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(false), new PsLogout() ).enter(new RqFake()).has(), Matchers.equalTo(false) ); } | @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response,
final Identity identity); } | PsTwice implements Pass { @Override public Opt<Identity> enter(final Request req) throws IOException { Opt<Identity> user = new Opt.Empty<>(); if (this.fst.enter(req).has()) { user = this.snd.enter(req); } return user; } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response,
final Identity identity); } |
@Test public void returnsCorrectResponseOnExit() throws Exception { MatcherAssert.assertThat( new PsTwice( new PsFake(true), new PsLogout() ).exit(new RsEmpty(), Identity.ANONYMOUS) .head().iterator().next(), Matchers.containsString("HTTP/1.1 200 O") ); } | @Override public Response exit(final Response response, final Identity identity) throws IOException { return this.snd.exit(response, identity); } | PsTwice implements Pass { @Override public Response exit(final Response response, final Identity identity) throws IOException { return this.snd.exit(response, identity); } } | PsTwice implements Pass { @Override public Response exit(final Response response, final Identity identity) throws IOException { return this.snd.exit(response, identity); } PsTwice(final Pass first, final Pass second); } | PsTwice implements Pass { @Override public Response exit(final Response response, final Identity identity) throws IOException { return this.snd.exit(response, identity); } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response,
final Identity identity); } | PsTwice implements Pass { @Override public Response exit(final Response response, final Identity identity) throws IOException { return this.snd.exit(response, identity); } PsTwice(final Pass first, final Pass second); @Override Opt<Identity> enter(final Request req); @Override Response exit(final Response response,
final Identity identity); } |
@Test public void buildsGifImage() throws Exception { MatcherAssert.assertThat( new RsPrint( new TkFavicon().act(new RqFake("GET", "/?unread=44")) ).printBody(), Matchers.notNullValue() ); } | @Override public Response act(final Request req) throws IOException { final long unread = TkFavicon.unread(req); final int width = 64; final int height = 64; final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); final Graphics graph = image.getGraphics(); graph.setColor(new Color(0x4b, 0x42, 0x50)); graph.fillRect(0, 0, width, height); if (unread > 0L) { final String text; if (unread >= (long) Tv.HUNDRED) { text = "99"; } else { text = Long.toString(unread); } graph.setColor(Color.WHITE); graph.setFont(new Font(Font.SANS_SERIF, Font.BOLD, height / 2)); graph.drawString( text, width - width / Tv.TEN - graph.getFontMetrics().stringWidth(text), height - height / Tv.TEN ); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "gif", baos); return new RsWithType( new RsWithBody(baos.toByteArray()), "image/gif" ); } | TkFavicon implements Take { @Override public Response act(final Request req) throws IOException { final long unread = TkFavicon.unread(req); final int width = 64; final int height = 64; final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); final Graphics graph = image.getGraphics(); graph.setColor(new Color(0x4b, 0x42, 0x50)); graph.fillRect(0, 0, width, height); if (unread > 0L) { final String text; if (unread >= (long) Tv.HUNDRED) { text = "99"; } else { text = Long.toString(unread); } graph.setColor(Color.WHITE); graph.setFont(new Font(Font.SANS_SERIF, Font.BOLD, height / 2)); graph.drawString( text, width - width / Tv.TEN - graph.getFontMetrics().stringWidth(text), height - height / Tv.TEN ); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "gif", baos); return new RsWithType( new RsWithBody(baos.toByteArray()), "image/gif" ); } } | TkFavicon implements Take { @Override public Response act(final Request req) throws IOException { final long unread = TkFavicon.unread(req); final int width = 64; final int height = 64; final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); final Graphics graph = image.getGraphics(); graph.setColor(new Color(0x4b, 0x42, 0x50)); graph.fillRect(0, 0, width, height); if (unread > 0L) { final String text; if (unread >= (long) Tv.HUNDRED) { text = "99"; } else { text = Long.toString(unread); } graph.setColor(Color.WHITE); graph.setFont(new Font(Font.SANS_SERIF, Font.BOLD, height / 2)); graph.drawString( text, width - width / Tv.TEN - graph.getFontMetrics().stringWidth(text), height - height / Tv.TEN ); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "gif", baos); return new RsWithType( new RsWithBody(baos.toByteArray()), "image/gif" ); } } | TkFavicon implements Take { @Override public Response act(final Request req) throws IOException { final long unread = TkFavicon.unread(req); final int width = 64; final int height = 64; final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); final Graphics graph = image.getGraphics(); graph.setColor(new Color(0x4b, 0x42, 0x50)); graph.fillRect(0, 0, width, height); if (unread > 0L) { final String text; if (unread >= (long) Tv.HUNDRED) { text = "99"; } else { text = Long.toString(unread); } graph.setColor(Color.WHITE); graph.setFont(new Font(Font.SANS_SERIF, Font.BOLD, height / 2)); graph.drawString( text, width - width / Tv.TEN - graph.getFontMetrics().stringWidth(text), height - height / Tv.TEN ); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "gif", baos); return new RsWithType( new RsWithBody(baos.toByteArray()), "image/gif" ); } @Override Response act(final Request req); } | TkFavicon implements Take { @Override public Response act(final Request req) throws IOException { final long unread = TkFavicon.unread(req); final int width = 64; final int height = 64; final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB ); final Graphics graph = image.getGraphics(); graph.setColor(new Color(0x4b, 0x42, 0x50)); graph.fillRect(0, 0, width, height); if (unread > 0L) { final String text; if (unread >= (long) Tv.HUNDRED) { text = "99"; } else { text = Long.toString(unread); } graph.setColor(Color.WHITE); graph.setFont(new Font(Font.SANS_SERIF, Font.BOLD, height / 2)); graph.drawString( text, width - width / Tv.TEN - graph.getFontMetrics().stringWidth(text), height - height / Tv.TEN ); } final ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "gif", baos); return new RsWithType( new RsWithBody(baos.toByteArray()), "image/gif" ); } @Override Response act(final Request req); } |
@Test public void sendsMessageToBout() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("jeff1"); final Alias alias = user.aliases().iterate().iterator().next(); final long number = alias.inbox().start(); final Bout bout = alias.inbox().bout(number); bout.friends().invite(alias.name()); final RqWithAuth request = new RqWithAuth( urn, new RqMultipart.Fake( TkAttachTest.fake(number), new RqWithHeaders( TkAttachTest.body("non-zero"), String.format(TkAttachTest.POST_URL, number), "Content-Disposition: form-data; name=\"file\"; filename=\"some.xml\"", "Content-Type: application/xml", "Content-Length: 8" ) ) ); try { new FkBout(".+", new TkAttach(base)).route(request); } catch (final RsForward response) { MatcherAssert.assertThat( response, new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER) ); } MatcherAssert.assertThat( bout.messages().iterate().iterator().next().text(), Matchers.containsString("attachment \"some.xml\"") ); } | private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); @Override Response act(final Request req); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); @Override Response act(final Request req); } |
@Test(expected = RsFailure.class) public void ignoresWrongRequest() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:3"; final User user = base.user(new URN(urn)); user.aliases().add("jeff3"); final Alias alias = user.aliases().iterate().iterator().next(); final long bout = alias.inbox().start(); alias.inbox().bout(bout).friends().invite(alias.name()); new FkBout(".*", new TkAttach(base)).route( new RqWithAuth( urn, new RqMultipart.Fake( TkAttachTest.fake(bout), new RqWithHeaders( new RqLive( new ByteArrayInputStream("content2".getBytes()) ), String.format(TkAttachTest.POST_URL, bout), "Content-Disposition: form-data; name=\"file\"; filenam=\"aBaaPDF.pdf\"", "Content-Type: application/pdf" ) ) ) ); } | private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); @Override Response act(final Request req); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); @Override Response act(final Request req); } |
@Test public void ignoresWrongFile() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:2"; final User user = base.user(new URN(urn)); user.aliases().add("jeff2"); final Alias alias = user.aliases().iterate().iterator().next(); final long bout = alias.inbox().start(); alias.inbox().bout(bout).friends().invite(alias.name()); final String file = "test.bin"; final RqWithAuth request = new RqWithAuth( urn, new RqMultipart.Fake( TkAttachTest.fake(bout), new RqWithHeaders( TkAttachTest.body(""), String.format(TkAttachTest.POST_URL, bout), String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", file), "Content-Type: application/octet-stream" ) ) ); try { new FkBout(".*$", new TkAttach(base)).route(request); Assert.fail("Expected RsFailure exception but nothing was thrown"); } catch (final RsFailure ex) { MatcherAssert.assertThat( "file unexpectedly exists after attach failure", new Attachments.Search( alias.inbox().bout(bout).attachments() ).exists(file), Matchers.is(false) ); } } | private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); @Override Response act(final Request req); } | TkAttach implements Take { private static String name(final Request file) throws IOException { final Matcher matcher = TkAttach.FILE_NAME_PATTERN.matcher( new RqHeaders.Smart( new RqHeaders.Base(file) ).single("Content-Disposition") ); if (!matcher.find()) { throw new RsFailure("Filename was not provided"); } return URLDecoder.decode(matcher.group(5), CharEncoding.UTF_8); } TkAttach(final Base bse); @Override Response act(final Request req); } |
@Test public void rendersBoutPage() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("jeff"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.attachments().create("a1"); bout.messages().post("hello, world!"); bout.friends().invite(alias.name()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new FkBout(TkIndexTest.REGEX, new TkIndex(base)).route( new RqWithAuth( urn, new RqFake( RqMethod.GET, String.format("/b/%d", bout.number()) ) ) ).get() ).printBody() ), XhtmlMatchers.hasXPaths( "/page/bout[number=1]", "/page/bout[title='untitled']", "/page/bout[unread=0]", "/page/bout/friends/friend[alias='jeff']", "/page/bout/friends/friend/links/link[@rel='photo']", "/page/bout/friends/friend/links/link[@rel='kick']", "/page/bout/attachments/attachment/links/link[@rel='delete']", "/page/bout/messages/message[text='hello, world!']" ) ); } | private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } TkIndex(final Base bse); } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } TkIndex(final Base bse); @Override Response act(final Request req); } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } TkIndex(final Base bse); @Override Response act(final Request req); } |
@Test public void searchesMessages() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:99"; final User user = base.user(new URN(urn)); user.aliases().add("test-search-user"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.messages().post("test1"); bout.messages().post("test2"); bout.messages().post("fest"); bout.friends().invite(alias.name()); MatcherAssert.assertThat( XhtmlMatchers.xhtml( new RsPrint( new FkBout(TkIndexTest.REGEX, new TkIndex(base)).route( new RqWithAuth( urn, new RqFake( RqMethod.GET, String.format( "/b/%d/search?q=test", bout.number() ) ) ) ).get() ).printBody() ), XhtmlMatchers.hasXPaths( "/page/bout/friends/friend[alias='test-search-user']", "/page/bout/messages/message[text='test2']", "/page/bout/messages/message[text='test1']" ) ); } | private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } TkIndex(final Base bse); } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } TkIndex(final Base bse); @Override Response act(final Request req); } | TkIndex implements Take { private static Iterable<Message> messages(final Bout bout, final Request req, final String query) throws IOException { final Iterable<Message> messages; if (StringUtils.isBlank(query)) { final long start = Long.parseLong( new RqHref.Smart(new RqHref.Base(req)).single( "start", Long.toString(Inbox.NEVER) ) ); messages = Iterables.limit( bout.messages().jump(start).iterate(), Messages.PAGE ); } else { messages = bout.messages().search(query); } return messages; } TkIndex(final Base bse); @Override Response act(final Request req); } |
@Test public void savesEmail() throws Exception { final Base base = new CdBase(new MkBase()); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("alias"); final Alias alias = user.aliases().iterate().iterator().next(); alias.email("[email protected]"); new TkAuth( new TkSaveEmail(base, false), new PsFixed(new Identity.Simple(urn)) ).act( new RqForm.Fake( new RqFake(), TkSaveEmailTest.EMAIL, "[email protected]" ) ); MatcherAssert.assertThat( alias.email(), Matchers.equalTo("[email protected][email protected]") ); } | @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); @Override Response act(final Request req); } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); @Override Response act(final Request req); } |
@Test (expected = RsForward.class) public void invitesUserByEmail() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:1"; final User user = base.user(new URN(urn)); user.aliases().add("jeff"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.messages().post("Before invite by email."); bout.friends().invite(alias.name()); try { new TkInvite(base).act( new RqWithHeader( new RqWithAuth( urn, new RqFake( RqMethod.POST, String.format( TkInviteTest.INVITE_PATH, bout.number() ), "[email protected]" ) ), TkInviteTest.NETBOUT_HEADER, Long.toString(bout.number()) ) ); } catch (final RsForward ex) { MatcherAssert.assertThat( ex.getLocalizedMessage(), Matchers.containsString("foo-bar-airfrc") ); throw ex; } } | @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); @Override Response act(final Request req); String inviteByEmail(@NotNull(message = "Invite can't be NULL")
final String invite, final Bout bout); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); @Override Response act(final Request req); String inviteByEmail(@NotNull(message = "Invite can't be NULL")
final String invite, final Bout bout); } |
@Test (expected = RsFailure.class) public void failsWhenInvitingWithTooLongAlias() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:2"; final User user = base.user(new URN(urn)); final String name = StringUtils.join( "12345678901234567890123456789012345678901234", "5678901234567890123456789012345678901234567", "890123456789012345678901234567890" ); user.aliases().add("jack"); final Alias alias = user.aliases().iterate().iterator().next(); final Bout bout = alias.inbox().bout(alias.inbox().start()); try { new TkInvite(base).act( new RqWithHeader( new RqWithAuth( urn, new RqFake( RqMethod.POST, String.format( TkInviteTest.INVITE_PATH, bout.number() ), String.format(TkInviteTest.INVITE_PARAM, name) ) ), TkInviteTest.NETBOUT_HEADER, Long.toString(bout.number()) ) ); } catch (final RsFailure ex) { MatcherAssert.assertThat( ex.getLocalizedMessage(), Matchers.containsString("alias is too long") ); throw ex; } } | @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); @Override Response act(final Request req); String inviteByEmail(@NotNull(message = "Invite can't be NULL")
final String invite, final Bout bout); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); @Override Response act(final Request req); String inviteByEmail(@NotNull(message = "Invite can't be NULL")
final String invite, final Bout bout); } |
@Test (expected = RsForward.class) public void invitesValidAlias() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:3"; final User user = base.user(new URN(urn)); final String name = "john"; user.aliases().add(name); final Alias alias = user.aliases().iterate().iterator().next(); try { final Bout bout = alias.inbox().bout(alias.inbox().start()); new TkInvite(base).act( new RqWithHeader( new RqWithAuth( urn, new RqFake( RqMethod.POST, String.format( TkInviteTest.INVITE_PATH, bout.number() ), String.format(TkInviteTest.INVITE_PARAM, name) ) ), TkInviteTest.NETBOUT_HEADER, Long.toString(bout.number()) ) ); } catch (final RsForward ex) { MatcherAssert.assertThat( ex.getLocalizedMessage(), Matchers.containsString( String.format("\"%s\" invited to the bout", name) ) ); throw ex; } } | @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); @Override Response act(final Request req); String inviteByEmail(@NotNull(message = "Invite can't be NULL")
final String invite, final Bout bout); } | TkInvite implements Take { @Override public Response act(final Request req) throws IOException { final String invite = new RqForm.Smart( new RqForm.Base(req) ).single("name"); final Bout bout = new RqBout(this.base, req).bout(); final String guest; if (MAIL_MASK.matcher(invite).find()) { guest = this.inviteByEmail(invite, bout); } else { guest = invite; } try { bout.friends().invite(guest); } catch ( final Friends.UnknownAliasException | IllegalArgumentException ex ) { throw new RsFailure(ex); } throw new RsForward( new RsFlash( String.format( "\"%s\" invited to the bout #%d", guest, bout.number() ), Level.INFO ) ); } TkInvite(final Base bse); @Override Response act(final Request req); String inviteByEmail(@NotNull(message = "Invite can't be NULL")
final String invite, final Bout bout); } |
@Test public void allocatesDifferentNumbersWithDifferentPorts() throws Exception { final int porta = Ports.allocate(); final int portb = Ports.allocate(); final int portc = Ports.allocate(); MatcherAssert.assertThat(porta, Matchers.not(portb)); MatcherAssert.assertThat(porta, Matchers.not(portc)); MatcherAssert.assertThat(portb, Matchers.not(portc)); } | public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); static int allocate(); static void release(final int port); } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); static int allocate(); static void release(final int port); } |
@Test public void allocatesDifferentNumbersWithSamePorts() throws Exception { final int porta = Ports.allocate(); final int portb = Ports.allocate(); final int portc = Ports.allocate(); MatcherAssert.assertThat(porta, Matchers.not(portb)); MatcherAssert.assertThat(porta, Matchers.not(portc)); MatcherAssert.assertThat(portb, Matchers.not(portc)); } | public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); static int allocate(); static void release(final int port); } | Ports { public static int allocate() throws IOException { synchronized (Ports.class) { int attempts = 0; int prt; do { prt = random(); ++attempts; if (attempts > 100) { throw new IllegalStateException( String.format( "failed to allocate TCP port after %d attempts", attempts ) ); } } while (Ports.ASSIGNED.contains(prt)); return prt; } } private Ports(); static int allocate(); static void release(final int port); } |
@Test public void readsInboxPeriodically() throws Exception { final GreenMail mail = new GreenMail( new ServerSetup(Ports.allocate(), null, "pop3") ); mail.start(); final ServerSetup setup = mail.getPop3().getServerSetup(); final String login = "to"; final String from = "[email protected]"; final String to = "[email protected]"; final String password = "soooosecret"; final String subject = GreenMailUtil.random(); final String body = GreenMailUtil.random(); final GreenMailUser user = mail.setUser(login, password); new EmCatch( new EmCatch.Action() { @Override public void run(final Message msg) { MatcherAssert.assertThat(msg, Matchers.notNullValue()); try { MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo(subject) ); MatcherAssert.assertThat( msg.getFrom()[0].toString(), Matchers.equalTo(from) ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.equalTo(to) ); } catch (final MessagingException ex) { throw new IllegalStateException(ex); } } }, login, password, setup.getBindAddress(), setup.getPort(), 500L ).start(); final MimeMessage message = GreenMailUtil.createTextEmail( to, from, subject, body, setup ); user.deliver(message); MatcherAssert.assertThat( mail.getReceivedMessages().length, Matchers.equalTo(1) ); Thread.sleep(1000); Ports.release(setup.getPort()); mail.stop(); } | public void start() { final Thread monitor = new Thread( new Runnable() { @Override public void run() { EmCatch.this.mainLoop(); } } ); monitor.setDaemon(true); monitor.start(); } | EmCatch { public void start() { final Thread monitor = new Thread( new Runnable() { @Override public void run() { EmCatch.this.mainLoop(); } } ); monitor.setDaemon(true); monitor.start(); } } | EmCatch { public void start() { final Thread monitor = new Thread( new Runnable() { @Override public void run() { EmCatch.this.mainLoop(); } } ); monitor.setDaemon(true); monitor.start(); } EmCatch(final Action act, final String usr, final String pass,
final String hst, final int prt, final long prd); } | EmCatch { public void start() { final Thread monitor = new Thread( new Runnable() { @Override public void run() { EmCatch.this.mainLoop(); } } ); monitor.setDaemon(true); monitor.start(); } EmCatch(final Action act, final String usr, final String pass,
final String hst, final int prt, final long prd); void start(); } | EmCatch { public void start() { final Thread monitor = new Thread( new Runnable() { @Override public void run() { EmCatch.this.mainLoop(); } } ); monitor.setDaemon(true); monitor.start(); } EmCatch(final Action act, final String usr, final String pass,
final String hst, final int prt, final long prd); void start(); } |
@Test public void sendEmailWithInviteKey() throws Exception { final String content = "You are invited into the Netbout click on the link to"; final Postman postman = Mockito.mock(Postman.class); final BoutInviteMail mail = new BoutInviteMail(postman); final MkBase base = new MkBase(); final Alias alias = new EmAlias(base.randomAlias(), postman); final String email = "[email protected]"; final String urn = "urn:[email protected]:mesutozen36-gmail-com"; final Bout bout = alias.inbox().bout(alias.inbox().start()); mail.send(email, urn, bout); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Message msg = captor.getValue().unwrap(); MatcherAssert.assertThat(msg.getAllRecipients().length, Matchers.is(1)); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.equalTo(email) ); MatcherAssert.assertThat(msg.getSubject(), Matchers.startsWith("#1: ")); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); MimeMultipart.class.cast(msg.getContent()).writeTo(baos); MatcherAssert.assertThat( baos.toString(), Matchers.containsString(content) ); } | public void send(final String email, final String urn, final Bout bout) throws IOException { this.postman.send( new Envelope.MIME() .with(new StRecipient(email)) .with( new StSubject( String.format( "#%d: %s", bout.number(), bout.title() ) ) ) .with( new EnHTML( Joiner.on('\n').join( new Markdown.Default().html( BoutInviteMail.MAIL_CONTENT ), "<br/>", String.format( Manifests.read("Netbout-Site") .concat("/b/%d?invite=%s"), bout.number(), encrypt(urn) ), "<p style=\"color:#C8C8C8;font-size:2px;\">", String.format("%d</p>", System.nanoTime()), new GmailViewAction(bout.number()).xml() ) ) ) ); } | BoutInviteMail { public void send(final String email, final String urn, final Bout bout) throws IOException { this.postman.send( new Envelope.MIME() .with(new StRecipient(email)) .with( new StSubject( String.format( "#%d: %s", bout.number(), bout.title() ) ) ) .with( new EnHTML( Joiner.on('\n').join( new Markdown.Default().html( BoutInviteMail.MAIL_CONTENT ), "<br/>", String.format( Manifests.read("Netbout-Site") .concat("/b/%d?invite=%s"), bout.number(), encrypt(urn) ), "<p style=\"color:#C8C8C8;font-size:2px;\">", String.format("%d</p>", System.nanoTime()), new GmailViewAction(bout.number()).xml() ) ) ) ); } } | BoutInviteMail { public void send(final String email, final String urn, final Bout bout) throws IOException { this.postman.send( new Envelope.MIME() .with(new StRecipient(email)) .with( new StSubject( String.format( "#%d: %s", bout.number(), bout.title() ) ) ) .with( new EnHTML( Joiner.on('\n').join( new Markdown.Default().html( BoutInviteMail.MAIL_CONTENT ), "<br/>", String.format( Manifests.read("Netbout-Site") .concat("/b/%d?invite=%s"), bout.number(), encrypt(urn) ), "<p style=\"color:#C8C8C8;font-size:2px;\">", String.format("%d</p>", System.nanoTime()), new GmailViewAction(bout.number()).xml() ) ) ) ); } BoutInviteMail(final Postman pst); } | BoutInviteMail { public void send(final String email, final String urn, final Bout bout) throws IOException { this.postman.send( new Envelope.MIME() .with(new StRecipient(email)) .with( new StSubject( String.format( "#%d: %s", bout.number(), bout.title() ) ) ) .with( new EnHTML( Joiner.on('\n').join( new Markdown.Default().html( BoutInviteMail.MAIL_CONTENT ), "<br/>", String.format( Manifests.read("Netbout-Site") .concat("/b/%d?invite=%s"), bout.number(), encrypt(urn) ), "<p style=\"color:#C8C8C8;font-size:2px;\">", String.format("%d</p>", System.nanoTime()), new GmailViewAction(bout.number()).xml() ) ) ) ); } BoutInviteMail(final Postman pst); void send(final String email, final String urn, final Bout bout); } | BoutInviteMail { public void send(final String email, final String urn, final Bout bout) throws IOException { this.postman.send( new Envelope.MIME() .with(new StRecipient(email)) .with( new StSubject( String.format( "#%d: %s", bout.number(), bout.title() ) ) ) .with( new EnHTML( Joiner.on('\n').join( new Markdown.Default().html( BoutInviteMail.MAIL_CONTENT ), "<br/>", String.format( Manifests.read("Netbout-Site") .concat("/b/%d?invite=%s"), bout.number(), encrypt(urn) ), "<p style=\"color:#C8C8C8;font-size:2px;\">", String.format("%d</p>", System.nanoTime()), new GmailViewAction(bout.number()).xml() ) ) ) ); } BoutInviteMail(final Postman pst); void send(final String email, final String urn, final Bout bout); } |
@Test(expected = RsFailure.class) public void throwsUserFriendlyExceptionOnFailure() throws Exception { final Postman postman = Mockito.mock(Postman.class); final MkBase base = new MkBase(); final Alias alias = new EmAlias(base.randomAlias(), postman); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.friends().invite(base.randomAlias().name()); Mockito.doThrow(new IOException()).when(postman) .send(Mockito.any(Envelope.class)); final EmMessages messages = new EmMessages( bout.messages(), postman, bout, alias.name() ); messages.post("how are you?"); } | @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } EmMessages(final Messages org, final Postman pst,
final Bout bot, final String slf); } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } EmMessages(final Messages org, final Postman pst,
final Bout bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long num); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } EmMessages(final Messages org, final Postman pst,
final Bout bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long num); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); } |
@Test public void canSendEmailWithReplyTo() throws Exception { final Postman postman = Mockito.mock(Postman.class); final MkBase base = new MkBase(); final Alias alias = new EmAlias(base.randomAlias(), postman); final Bout bout = alias.inbox().bout(alias.inbox().start()); bout.friends().invite(base.randomAlias().name()); bout.messages().post("reply-to header test"); final ArgumentCaptor<Envelope> argument = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman) .send(argument.capture()); final String[] reply = argument.getValue().unwrap().getReplyTo()[0].toString().split("@"); MatcherAssert.assertThat( String.format( "%s@%s", EmCatch.decrypt(reply[0]), reply[1] ), Matchers.equalTo( String.format( "%s|%[email protected]", alias.name(), bout.number() ) ) ); } | @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } EmMessages(final Messages org, final Postman pst,
final Bout bot, final String slf); } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } EmMessages(final Messages org, final Postman pst,
final Bout bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long num); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); } | EmMessages implements Messages { @Override public void post(final String text) throws IOException { this.origin.post(text); final Collection<String> failed = new ArrayList<>(16); for (final Friend friend : this.bout.friends().iterate()) { if (friend.email().isEmpty() || friend.alias().equals(this.self) || !this.bout.subscription(friend.alias())) { continue; } try { this.courier.email(this.self, friend, text); } catch (final IOException exception) { failed.add(friend.alias()); } } if (!failed.isEmpty()) { final String message = String.format( "Sorry, we were not able to send the notification email to %s.", Joiner.on(", ").join(failed) ); throw new RsFailure(new EmailDeliveryException(message)); } } EmMessages(final Messages org, final Postman pst,
final Bout bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long num); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); } |
@Test public void sendsConfirmationEmail() throws Exception { final Postman postman = Mockito.mock(Postman.class); final Alias alias = new EmAlias(new MkBase().randomAlias(), postman); alias.email("[email protected]", "netbout.com/test/verification/link"); final ArgumentCaptor<Envelope> captor = ArgumentCaptor.forClass(Envelope.class); Mockito.verify(postman).send(captor.capture()); final Message msg = captor.getValue().unwrap(); MatcherAssert.assertThat(msg.getFrom().length, Matchers.is(1)); MatcherAssert.assertThat( msg.getSubject(), Matchers.equalTo("Netbout email verification") ); MatcherAssert.assertThat( msg.getAllRecipients()[0].toString(), Matchers.containsString("mihai@test") ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); MimeMultipart.class.cast(msg.getContent()).writeTo(baos); final String content = new String(baos.toByteArray(), "UTF-8"); MatcherAssert.assertThat( content, Matchers.containsString( "<p>Hi,<br />Your notification e-mail address" ) ); MatcherAssert.assertThat( content, Matchers.containsString( "<a href=\"netbout.com/test/verification/link\">here</a>" ) ); } | @Override public String email() throws IOException { return this.origin.email(); } | EmAlias implements Alias { @Override public String email() throws IOException { return this.origin.email(); } } | EmAlias implements Alias { @Override public String email() throws IOException { return this.origin.email(); } EmAlias(final Alias org, final Postman pst); } | EmAlias implements Alias { @Override public String email() throws IOException { return this.origin.email(); } EmAlias(final Alias org, final Postman pst); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); } | EmAlias implements Alias { @Override public String email() throws IOException { return this.origin.email(); } EmAlias(final Alias org, final Postman pst); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); } |
@Test public void savesEmailLocal() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:2"; final User user = base.user(new URN(urn)); user.aliases().add("alias2"); final Alias alias = user.aliases().iterate().iterator().next(); alias.email("[email protected]"); final String email = "[email protected]"; new TkAuth( new TkSaveEmail(base), new PsFixed(new Identity.Simple(urn)) ).act(new RqForm.Fake(new RqFake(), TkSaveEmailTest.EMAIL, email)); MatcherAssert.assertThat( alias.email(), Matchers.equalTo(email) ); } | @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); @Override Response act(final Request req); } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); @Override Response act(final Request req); } |
@Test public void changesUpdateAttribute() throws Exception { final Bout bout = new MkBase().randomBout(); final Messages messages = bout.messages(); final Long last = bout.updated().getTime(); messages.post("hi"); Thread.sleep(Tv.HUNDRED); MatcherAssert.assertThat( bout.updated().getTime(), Matchers.greaterThan(last) ); } | @Override public void post(final String text) throws IOException { try { new JdbcSession(this.sql.source()) .sql("INSERT INTO message (bout, text, author) VALUES (?, ?, ?)") .set(this.bout) .set(text) .set(this.self) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } new TouchBout(this.sql, this.bout).act(); } | MkMessages implements Messages { @Override public void post(final String text) throws IOException { try { new JdbcSession(this.sql.source()) .sql("INSERT INTO message (bout, text, author) VALUES (?, ?, ?)") .set(this.bout) .set(text) .set(this.self) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } new TouchBout(this.sql, this.bout).act(); } } | MkMessages implements Messages { @Override public void post(final String text) throws IOException { try { new JdbcSession(this.sql.source()) .sql("INSERT INTO message (bout, text, author) VALUES (?, ?, ?)") .set(this.bout) .set(text) .set(this.self) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } new TouchBout(this.sql, this.bout).act(); } MkMessages(final Sql src, final long bot, final String slf); } | MkMessages implements Messages { @Override public void post(final String text) throws IOException { try { new JdbcSession(this.sql.source()) .sql("INSERT INTO message (bout, text, author) VALUES (?, ?, ?)") .set(this.bout) .set(text) .set(this.self) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } new TouchBout(this.sql, this.bout).act(); } MkMessages(final Sql src, final long bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long number); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); } | MkMessages implements Messages { @Override public void post(final String text) throws IOException { try { new JdbcSession(this.sql.source()) .sql("INSERT INTO message (bout, text, author) VALUES (?, ?, ?)") .set(this.bout) .set(text) .set(this.self) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } new TouchBout(this.sql, this.bout).act(); } MkMessages(final Sql src, final long bot, final String slf); @Override void post(final String text); @Override long unread(); @Override Pageable<Message> jump(final long number); @Override Iterable<Message> iterate(); @Override Iterable<Message> search(final String term); } |
@Test public final void testStart() throws IOException { final String name = "current-name"; final Sql sql = new H2Sql(); final Aliases aliases = new MkUser( sql, URN.create( String.format( "urn:test:%d", new SecureRandom().nextInt(Integer.MAX_VALUE) ) ) ).aliases(); aliases.add(name); final Alias alias = aliases.iterate().iterator().next(); alias.email(String.format("%[email protected]", alias.name())); final MkInbox inbox = new MkInbox(sql, name); final Bout bout = inbox.bout(inbox.start()); MatcherAssert.assertThat( bout.friends().iterate(), Matchers.hasItem(new Friend.HasAlias(Matchers.is(name))) ); } | @Override public long start() throws IOException { try { final Long number = new JdbcSession(this.sql.source()) .sql("INSERT INTO bout (title) VALUES (?)") .set("untitled") .insert(new SingleOutcome<Long>(Long.class)); this.bout(number).friends().invite(this.self); return number; } catch (final SQLException ex) { throw new IOException(ex); } } | MkInbox implements Inbox { @Override public long start() throws IOException { try { final Long number = new JdbcSession(this.sql.source()) .sql("INSERT INTO bout (title) VALUES (?)") .set("untitled") .insert(new SingleOutcome<Long>(Long.class)); this.bout(number).friends().invite(this.self); return number; } catch (final SQLException ex) { throw new IOException(ex); } } } | MkInbox implements Inbox { @Override public long start() throws IOException { try { final Long number = new JdbcSession(this.sql.source()) .sql("INSERT INTO bout (title) VALUES (?)") .set("untitled") .insert(new SingleOutcome<Long>(Long.class)); this.bout(number).friends().invite(this.self); return number; } catch (final SQLException ex) { throw new IOException(ex); } } MkInbox(final Sql src, final String name); } | MkInbox implements Inbox { @Override public long start() throws IOException { try { final Long number = new JdbcSession(this.sql.source()) .sql("INSERT INTO bout (title) VALUES (?)") .set("untitled") .insert(new SingleOutcome<Long>(Long.class)); this.bout(number).friends().invite(this.self); return number; } catch (final SQLException ex) { throw new IOException(ex); } } MkInbox(final Sql src, final String name); @Override long start(); @Override long unread(); @Override Bout bout(final long number); @Override Pageable<Bout> jump(final long number); @Override Iterable<Bout> iterate(); @Override Iterable<Bout> search(final String term); } | MkInbox implements Inbox { @Override public long start() throws IOException { try { final Long number = new JdbcSession(this.sql.source()) .sql("INSERT INTO bout (title) VALUES (?)") .set("untitled") .insert(new SingleOutcome<Long>(Long.class)); this.bout(number).friends().invite(this.self); return number; } catch (final SQLException ex) { throw new IOException(ex); } } MkInbox(final Sql src, final String name); @Override long start(); @Override long unread(); @Override Bout bout(final long number); @Override Pageable<Bout> jump(final long number); @Override Iterable<Bout> iterate(); @Override Iterable<Bout> search(final String term); } |
@Test public void savesAndReadsEmail() throws Exception { final Alias alias = new MkBase().randomAlias(); MatcherAssert.assertThat(alias.email(), Matchers.notNullValue()); final String email = "[email protected]"; alias.email(email); MatcherAssert.assertThat(alias.email(), Matchers.equalTo(email)); } | @Override public String email() throws IOException { try { return new JdbcSession(this.sql.source()) .sql("SELECT email FROM alias WHERE name = ?") .set(this.label) .select(new SingleOutcome<String>(String.class)); } catch (final SQLException ex) { throw new IOException(ex); } } | MkAlias implements Alias { @Override public String email() throws IOException { try { return new JdbcSession(this.sql.source()) .sql("SELECT email FROM alias WHERE name = ?") .set(this.label) .select(new SingleOutcome<String>(String.class)); } catch (final SQLException ex) { throw new IOException(ex); } } } | MkAlias implements Alias { @Override public String email() throws IOException { try { return new JdbcSession(this.sql.source()) .sql("SELECT email FROM alias WHERE name = ?") .set(this.label) .select(new SingleOutcome<String>(String.class)); } catch (final SQLException ex) { throw new IOException(ex); } } MkAlias(final Sql src, final String name); } | MkAlias implements Alias { @Override public String email() throws IOException { try { return new JdbcSession(this.sql.source()) .sql("SELECT email FROM alias WHERE name = ?") .set(this.label) .select(new SingleOutcome<String>(String.class)); } catch (final SQLException ex) { throw new IOException(ex); } } MkAlias(final Sql src, final String name); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); } | MkAlias implements Alias { @Override public String email() throws IOException { try { return new JdbcSession(this.sql.source()) .sql("SELECT email FROM alias WHERE name = ?") .set(this.label) .select(new SingleOutcome<String>(String.class)); } catch (final SQLException ex) { throw new IOException(ex); } } MkAlias(final Sql src, final String name); @Override String name(); @Override URI photo(); @Override Locale locale(); @Override void photo(final URI uri); @Override String email(); @Override void email(final String email); @Override void email(final String email, final String urn, final Bout bout); @Override void email(final String email, final String link); @Override Inbox inbox(); } |
@Test public void startsBoutAndTalks() throws Exception { final Messages messages = new MkBase().randomBout().messages(); messages.post("How are you doing?"); MatcherAssert.assertThat( messages.iterate(), Matchers.hasItem( new Message.HasText(Matchers.containsString("are you")) ) ); } | public Bout randomBout() throws IOException { final Inbox inbox = this.randomAlias().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.rename( String.format( "random title %d", MkBase.RANDOM.nextInt(Integer.MAX_VALUE) ) ); return bout; } | MkBase implements Base { public Bout randomBout() throws IOException { final Inbox inbox = this.randomAlias().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.rename( String.format( "random title %d", MkBase.RANDOM.nextInt(Integer.MAX_VALUE) ) ); return bout; } } | MkBase implements Base { public Bout randomBout() throws IOException { final Inbox inbox = this.randomAlias().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.rename( String.format( "random title %d", MkBase.RANDOM.nextInt(Integer.MAX_VALUE) ) ); return bout; } MkBase(); MkBase(final Sql src); } | MkBase implements Base { public Bout randomBout() throws IOException { final Inbox inbox = this.randomAlias().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.rename( String.format( "random title %d", MkBase.RANDOM.nextInt(Integer.MAX_VALUE) ) ); return bout; } MkBase(); MkBase(final Sql src); @Override User user(final URN urn); @Override void close(); Alias randomAlias(); Bout randomBout(); } | MkBase implements Base { public Bout randomBout() throws IOException { final Inbox inbox = this.randomAlias().inbox(); final Bout bout = inbox.bout(inbox.start()); bout.rename( String.format( "random title %d", MkBase.RANDOM.nextInt(Integer.MAX_VALUE) ) ); return bout; } MkBase(); MkBase(final Sql src); @Override User user(final URN urn); @Override void close(); Alias randomAlias(); Bout randomBout(); } |
@Test public void changesUpdateAttribute() throws Exception { final Sql sql = new H2Sql(); final Bout bout = new MkBase(sql).randomBout(); final Long last = bout.updated().getTime(); new TouchBout(sql, bout.number()).act(); Thread.sleep(Tv.HUNDRED); MatcherAssert.assertThat( bout.updated().getTime(), Matchers.greaterThan(last) ); } | public void act() throws IOException { try { new JdbcSession(this.sql.source()) .sql("UPDATE bout SET updated = CURRENT_TIMESTAMP WHERE number = ?") .set(this.bout) .update(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } | TouchBout { public void act() throws IOException { try { new JdbcSession(this.sql.source()) .sql("UPDATE bout SET updated = CURRENT_TIMESTAMP WHERE number = ?") .set(this.bout) .update(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } } | TouchBout { public void act() throws IOException { try { new JdbcSession(this.sql.source()) .sql("UPDATE bout SET updated = CURRENT_TIMESTAMP WHERE number = ?") .set(this.bout) .update(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } TouchBout(final Sql src, final long bot); } | TouchBout { public void act() throws IOException { try { new JdbcSession(this.sql.source()) .sql("UPDATE bout SET updated = CURRENT_TIMESTAMP WHERE number = ?") .set(this.bout) .update(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } TouchBout(final Sql src, final long bot); void act(); } | TouchBout { public void act() throws IOException { try { new JdbcSession(this.sql.source()) .sql("UPDATE bout SET updated = CURRENT_TIMESTAMP WHERE number = ?") .set(this.bout) .update(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } TouchBout(final Sql src, final long bot); void act(); } |
@Test(expected = Friends.UnknownAliasException.class) public void inviteFailsOnUnknownAlias() throws Exception { new MkBase().randomBout().friends().invite("NoSuchFriend"); } | @Override public void invite(final String friend) throws IOException { try { final boolean exists = new JdbcSession(this.sql.source()) .sql("SELECT name FROM alias WHERE name = ?") .set(friend) .select(Outcome.NOT_EMPTY); if (!exists) { throw new Friends.UnknownAliasException( String.format("alias '%s' doesn't exist", friend) ); } new JdbcSession(this.sql.source()) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } | MkFriends implements Friends { @Override public void invite(final String friend) throws IOException { try { final boolean exists = new JdbcSession(this.sql.source()) .sql("SELECT name FROM alias WHERE name = ?") .set(friend) .select(Outcome.NOT_EMPTY); if (!exists) { throw new Friends.UnknownAliasException( String.format("alias '%s' doesn't exist", friend) ); } new JdbcSession(this.sql.source()) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } } | MkFriends implements Friends { @Override public void invite(final String friend) throws IOException { try { final boolean exists = new JdbcSession(this.sql.source()) .sql("SELECT name FROM alias WHERE name = ?") .set(friend) .select(Outcome.NOT_EMPTY); if (!exists) { throw new Friends.UnknownAliasException( String.format("alias '%s' doesn't exist", friend) ); } new JdbcSession(this.sql.source()) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } MkFriends(final Sql src, final long bot); } | MkFriends implements Friends { @Override public void invite(final String friend) throws IOException { try { final boolean exists = new JdbcSession(this.sql.source()) .sql("SELECT name FROM alias WHERE name = ?") .set(friend) .select(Outcome.NOT_EMPTY); if (!exists) { throw new Friends.UnknownAliasException( String.format("alias '%s' doesn't exist", friend) ); } new JdbcSession(this.sql.source()) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } MkFriends(final Sql src, final long bot); @Override void invite(final String friend); @Override void kick(final String friend); @Override Iterable<Friend> iterate(); } | MkFriends implements Friends { @Override public void invite(final String friend) throws IOException { try { final boolean exists = new JdbcSession(this.sql.source()) .sql("SELECT name FROM alias WHERE name = ?") .set(friend) .select(Outcome.NOT_EMPTY); if (!exists) { throw new Friends.UnknownAliasException( String.format("alias '%s' doesn't exist", friend) ); } new JdbcSession(this.sql.source()) .sql("INSERT INTO friend (bout, alias, subscription) VALUES (?, ?, ?)") .set(this.bout) .set(friend) .set(true) .insert(Outcome.VOID); } catch (final SQLException ex) { throw new IOException(ex); } } MkFriends(final Sql src, final long bot); @Override void invite(final String friend); @Override void kick(final String friend); @Override Iterable<Friend> iterate(); } |
@Test(expected = RsForward.class) public void throwsRsForward() throws Exception { final MkBase base = new MkBase(); final String urn = "urn:test:3"; final User user = base.user(new URN(urn)); user.aliases().add("alias3"); final Alias alias = user.aliases().iterate().iterator().next(); alias.email("[email protected]"); new TkAuth( new TkSaveEmail(base, true), new PsFixed(new Identity.Simple(urn)) ).act( new RqForm.Fake( new RqFake(), TkSaveEmailTest.EMAIL, "invalidemail" ) ); } | @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); @Override Response act(final Request req); } | TkSaveEmail implements Take { @Override public Response act(final Request req) throws IOException { final String email = new RqForm.Smart( new RqForm.Base(req) ).single("email"); final Alias alias = new RqAlias(this.base, req).alias(); final Response res; if (this.local) { try { alias.email(email); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format("Email changed to \"%s\".", email) ) ); } else { final String code = URLEncoder.encode( TkSaveEmail.ENC.encrypt( String.format( "%s:%s:%s", new RqAuth(req).identity().urn(), alias.name(), email ) ), "UTF-8" ); final String link = String.format( "%semverify/%s", new RqHref.Smart(new RqHref.Base(req)).home().bare(), code ); final String old; if (alias.email().contains("!")) { old = alias.email().substring(0, alias.email().indexOf('!')); } else { old = alias.email(); } try { alias.email(String.format("%s!%s", old, email), link); } catch (final IOException ex) { throw new RsFailure(ex); } res = new RsForward( new RsFlash( String.format( "Email changed to \"%s\". The verification " + "link sent to this address.", email ) ) ); } return res; } TkSaveEmail(final Base bse); TkSaveEmail(final Base bse, final boolean lcl); @Override Response act(final Request req); } |
@Test public void kicksAnUser() throws Exception { final String alias = "test"; final String urn = "urn:test:1"; final MkBase base = new MkBase(); final Bout bout = base.randomBout(); base.user(new URN(urn)).aliases().add(alias); bout.friends().invite(alias); MatcherAssert.assertThat( new RsPrint( new TkAuth( new TkApp(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, String.format( "/b/%d/kick?name=%s", bout.number(), alias ) ) ) ).printHead(), Matchers.containsString("you+kicked") ); } | @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } |
@Test public void searchesBouts() throws Exception { final String urn = "urn:test:2"; final MkBase base = new MkBase(); final Aliases aliases = base.user(new URN(urn)).aliases(); aliases.add("test2"); final Inbox inbox = aliases.iterate().iterator().next().inbox(); final Bout first = inbox.bout(inbox.start()); final String firsttitle = "bout1 title"; first.rename(firsttitle); first.messages().post("hello"); final Bout second = inbox.bout(inbox.start()); final String secondtitle = "bout2 title"; second.rename(secondtitle); second.messages().post("message with term"); final String thirdtitle = "bout title with term"; inbox.bout(inbox.start()).rename(thirdtitle); final String body = new RsPrint( new TkAuth( new TkInbox(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, String.format( "/search?q=%s", "term" ) ) ) ).printBody(); MatcherAssert.assertThat( body, Matchers.containsString(secondtitle) ); MatcherAssert.assertThat( body, Matchers.containsString(thirdtitle) ); MatcherAssert.assertThat( body, Matchers.not(Matchers.containsString(firsttitle)) ); } | @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } |
@Test public void handleInvalidSince() throws Exception { final String alias = "test3"; final String urn = "urn:test:3"; final MkBase base = new MkBase(); final Bout bout = base.randomBout(); base.user(new URN(urn)).aliases().add(alias); bout.friends().invite(alias); MatcherAssert.assertThat( new RsPrint( new TkAuth( new TkApp(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, "/?since" ) ) ).printHead(), Matchers.containsString( "invalid+%27since%27+value%2C+timestamp+is+expected" ) ); } | @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } |
@Test public void handleValidSince() throws Exception { final String alias = "test4"; final String urn = "urn:test:4"; final MkBase base = new MkBase(); final Bout bout = base.randomBout(); base.user(new URN(urn)).aliases().add(alias); bout.friends().invite(alias); MatcherAssert.assertThat( new RsPrint( new TkAuth( new TkApp(base), new PsFixed(new Identity.Simple(urn)) ).act( new RqFake( RqMethod.GET, "/?since=123456789" ) ) ).printHead(), Matchers.startsWith( "HTTP/1.1 200 OK" ) ); } | @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } | TkInbox implements Take { @Override public Response act(final Request req) throws IOException { final String query = new RqHref.Smart(new RqHref.Base(req)).single( "q", "" ); return new RsPage( "/xsl/inbox.xsl", this.base, req, new XeAppend("bouts", this.bouts(req, query)), new XeAppend("query", query), new XeLink("search", new Href("/search")) ); } TkInbox(final Base bse); @Override Response act(final Request req); } |
@Test public void handlesWhitespaceAfterLinks() throws Exception { MatcherAssert.assertThat( new MarkdownTxtmark().html( "Hi [google](http: ), Matchers.equalTo( "<p>Hi <a href=\"http: ) ); } | @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } | MarkdownTxtmark implements Markdown { @Override public String html(@NotNull final String txt) { final Configuration conf = Configuration.builder() .enableSafeMode() .build(); return MarkdownTxtmark.fixedCodeBlocks( Processor.process( MarkdownTxtmark.formatLinks( MarkdownTxtmark.makeLineBreakExcludeCode( txt, Arrays.asList("```", "``", "`").iterator() ) ), conf ) ); } @Override String html(@NotNull final String txt); } |
@Test public void combinesMultipleFiles() throws Exception { final File input = this.temp.newFolder(); final File output = this.temp.newFolder(); FileUtils.write( new File(input, "b.req"), "\n\nUser is a \"good human being\".", StandardCharsets.UTF_8 ); FileUtils.write( new File(input, "a.req"), "\n\nUser is a \"human being\".", StandardCharsets.UTF_8 ); FileUtils.write( new File(input, "c.req"), "\n\n\nUser is a \"very good human being\". bug", StandardCharsets.UTF_8 ); new Compiler(input, output).compile(); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new XMLDocument(new File(output, "requs.xml"))), XhtmlMatchers.hasXPaths( "/spec/files/file[@id='0' and @line='1']", "/spec/files/file[@id='1' and @line='4']", "/spec/files/file[@id='2' and @line='7']", " " " "/spec/errors/error[@file='2' and @line='4']" ) ); } | public void compile() throws IOException { assert this.properties != null; final long start = System.currentTimeMillis(); final Facet[] facets = { new XeFacet.Wrap(new Aggregate(new File(this.input))), new XeFacet.Wrap(new AntlrFacet()), new Transform("cleanup/duplicate-step-numbers.xsl"), new Transform("cleanup/duplicate-step-signatures.xsl"), new Transform("cleanup/duplicate-step-objects.xsl"), new Transform("cleanup/duplicate-step-results.xsl"), new Transform("cleanup/lost-steps.xsl"), new Transform("cleanup/lost-methods.xsl"), new Transform("cleanup/duplicate-signatures.xsl"), new Transform("cleanup/duplicate-method-signatures.xsl"), new Transform("cleanup/duplicate-method-objects.xsl"), new Transform("cleanup/duplicate-method-bindings.xsl"), new Transform("cleanup/incomplete-step-object.xsl"), new Transform("cleanup/incomplete-step-signature.xsl"), new Transform("cleanup/incomplete-step-result.xsl"), new Transform("cleanup/incomplete-binding.xsl"), new Transform("cleanup/bindings-in-exception.xsl"), new Transform("seal-methods.xsl"), new Transform("sanity/signatures-check.xsl"), new Transform("sanity/types-check.xsl"), new Transform("sanity/seals-check.xsl"), new Transform("sanity/exception-rethrow-check.xsl"), new Transform("sanity/misplaced-failure-check.xsl"), new Transform("sanity/broken-order-of-steps.xsl"), new Transform("sanity/missed-step-numbers.xsl"), new Transform("sanity/too-many-steps.xsl"), new Transform("sanity/empty-re-throws.xsl"), new Transform("sanity/orphan-types.xsl"), new Transform("sanity/undeclared-bindings.xsl"), new Transform("sanity/actor-is-singleton.xsl"), new Transform("step-refs.xsl"), new Transform("methods-in-markdown.xsl"), new Transform("pages-in-html.xsl"), new Transform("count-ambiguity.xsl"), new Transform("find-tbds.xsl"), new Transform("uml/sequence-diagrams.xsl"), new Transform("uml/use-case-diagrams.xsl"), new Transform("uml/class-diagrams.xsl"), new XeFacet.Wrap(new Rules()), new XeFacet.Wrap(new XeFacet.Fixed(Compiler.decor())), new Transform("renumber.xsl"), new XeFacet.Wrap( spec -> new Directives().xpath("/*").attr( "msec", Long.toString(System.currentTimeMillis() - start) ) ), }; XML spec = new XMLDocument( "<?xml-stylesheet href='requs.xsl' type='text/xsl'?><spec/>" ); for (final Facet facet : facets) { spec = facet.touch(spec); Logger.info(this, "%s done", facet); } this.copy(); FileUtils.write( new File(this.output, "requs.xml"), new StrictXML(spec, Compiler.SCHEMA).toString(), StandardCharsets.UTF_8 ); Logger.info(this, "compiled and saved to %s", this.output); } | Compiler { public void compile() throws IOException { assert this.properties != null; final long start = System.currentTimeMillis(); final Facet[] facets = { new XeFacet.Wrap(new Aggregate(new File(this.input))), new XeFacet.Wrap(new AntlrFacet()), new Transform("cleanup/duplicate-step-numbers.xsl"), new Transform("cleanup/duplicate-step-signatures.xsl"), new Transform("cleanup/duplicate-step-objects.xsl"), new Transform("cleanup/duplicate-step-results.xsl"), new Transform("cleanup/lost-steps.xsl"), new Transform("cleanup/lost-methods.xsl"), new Transform("cleanup/duplicate-signatures.xsl"), new Transform("cleanup/duplicate-method-signatures.xsl"), new Transform("cleanup/duplicate-method-objects.xsl"), new Transform("cleanup/duplicate-method-bindings.xsl"), new Transform("cleanup/incomplete-step-object.xsl"), new Transform("cleanup/incomplete-step-signature.xsl"), new Transform("cleanup/incomplete-step-result.xsl"), new Transform("cleanup/incomplete-binding.xsl"), new Transform("cleanup/bindings-in-exception.xsl"), new Transform("seal-methods.xsl"), new Transform("sanity/signatures-check.xsl"), new Transform("sanity/types-check.xsl"), new Transform("sanity/seals-check.xsl"), new Transform("sanity/exception-rethrow-check.xsl"), new Transform("sanity/misplaced-failure-check.xsl"), new Transform("sanity/broken-order-of-steps.xsl"), new Transform("sanity/missed-step-numbers.xsl"), new Transform("sanity/too-many-steps.xsl"), new Transform("sanity/empty-re-throws.xsl"), new Transform("sanity/orphan-types.xsl"), new Transform("sanity/undeclared-bindings.xsl"), new Transform("sanity/actor-is-singleton.xsl"), new Transform("step-refs.xsl"), new Transform("methods-in-markdown.xsl"), new Transform("pages-in-html.xsl"), new Transform("count-ambiguity.xsl"), new Transform("find-tbds.xsl"), new Transform("uml/sequence-diagrams.xsl"), new Transform("uml/use-case-diagrams.xsl"), new Transform("uml/class-diagrams.xsl"), new XeFacet.Wrap(new Rules()), new XeFacet.Wrap(new XeFacet.Fixed(Compiler.decor())), new Transform("renumber.xsl"), new XeFacet.Wrap( spec -> new Directives().xpath("/*").attr( "msec", Long.toString(System.currentTimeMillis() - start) ) ), }; XML spec = new XMLDocument( "<?xml-stylesheet href='requs.xsl' type='text/xsl'?><spec/>" ); for (final Facet facet : facets) { spec = facet.touch(spec); Logger.info(this, "%s done", facet); } this.copy(); FileUtils.write( new File(this.output, "requs.xml"), new StrictXML(spec, Compiler.SCHEMA).toString(), StandardCharsets.UTF_8 ); Logger.info(this, "compiled and saved to %s", this.output); } } | Compiler { public void compile() throws IOException { assert this.properties != null; final long start = System.currentTimeMillis(); final Facet[] facets = { new XeFacet.Wrap(new Aggregate(new File(this.input))), new XeFacet.Wrap(new AntlrFacet()), new Transform("cleanup/duplicate-step-numbers.xsl"), new Transform("cleanup/duplicate-step-signatures.xsl"), new Transform("cleanup/duplicate-step-objects.xsl"), new Transform("cleanup/duplicate-step-results.xsl"), new Transform("cleanup/lost-steps.xsl"), new Transform("cleanup/lost-methods.xsl"), new Transform("cleanup/duplicate-signatures.xsl"), new Transform("cleanup/duplicate-method-signatures.xsl"), new Transform("cleanup/duplicate-method-objects.xsl"), new Transform("cleanup/duplicate-method-bindings.xsl"), new Transform("cleanup/incomplete-step-object.xsl"), new Transform("cleanup/incomplete-step-signature.xsl"), new Transform("cleanup/incomplete-step-result.xsl"), new Transform("cleanup/incomplete-binding.xsl"), new Transform("cleanup/bindings-in-exception.xsl"), new Transform("seal-methods.xsl"), new Transform("sanity/signatures-check.xsl"), new Transform("sanity/types-check.xsl"), new Transform("sanity/seals-check.xsl"), new Transform("sanity/exception-rethrow-check.xsl"), new Transform("sanity/misplaced-failure-check.xsl"), new Transform("sanity/broken-order-of-steps.xsl"), new Transform("sanity/missed-step-numbers.xsl"), new Transform("sanity/too-many-steps.xsl"), new Transform("sanity/empty-re-throws.xsl"), new Transform("sanity/orphan-types.xsl"), new Transform("sanity/undeclared-bindings.xsl"), new Transform("sanity/actor-is-singleton.xsl"), new Transform("step-refs.xsl"), new Transform("methods-in-markdown.xsl"), new Transform("pages-in-html.xsl"), new Transform("count-ambiguity.xsl"), new Transform("find-tbds.xsl"), new Transform("uml/sequence-diagrams.xsl"), new Transform("uml/use-case-diagrams.xsl"), new Transform("uml/class-diagrams.xsl"), new XeFacet.Wrap(new Rules()), new XeFacet.Wrap(new XeFacet.Fixed(Compiler.decor())), new Transform("renumber.xsl"), new XeFacet.Wrap( spec -> new Directives().xpath("/*").attr( "msec", Long.toString(System.currentTimeMillis() - start) ) ), }; XML spec = new XMLDocument( "<?xml-stylesheet href='requs.xsl' type='text/xsl'?><spec/>" ); for (final Facet facet : facets) { spec = facet.touch(spec); Logger.info(this, "%s done", facet); } this.copy(); FileUtils.write( new File(this.output, "requs.xml"), new StrictXML(spec, Compiler.SCHEMA).toString(), StandardCharsets.UTF_8 ); Logger.info(this, "compiled and saved to %s", this.output); } Compiler(final File src, final File dest); @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") Compiler(@NotNull final File src, @NotNull final File dest,
@NotNull final Map<String, String> props); } | Compiler { public void compile() throws IOException { assert this.properties != null; final long start = System.currentTimeMillis(); final Facet[] facets = { new XeFacet.Wrap(new Aggregate(new File(this.input))), new XeFacet.Wrap(new AntlrFacet()), new Transform("cleanup/duplicate-step-numbers.xsl"), new Transform("cleanup/duplicate-step-signatures.xsl"), new Transform("cleanup/duplicate-step-objects.xsl"), new Transform("cleanup/duplicate-step-results.xsl"), new Transform("cleanup/lost-steps.xsl"), new Transform("cleanup/lost-methods.xsl"), new Transform("cleanup/duplicate-signatures.xsl"), new Transform("cleanup/duplicate-method-signatures.xsl"), new Transform("cleanup/duplicate-method-objects.xsl"), new Transform("cleanup/duplicate-method-bindings.xsl"), new Transform("cleanup/incomplete-step-object.xsl"), new Transform("cleanup/incomplete-step-signature.xsl"), new Transform("cleanup/incomplete-step-result.xsl"), new Transform("cleanup/incomplete-binding.xsl"), new Transform("cleanup/bindings-in-exception.xsl"), new Transform("seal-methods.xsl"), new Transform("sanity/signatures-check.xsl"), new Transform("sanity/types-check.xsl"), new Transform("sanity/seals-check.xsl"), new Transform("sanity/exception-rethrow-check.xsl"), new Transform("sanity/misplaced-failure-check.xsl"), new Transform("sanity/broken-order-of-steps.xsl"), new Transform("sanity/missed-step-numbers.xsl"), new Transform("sanity/too-many-steps.xsl"), new Transform("sanity/empty-re-throws.xsl"), new Transform("sanity/orphan-types.xsl"), new Transform("sanity/undeclared-bindings.xsl"), new Transform("sanity/actor-is-singleton.xsl"), new Transform("step-refs.xsl"), new Transform("methods-in-markdown.xsl"), new Transform("pages-in-html.xsl"), new Transform("count-ambiguity.xsl"), new Transform("find-tbds.xsl"), new Transform("uml/sequence-diagrams.xsl"), new Transform("uml/use-case-diagrams.xsl"), new Transform("uml/class-diagrams.xsl"), new XeFacet.Wrap(new Rules()), new XeFacet.Wrap(new XeFacet.Fixed(Compiler.decor())), new Transform("renumber.xsl"), new XeFacet.Wrap( spec -> new Directives().xpath("/*").attr( "msec", Long.toString(System.currentTimeMillis() - start) ) ), }; XML spec = new XMLDocument( "<?xml-stylesheet href='requs.xsl' type='text/xsl'?><spec/>" ); for (final Facet facet : facets) { spec = facet.touch(spec); Logger.info(this, "%s done", facet); } this.copy(); FileUtils.write( new File(this.output, "requs.xml"), new StrictXML(spec, Compiler.SCHEMA).toString(), StandardCharsets.UTF_8 ); Logger.info(this, "compiled and saved to %s", this.output); } Compiler(final File src, final File dest); @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") Compiler(@NotNull final File src, @NotNull final File dest,
@NotNull final Map<String, String> props); void compile(); } | Compiler { public void compile() throws IOException { assert this.properties != null; final long start = System.currentTimeMillis(); final Facet[] facets = { new XeFacet.Wrap(new Aggregate(new File(this.input))), new XeFacet.Wrap(new AntlrFacet()), new Transform("cleanup/duplicate-step-numbers.xsl"), new Transform("cleanup/duplicate-step-signatures.xsl"), new Transform("cleanup/duplicate-step-objects.xsl"), new Transform("cleanup/duplicate-step-results.xsl"), new Transform("cleanup/lost-steps.xsl"), new Transform("cleanup/lost-methods.xsl"), new Transform("cleanup/duplicate-signatures.xsl"), new Transform("cleanup/duplicate-method-signatures.xsl"), new Transform("cleanup/duplicate-method-objects.xsl"), new Transform("cleanup/duplicate-method-bindings.xsl"), new Transform("cleanup/incomplete-step-object.xsl"), new Transform("cleanup/incomplete-step-signature.xsl"), new Transform("cleanup/incomplete-step-result.xsl"), new Transform("cleanup/incomplete-binding.xsl"), new Transform("cleanup/bindings-in-exception.xsl"), new Transform("seal-methods.xsl"), new Transform("sanity/signatures-check.xsl"), new Transform("sanity/types-check.xsl"), new Transform("sanity/seals-check.xsl"), new Transform("sanity/exception-rethrow-check.xsl"), new Transform("sanity/misplaced-failure-check.xsl"), new Transform("sanity/broken-order-of-steps.xsl"), new Transform("sanity/missed-step-numbers.xsl"), new Transform("sanity/too-many-steps.xsl"), new Transform("sanity/empty-re-throws.xsl"), new Transform("sanity/orphan-types.xsl"), new Transform("sanity/undeclared-bindings.xsl"), new Transform("sanity/actor-is-singleton.xsl"), new Transform("step-refs.xsl"), new Transform("methods-in-markdown.xsl"), new Transform("pages-in-html.xsl"), new Transform("count-ambiguity.xsl"), new Transform("find-tbds.xsl"), new Transform("uml/sequence-diagrams.xsl"), new Transform("uml/use-case-diagrams.xsl"), new Transform("uml/class-diagrams.xsl"), new XeFacet.Wrap(new Rules()), new XeFacet.Wrap(new XeFacet.Fixed(Compiler.decor())), new Transform("renumber.xsl"), new XeFacet.Wrap( spec -> new Directives().xpath("/*").attr( "msec", Long.toString(System.currentTimeMillis() - start) ) ), }; XML spec = new XMLDocument( "<?xml-stylesheet href='requs.xsl' type='text/xsl'?><spec/>" ); for (final Facet facet : facets) { spec = facet.touch(spec); Logger.info(this, "%s done", facet); } this.copy(); FileUtils.write( new File(this.output, "requs.xml"), new StrictXML(spec, Compiler.SCHEMA).toString(), StandardCharsets.UTF_8 ); Logger.info(this, "compiled and saved to %s", this.output); } Compiler(final File src, final File dest); @SuppressWarnings("PMD.ConstructorOnlyInitializesOrCallOtherConstructors") Compiler(@NotNull final File src, @NotNull final File dest,
@NotNull final Map<String, String> props); void compile(); static final XSD SCHEMA; } |
@Test public void setsAttributes() throws Exception { final Directives dirs = new Directives().add("x"); final Method method = new XeMethod(dirs, "/x"); final String name = "attr-1"; method.attribute(name, ""); method.attribute(name, "ffa7ed"); method.attribute("another", "123456"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/x/attributes[count(attribute)=2]", "/x/attributes[attribute='attr-1' and attribute='another']", "/x/attributes/attribute[.='attr-1' and @seal='ffa7ed']" ) ); } | @Override public void attribute(final String name, final String seal) { this.dirs.xpath(this.start) .strict(1) .addIf("attributes") .xpath( String.format( "%s/attributes[not(attribute=%s)]", this.start, XeOntology.escapeXPath(name) ) ) .add("attribute").set(name) .xpath( String.format( "%s/attributes/attribute[.=%s]", this.start, XeOntology.escapeXPath(name) ) ) .strict(1) .attr("seal", seal); } | XeMethod implements Method { @Override public void attribute(final String name, final String seal) { this.dirs.xpath(this.start) .strict(1) .addIf("attributes") .xpath( String.format( "%s/attributes[not(attribute=%s)]", this.start, XeOntology.escapeXPath(name) ) ) .add("attribute").set(name) .xpath( String.format( "%s/attributes/attribute[.=%s]", this.start, XeOntology.escapeXPath(name) ) ) .strict(1) .attr("seal", seal); } } | XeMethod implements Method { @Override public void attribute(final String name, final String seal) { this.dirs.xpath(this.start) .strict(1) .addIf("attributes") .xpath( String.format( "%s/attributes[not(attribute=%s)]", this.start, XeOntology.escapeXPath(name) ) ) .add("attribute").set(name) .xpath( String.format( "%s/attributes/attribute[.=%s]", this.start, XeOntology.escapeXPath(name) ) ) .strict(1) .attr("seal", seal); } XeMethod(final Directives directives, final String xpath); } | XeMethod implements Method { @Override public void attribute(final String name, final String seal) { this.dirs.xpath(this.start) .strict(1) .addIf("attributes") .xpath( String.format( "%s/attributes[not(attribute=%s)]", this.start, XeOntology.escapeXPath(name) ) ) .add("attribute").set(name) .xpath( String.format( "%s/attributes/attribute[.=%s]", this.start, XeOntology.escapeXPath(name) ) ) .strict(1) .attr("seal", seal); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); } | XeMethod implements Method { @Override public void attribute(final String name, final String seal) { this.dirs.xpath(this.start) .strict(1) .addIf("attributes") .xpath( String.format( "%s/attributes[not(attribute=%s)]", this.start, XeOntology.escapeXPath(name) ) ) .add("attribute").set(name) .xpath( String.format( "%s/attributes/attribute[.=%s]", this.start, XeOntology.escapeXPath(name) ) ) .strict(1) .attr("seal", seal); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); } |
@Test public void manipulatesWithTypesAndUseCases() throws Exception { final XeOntology onto = new XeOntology(); final Type type = onto.type("First"); type.explain("first text"); type.parent("Root"); type.slot("one").assign("Emp"); onto.type("Second").explain("second text"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPaths( "/spec", "/spec/types/type[name='First']", "/spec/types/type[name='Second']" ) ); } | @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); } |
@Test public void avoidsDuplication() throws Exception { final XeOntology onto = new XeOntology(); final String name = "Alpha"; onto.type(name); onto.type(name); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPath("/spec/types[count(type)=1]") ); } | @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); } | XeOntology implements Ontology { @Override public Type type(final String name) { this.root("types") .xpath( String.format( "/spec/types[not(type/name=%s)]", XeOntology.escapeXPath(name) ) ) .add("type").add("name").set(name); return new XeType( this.dirs, String.format( "/spec/types/type[name=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); } |
@Test public void avoidsDuplicationOfMethods() throws Exception { final XeOntology onto = new XeOntology(); final String name = "UC3"; onto.method(name); onto.method(name); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(onto).xml()), XhtmlMatchers.hasXPath("/spec/methods[count(method)=1]") ); } | @Override public Method method(final String name) { this.root("methods") .xpath( String.format( "/spec/methods[not(method/id=%s)]", XeOntology.escapeXPath(name) ) ) .add("method").add("id").set(name); return new XeMethod( this.dirs, String.format( "/spec/methods/method[id=%s]", XeOntology.escapeXPath(name) ) ); } | XeOntology implements Ontology { @Override public Method method(final String name) { this.root("methods") .xpath( String.format( "/spec/methods[not(method/id=%s)]", XeOntology.escapeXPath(name) ) ) .add("method").add("id").set(name); return new XeMethod( this.dirs, String.format( "/spec/methods/method[id=%s]", XeOntology.escapeXPath(name) ) ); } } | XeOntology implements Ontology { @Override public Method method(final String name) { this.root("methods") .xpath( String.format( "/spec/methods[not(method/id=%s)]", XeOntology.escapeXPath(name) ) ) .add("method").add("id").set(name); return new XeMethod( this.dirs, String.format( "/spec/methods/method[id=%s]", XeOntology.escapeXPath(name) ) ); } } | XeOntology implements Ontology { @Override public Method method(final String name) { this.root("methods") .xpath( String.format( "/spec/methods[not(method/id=%s)]", XeOntology.escapeXPath(name) ) ) .add("method").add("id").set(name); return new XeMethod( this.dirs, String.format( "/spec/methods/method[id=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); } | XeOntology implements Ontology { @Override public Method method(final String name) { this.root("methods") .xpath( String.format( "/spec/methods[not(method/id=%s)]", XeOntology.escapeXPath(name) ) ) .add("method").add("id").set(name); return new XeMethod( this.dirs, String.format( "/spec/methods/method[id=%s]", XeOntology.escapeXPath(name) ) ); } @Override Type type(final String name); @Override Method method(final String name); @Override Page page(final String name); @Override Acronym acronym(final String name); @Override Iterator<Directive> iterator(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String escapeXPath(final String text); } |
@Test public void manipulatesWithBindings() throws Exception { final Directives dirs = new Directives().add("f"); final Flow flow = new XeFlow(dirs, "/f"); flow.binding("emp", "Employee"); flow.binding("one", "One"); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/f/bindings/binding[name='emp' and type='Employee']", "/f/bindings/binding[name='one' and type='One']" ) ); } | @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void explain(final String info); } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void explain(final String info); } |
@Test public void avoidsDuplicateBindings() throws Exception { final Directives dirs = new Directives().add("f1"); final Flow flow = new XeFlow(dirs, "/f1"); for (int idx = 0; idx < Tv.FIVE; ++idx) { flow.binding("a", "alpha"); } MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/f1/bindings[count(binding)=1]", "/f1/bindings/binding[name='a' and type='alpha']" ) ); } | @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void explain(final String info); } | XeFlow implements Flow { @Override public void binding(final String name, final String type) { this.dirs.xpath(this.start).strict(1).addIf("bindings").up().xpath( String.format( "bindings[not(binding[name='%s' and type=%s])]", name, XeOntology.escapeXPath(type) ) ).add("binding").add("name").set(name).up().add("type").set(type); } XeFlow(final Directives directives, final String xpath); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void explain(final String info); } |
@Test public void checksSeals() { MatcherAssert.assertThat( XhtmlMatchers.xhtml( new Transform("sanity/seals-check.xsl").touch( new XMLDocument( StringUtils.join( "<spec><method seal='a12ef4'>", "<id>UC5</id><attributes>", "<attribute seal='b89e4e'>invalid</attribute>", "<attribute seal='a12ef4'>valid</attribute>", "</attributes></method><errors/></spec>" ) ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors[count(error)=1]", "/spec/errors/error[contains(.,'a12ef4')]" ) ); } | @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); @Override XML touch(final XML spec); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); @Override XML touch(final XML spec); } |
@Test public void checksTypes() { MatcherAssert.assertThat( XhtmlMatchers.xhtml( new Transform("sanity/types-check.xsl").touch( new XMLDocument( StringUtils.join( "<spec><types><type><name>User</name>", "<slots><slot><type>Alpha</type></slot></slots>", "</type></types><methods><method><bindings>", "<binding><type>Beta</type></binding>", "</bindings></method></methods><errors/></spec>" ) ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors[count(error)=2]", "/spec/errors/error[contains(.,'Alpha')]" ) ); } | @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); @Override XML touch(final XML spec); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); @Override XML touch(final XML spec); } |
@Test public void checksSignatures() { MatcherAssert.assertThat( XhtmlMatchers.xhtml( new Transform("sanity/signatures-check.xsl").touch( new XMLDocument( StringUtils.join( "<spec><methods><method><signature>abc</signature>", "</method><method><steps><step><signature>cde", "</signature></step></steps></method></methods>", "<errors/></spec>" ) ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors[count(error)=1 ]", "/spec/errors/error[contains(.,'cde')]" ) ); } | @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); @Override XML touch(final XML spec); } | Transform implements Facet { @Override public XML touch(final XML spec) { final URL url = Transform.class.getResource(this.sheet); if (url == null) { throw new IllegalArgumentException( String.format("stylesheet '%s' not found", this.sheet) ); } return XSLDocument.make(url) .with(new ClasspathSources(this.getClass())) .transform(spec); } Transform(final String xsl); @Override XML touch(final XML spec); } |
@Test public void buildsSvg() throws IOException { Assume.assumeFalse(SystemUtils.IS_OS_WINDOWS); MatcherAssert.assertThat( XhtmlMatchers.xhtml( Plant.svg("@startuml\nBob -> Alice : hello\n@enduml\n") ), XhtmlMatchers.hasXPath(" ); } | @SuppressWarnings("PMD.ProhibitPublicStaticMethods") public static String svg(final String src) throws IOException { final String svg; if (SystemUtils.IS_OS_WINDOWS) { svg = "<p>SVG can't be rendered in Windows</p>"; } else { final SourceStringReader reader = new SourceStringReader(src); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); reader.generateImage(baos, new FileFormatOption(FileFormat.SVG)); svg = new XMLDocument( new String(baos.toByteArray()) ).nodes("/*").get(0).toString().replace("xmlns=\"\"", ""); } return svg; } | Plant { @SuppressWarnings("PMD.ProhibitPublicStaticMethods") public static String svg(final String src) throws IOException { final String svg; if (SystemUtils.IS_OS_WINDOWS) { svg = "<p>SVG can't be rendered in Windows</p>"; } else { final SourceStringReader reader = new SourceStringReader(src); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); reader.generateImage(baos, new FileFormatOption(FileFormat.SVG)); svg = new XMLDocument( new String(baos.toByteArray()) ).nodes("/*").get(0).toString().replace("xmlns=\"\"", ""); } return svg; } } | Plant { @SuppressWarnings("PMD.ProhibitPublicStaticMethods") public static String svg(final String src) throws IOException { final String svg; if (SystemUtils.IS_OS_WINDOWS) { svg = "<p>SVG can't be rendered in Windows</p>"; } else { final SourceStringReader reader = new SourceStringReader(src); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); reader.generateImage(baos, new FileFormatOption(FileFormat.SVG)); svg = new XMLDocument( new String(baos.toByteArray()) ).nodes("/*").get(0).toString().replace("xmlns=\"\"", ""); } return svg; } private Plant(); } | Plant { @SuppressWarnings("PMD.ProhibitPublicStaticMethods") public static String svg(final String src) throws IOException { final String svg; if (SystemUtils.IS_OS_WINDOWS) { svg = "<p>SVG can't be rendered in Windows</p>"; } else { final SourceStringReader reader = new SourceStringReader(src); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); reader.generateImage(baos, new FileFormatOption(FileFormat.SVG)); svg = new XMLDocument( new String(baos.toByteArray()) ).nodes("/*").get(0).toString().replace("xmlns=\"\"", ""); } return svg; } private Plant(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String svg(final String src); } | Plant { @SuppressWarnings("PMD.ProhibitPublicStaticMethods") public static String svg(final String src) throws IOException { final String svg; if (SystemUtils.IS_OS_WINDOWS) { svg = "<p>SVG can't be rendered in Windows</p>"; } else { final SourceStringReader reader = new SourceStringReader(src); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); reader.generateImage(baos, new FileFormatOption(FileFormat.SVG)); svg = new XMLDocument( new String(baos.toByteArray()) ).nodes("/*").get(0).toString().replace("xmlns=\"\"", ""); } return svg; } private Plant(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static String svg(final String src); } |
@Test public void checksInput() throws Exception { MatcherAssert.assertThat( new CascadingRule().enforce("hey\n works\n fine\nstart"), Matchers.empty() ); } | @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> enforce(final String text); } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> enforce(final String text); } |
@Test public void displaysVersionNumber() throws Exception { Main.main(new String[]{"-v"}); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("-SNAPSHOT") ); } | private Main() { } | Main { private Main() { } } | Main { private Main() { } private Main(); } | Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); } | Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); } |
@Test public void rendersHelpMessage() throws Exception { Main.main(new String[] {"-h"}); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("Usage:") ); } | private Main() { } | Main { private Main() { } } | Main { private Main() { } private Main(); } | Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); } | Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); } |
@Test public void compilesRequsSources() throws Exception { final File input = this.temp.newFolder(); final File output = this.temp.newFolder(); FileUtils.write( new File(input, "employee.req"), "Employee is a \"user of the system\".", StandardCharsets.UTF_8 ); Main.main( new String[] { "-i", input.getAbsolutePath(), "-o", output.getAbsolutePath(), } ); MatcherAssert.assertThat( this.out.toString(), Matchers.containsString("compiled and saved to") ); MatcherAssert.assertThat( XhtmlMatchers.xhtml( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ), XhtmlMatchers.hasXPaths("/spec/types/type[name='Employee']") ); } | private Main() { } | Main { private Main() { } } | Main { private Main() { } private Main(); } | Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); } | Main { private Main() { } private Main(); @SuppressWarnings("PMD.ProhibitPublicStaticMethods") static void main(final String... args); } |
@Test public void processesRequsSpec() throws Exception { final InstantRs res = new InstantRs(); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); final SecurityContext sec = Mockito.mock(SecurityContext.class); res.setSecurityContext(sec); final String json = res.post("User is a \"type\"."); MatcherAssert.assertThat( Json.createReader(new StringReader(json)) .readObject().getString("spec"), XhtmlMatchers.hasXPath("/spec/types/type[name='User']") ); } | @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") public String post(@NotNull @FormParam("text") final String text) throws IOException { final File input = Files.createTempDir(); FileUtils.write( new File(input, "in.req"), text, StandardCharsets.UTF_8 ); final File output = Files.createTempDir(); try { new org.requs.Compiler(input, output).compile(); final XML xml = new XMLDocument( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ); final XSL xsl = new XSLDocument( FileUtils.readFileToString( new File(output, "requs.xsl"), StandardCharsets.UTF_8 ) ); return Json.createObjectBuilder() .add("spec", xml.nodes("/spec").get(0).toString()) .add("html", xsl.applyTo(xml)) .build().toString(); } catch (final RuntimeException ex) { throw new WebApplicationException( Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity(ExceptionUtils.getStackTrace(ex)) .build() ); } finally { FileUtils.deleteDirectory(input); FileUtils.deleteDirectory(output); } } | InstantRs extends BaseRs { @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") public String post(@NotNull @FormParam("text") final String text) throws IOException { final File input = Files.createTempDir(); FileUtils.write( new File(input, "in.req"), text, StandardCharsets.UTF_8 ); final File output = Files.createTempDir(); try { new org.requs.Compiler(input, output).compile(); final XML xml = new XMLDocument( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ); final XSL xsl = new XSLDocument( FileUtils.readFileToString( new File(output, "requs.xsl"), StandardCharsets.UTF_8 ) ); return Json.createObjectBuilder() .add("spec", xml.nodes("/spec").get(0).toString()) .add("html", xsl.applyTo(xml)) .build().toString(); } catch (final RuntimeException ex) { throw new WebApplicationException( Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity(ExceptionUtils.getStackTrace(ex)) .build() ); } finally { FileUtils.deleteDirectory(input); FileUtils.deleteDirectory(output); } } } | InstantRs extends BaseRs { @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") public String post(@NotNull @FormParam("text") final String text) throws IOException { final File input = Files.createTempDir(); FileUtils.write( new File(input, "in.req"), text, StandardCharsets.UTF_8 ); final File output = Files.createTempDir(); try { new org.requs.Compiler(input, output).compile(); final XML xml = new XMLDocument( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ); final XSL xsl = new XSLDocument( FileUtils.readFileToString( new File(output, "requs.xsl"), StandardCharsets.UTF_8 ) ); return Json.createObjectBuilder() .add("spec", xml.nodes("/spec").get(0).toString()) .add("html", xsl.applyTo(xml)) .build().toString(); } catch (final RuntimeException ex) { throw new WebApplicationException( Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity(ExceptionUtils.getStackTrace(ex)) .build() ); } finally { FileUtils.deleteDirectory(input); FileUtils.deleteDirectory(output); } } } | InstantRs extends BaseRs { @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") public String post(@NotNull @FormParam("text") final String text) throws IOException { final File input = Files.createTempDir(); FileUtils.write( new File(input, "in.req"), text, StandardCharsets.UTF_8 ); final File output = Files.createTempDir(); try { new org.requs.Compiler(input, output).compile(); final XML xml = new XMLDocument( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ); final XSL xsl = new XSLDocument( FileUtils.readFileToString( new File(output, "requs.xsl"), StandardCharsets.UTF_8 ) ); return Json.createObjectBuilder() .add("spec", xml.nodes("/spec").get(0).toString()) .add("html", xsl.applyTo(xml)) .build().toString(); } catch (final RuntimeException ex) { throw new WebApplicationException( Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity(ExceptionUtils.getStackTrace(ex)) .build() ); } finally { FileUtils.deleteDirectory(input); FileUtils.deleteDirectory(output); } } @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") String post(@NotNull @FormParam("text") final String text); } | InstantRs extends BaseRs { @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") public String post(@NotNull @FormParam("text") final String text) throws IOException { final File input = Files.createTempDir(); FileUtils.write( new File(input, "in.req"), text, StandardCharsets.UTF_8 ); final File output = Files.createTempDir(); try { new org.requs.Compiler(input, output).compile(); final XML xml = new XMLDocument( FileUtils.readFileToString( new File(output, "requs.xml"), StandardCharsets.UTF_8 ) ); final XSL xsl = new XSLDocument( FileUtils.readFileToString( new File(output, "requs.xsl"), StandardCharsets.UTF_8 ) ); return Json.createObjectBuilder() .add("spec", xml.nodes("/spec").get(0).toString()) .add("html", xsl.applyTo(xml)) .build().toString(); } catch (final RuntimeException ex) { throw new WebApplicationException( Response.status(HttpURLConnection.HTTP_INTERNAL_ERROR) .entity(ExceptionUtils.getStackTrace(ex)) .build() ); } finally { FileUtils.deleteDirectory(input); FileUtils.deleteDirectory(output); } } @POST @Path("/") @Produces(MediaType.APPLICATION_JSON) @Loggable @SuppressWarnings("PMD.AvoidCatchingGenericException") String post(@NotNull @FormParam("text") final String text); } |
@Test public void rendersFrontPage() throws Exception { final IndexRs res = new IndexRs(); res.setUriInfo(new UriInfoMocker().mock()); res.setHttpHeaders(new HttpHeadersMocker().mock()); final SecurityContext sec = Mockito.mock(SecurityContext.class); res.setSecurityContext(sec); final Response response = res.index(); MatcherAssert.assertThat( JaxbConverter.the(response.getEntity()), XhtmlMatchers.hasXPaths( "/page/millis", "/page/version/name" ) ); } | @GET @Path("/") public Response index() throws Exception { return new PageBuilder() .stylesheet("/xsl/index.xsl") .build(DemoPage.class) .init(this) .render() .build(); } | IndexRs extends BaseRs { @GET @Path("/") public Response index() throws Exception { return new PageBuilder() .stylesheet("/xsl/index.xsl") .build(DemoPage.class) .init(this) .render() .build(); } } | IndexRs extends BaseRs { @GET @Path("/") public Response index() throws Exception { return new PageBuilder() .stylesheet("/xsl/index.xsl") .build(DemoPage.class) .init(this) .render() .build(); } } | IndexRs extends BaseRs { @GET @Path("/") public Response index() throws Exception { return new PageBuilder() .stylesheet("/xsl/index.xsl") .build(DemoPage.class) .init(this) .render() .build(); } @GET @Path("/") Response index(); } | IndexRs extends BaseRs { @GET @Path("/") public Response index() throws Exception { return new PageBuilder() .stylesheet("/xsl/index.xsl") .build(DemoPage.class) .init(this) .render() .build(); } @GET @Path("/") Response index(); } |
@Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new CascadingRule().enforce( "\n\n\n hey\n three!" ).iterator().next().line(), Matchers.equalTo(Tv.FIVE) ); } | @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> enforce(final String text); } | CascadingRule implements Rule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> enforce(final String text) { final String[] lines = StringUtils.splitPreserveAllTokens(text, '\n'); final Collection<Violation> violations = new LinkedList<>(); int indent = 0; for (int idx = 0; idx < lines.length; ++idx) { final int next = CascadingRule.indent(lines[idx]); if (indent > 0 && next > indent && next != indent + 2) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, while %d required: [%s]", next, indent + 2, lines[idx] ), idx + 1, next ) ); } indent = next; } return violations; } @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> enforce(final String text); } |
@Test public void checksInput() throws IOException { MatcherAssert.assertThat( new XeFacet.Wrap(new Rules()).touch( new XMLDocument( StringUtils.join( "<spec><input>", "User is\ta "human being". ", "</input></spec>" ) ) ), XhtmlMatchers.hasXPaths( "/spec/errors", "/spec/errors[count(error)>2]" ) ); } | @Override public Iterable<Directive> touch(final XML spec) { final Rule[] rules = { new LineRule.Wrap( new RegexRule( "[^ ] +$", "trailing space(s) at the end of line" ) ), new LineRule.Wrap( new RegexRule( "[^ ] {2,}", "avoid two or more consecutive spaces" ) ), new LineRule.Wrap( new RegexRule( ".{81,}", "avoid lines longer than 80 characters" ) ), new LineRule.Wrap( new RegexRule( "\t", "avoid TAB characters, use four spaces instead" ) ), new LineRule.Wrap( new RegexRule( "\r", "don't use Windows line-endings" ) ), new LineRule.Wrap( new RegexRule( ",[^$ \n\r]", "always use space after comma" ) ), new LineRule.Wrap( new RegexRule( ";[^$ ]", "always use space after semicolon" ) ), new LineRule.Wrap(new IndentationRule()), new CascadingRule(), }; final String input; if (spec.nodes("/spec/input[.!='']").isEmpty()) { input = ""; } else { input = spec.xpath("/spec/input/text()").get(0); } final Directives dirs = new Directives().xpath("/spec").addIf("errors"); for (final Rule rule : rules) { for (final Violation violation : rule.enforce(input)) { dirs.add("error") .attr("pos", Integer.toString(violation.position())) .attr("line", Integer.toString(violation.line())) .set(violation.details()).up(); } } return dirs; } | Rules implements XeFacet { @Override public Iterable<Directive> touch(final XML spec) { final Rule[] rules = { new LineRule.Wrap( new RegexRule( "[^ ] +$", "trailing space(s) at the end of line" ) ), new LineRule.Wrap( new RegexRule( "[^ ] {2,}", "avoid two or more consecutive spaces" ) ), new LineRule.Wrap( new RegexRule( ".{81,}", "avoid lines longer than 80 characters" ) ), new LineRule.Wrap( new RegexRule( "\t", "avoid TAB characters, use four spaces instead" ) ), new LineRule.Wrap( new RegexRule( "\r", "don't use Windows line-endings" ) ), new LineRule.Wrap( new RegexRule( ",[^$ \n\r]", "always use space after comma" ) ), new LineRule.Wrap( new RegexRule( ";[^$ ]", "always use space after semicolon" ) ), new LineRule.Wrap(new IndentationRule()), new CascadingRule(), }; final String input; if (spec.nodes("/spec/input[.!='']").isEmpty()) { input = ""; } else { input = spec.xpath("/spec/input/text()").get(0); } final Directives dirs = new Directives().xpath("/spec").addIf("errors"); for (final Rule rule : rules) { for (final Violation violation : rule.enforce(input)) { dirs.add("error") .attr("pos", Integer.toString(violation.position())) .attr("line", Integer.toString(violation.line())) .set(violation.details()).up(); } } return dirs; } } | Rules implements XeFacet { @Override public Iterable<Directive> touch(final XML spec) { final Rule[] rules = { new LineRule.Wrap( new RegexRule( "[^ ] +$", "trailing space(s) at the end of line" ) ), new LineRule.Wrap( new RegexRule( "[^ ] {2,}", "avoid two or more consecutive spaces" ) ), new LineRule.Wrap( new RegexRule( ".{81,}", "avoid lines longer than 80 characters" ) ), new LineRule.Wrap( new RegexRule( "\t", "avoid TAB characters, use four spaces instead" ) ), new LineRule.Wrap( new RegexRule( "\r", "don't use Windows line-endings" ) ), new LineRule.Wrap( new RegexRule( ",[^$ \n\r]", "always use space after comma" ) ), new LineRule.Wrap( new RegexRule( ";[^$ ]", "always use space after semicolon" ) ), new LineRule.Wrap(new IndentationRule()), new CascadingRule(), }; final String input; if (spec.nodes("/spec/input[.!='']").isEmpty()) { input = ""; } else { input = spec.xpath("/spec/input/text()").get(0); } final Directives dirs = new Directives().xpath("/spec").addIf("errors"); for (final Rule rule : rules) { for (final Violation violation : rule.enforce(input)) { dirs.add("error") .attr("pos", Integer.toString(violation.position())) .attr("line", Integer.toString(violation.line())) .set(violation.details()).up(); } } return dirs; } } | Rules implements XeFacet { @Override public Iterable<Directive> touch(final XML spec) { final Rule[] rules = { new LineRule.Wrap( new RegexRule( "[^ ] +$", "trailing space(s) at the end of line" ) ), new LineRule.Wrap( new RegexRule( "[^ ] {2,}", "avoid two or more consecutive spaces" ) ), new LineRule.Wrap( new RegexRule( ".{81,}", "avoid lines longer than 80 characters" ) ), new LineRule.Wrap( new RegexRule( "\t", "avoid TAB characters, use four spaces instead" ) ), new LineRule.Wrap( new RegexRule( "\r", "don't use Windows line-endings" ) ), new LineRule.Wrap( new RegexRule( ",[^$ \n\r]", "always use space after comma" ) ), new LineRule.Wrap( new RegexRule( ";[^$ ]", "always use space after semicolon" ) ), new LineRule.Wrap(new IndentationRule()), new CascadingRule(), }; final String input; if (spec.nodes("/spec/input[.!='']").isEmpty()) { input = ""; } else { input = spec.xpath("/spec/input/text()").get(0); } final Directives dirs = new Directives().xpath("/spec").addIf("errors"); for (final Rule rule : rules) { for (final Violation violation : rule.enforce(input)) { dirs.add("error") .attr("pos", Integer.toString(violation.position())) .attr("line", Integer.toString(violation.line())) .set(violation.details()).up(); } } return dirs; } @Override Iterable<Directive> touch(final XML spec); } | Rules implements XeFacet { @Override public Iterable<Directive> touch(final XML spec) { final Rule[] rules = { new LineRule.Wrap( new RegexRule( "[^ ] +$", "trailing space(s) at the end of line" ) ), new LineRule.Wrap( new RegexRule( "[^ ] {2,}", "avoid two or more consecutive spaces" ) ), new LineRule.Wrap( new RegexRule( ".{81,}", "avoid lines longer than 80 characters" ) ), new LineRule.Wrap( new RegexRule( "\t", "avoid TAB characters, use four spaces instead" ) ), new LineRule.Wrap( new RegexRule( "\r", "don't use Windows line-endings" ) ), new LineRule.Wrap( new RegexRule( ",[^$ \n\r]", "always use space after comma" ) ), new LineRule.Wrap( new RegexRule( ";[^$ ]", "always use space after semicolon" ) ), new LineRule.Wrap(new IndentationRule()), new CascadingRule(), }; final String input; if (spec.nodes("/spec/input[.!='']").isEmpty()) { input = ""; } else { input = spec.xpath("/spec/input/text()").get(0); } final Directives dirs = new Directives().xpath("/spec").addIf("errors"); for (final Rule rule : rules) { for (final Violation violation : rule.enforce(input)) { dirs.add("error") .attr("pos", Integer.toString(violation.position())) .attr("line", Integer.toString(violation.line())) .set(violation.details()).up(); } } return dirs; } @Override Iterable<Directive> touch(final XML spec); } |
@Test public void checksInput() throws Exception { MatcherAssert.assertThat( new IndentationRule().check(" works fine"), Matchers.empty() ); } | @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } @Override Collection<Violation> check(final String line); } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } @Override Collection<Violation> check(final String line); } |
@Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new IndentationRule().check(" works fine"), Matchers.not(Matchers.empty()) ); } | @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } @Override Collection<Violation> check(final String line); } | IndentationRule implements LineRule { @Override public Collection<Violation> check(final String line) { int indent; for (indent = 0; indent < line.length(); ++indent) { if (line.charAt(indent) != ' ') { break; } } final Collection<Violation> violations = new LinkedList<>(); if (indent % 2 != 0) { violations.add( new Violation.Simple( String.format( "indented for %d spaces, must be either %d or %d: [%s]", indent, indent >> 1 << 1, indent + 1 >> 1 << 1, line ), 0, indent ) ); } return violations; } @Override Collection<Violation> check(final String line); } |
@Test public void checksInput() throws Exception { MatcherAssert.assertThat( new RegexRule("[a-z]+", "").check("abjkljeklsf"), Matchers.not(Matchers.empty()) ); } | @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> check(final String line); } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> check(final String line); } |
@Test public void checksInvalidInput() throws Exception { MatcherAssert.assertThat( new RegexRule("[0-9]", "").check("broken input"), Matchers.empty() ); } | @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> check(final String line); } | RegexRule implements LineRule { @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") public Collection<Violation> check(final String line) { final Pattern ptn = Pattern.compile(this.regex); final Matcher matcher = ptn.matcher(line); final Collection<Violation> violations = new LinkedList<>(); while (matcher.find()) { violations.add( new Violation.Simple( String.format("%s: [%s]", this.text, line), 0, matcher.start() + 1 ) ); } return violations; } RegexRule(final String rgx, final String txt); @Override @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops") Collection<Violation> check(final String line); } |
@Test public void signsMethod() throws Exception { final Directives dirs = new Directives().add("s"); final Signature signature = new XeSignature(dirs, "/s"); signature.sign("\"informal one\""); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPaths( "/s[signature='\"informal one\"']" ) ); } | @Override public void sign(final String text) { this.dirs.xpath(this.start).strict(1) .add("signature").set(text); } | XeSignature implements Signature { @Override public void sign(final String text) { this.dirs.xpath(this.start).strict(1) .add("signature").set(text); } } | XeSignature implements Signature { @Override public void sign(final String text) { this.dirs.xpath(this.start).strict(1) .add("signature").set(text); } XeSignature(final Directives directives, final String xpath); } | XeSignature implements Signature { @Override public void sign(final String text) { this.dirs.xpath(this.start).strict(1) .add("signature").set(text); } XeSignature(final Directives directives, final String xpath); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override void input(final String name); @Override void explain(final String info); } | XeSignature implements Signature { @Override public void sign(final String text) { this.dirs.xpath(this.start).strict(1) .add("signature").set(text); } XeSignature(final Directives directives, final String xpath); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override void input(final String name); @Override void explain(final String info); } |
@Test public void avoidsDuplicateSteps() throws Exception { final Directives dirs = new Directives().add("mtd"); final Method method = new XeMethod(dirs, "/mtd"); method.step(1); method.step(1); MatcherAssert.assertThat( XhtmlMatchers.xhtml(new Xembler(dirs).xml()), XhtmlMatchers.hasXPath("/mtd/steps[count(step)=1]") ); } | @Override public Step step(final int number) { return this.flow.step(number); } | XeMethod implements Method { @Override public Step step(final int number) { return this.flow.step(number); } } | XeMethod implements Method { @Override public Step step(final int number) { return this.flow.step(number); } XeMethod(final Directives directives, final String xpath); } | XeMethod implements Method { @Override public Step step(final int number) { return this.flow.step(number); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); } | XeMethod implements Method { @Override public Step step(final int number) { return this.flow.step(number); } XeMethod(final Directives directives, final String xpath); @Override void attribute(final String name, final String seal); @Override Nfr nfr(final String name); @Override void sign(final String text); @Override void object(final String name); @Override void result(final String name); @Override Step step(final int number); @Override void binding(final String name, final String type); @Override void input(final String name); @Override void explain(final String info); @Override void mention(final int where); } |
@Test(dataProvider = "parametricStateTestDP") public void parametricStateTest(int originalBase, State s) { ParametricState ts = new ParametricState(s); State s1 = ts.createActualState(originalBase); assert Arrays.equals(s.getMemberPositions(), s1.getMemberPositions()); } | public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } } | ParametricState { public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } } } | ParametricState { public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } } ParametricState(State state); ParametricState(State state, int transitionBoundaryOffset); } | ParametricState { public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } } ParametricState(State state); ParametricState(State state, int transitionBoundaryOffset); int getLargestPositionOffset(); int getTransitionBoundaryOffset(); State createActualState(int minimalBoundary); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | ParametricState { public ParametricState(State state) { Position[] stateMemberPositionArray = state.getMemberPositions(); int memberPositionCount = stateMemberPositionArray.length; memberPositionBoundaryOffsetArray = new int[memberPositionCount]; memberPositionEArray = new int[memberPositionCount]; memberPositionTArray = new boolean[memberPositionCount]; for(int i = 0; i < memberPositionCount; i++) { memberPositionBoundaryOffsetArray[i] = stateMemberPositionArray[i].getI() - stateMemberPositionArray[0].getI(); memberPositionEArray[i] = stateMemberPositionArray[i].getE(); memberPositionTArray[i] = stateMemberPositionArray[i].getT(); } } ParametricState(State state); ParametricState(State state, int transitionBoundaryOffset); int getLargestPositionOffset(); int getTransitionBoundaryOffset(); State createActualState(int minimalBoundary); @Override boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } |
@Test(dataProvider = "transitionInternalTestDp") public void transitionInternalTest(Position p) { int mdStartIndex = p.getE() + (!p.getT() ? 2 : 1); for(int mdi = mdStartIndex; mdi >= p.getE(); mdi--) { for(int rsi = 0; rsi <= 2; rsi++) { for(int hii = -1; hii <= 4; hii++) { int currentE = (mdi == p.getE() + 2 ? 0 : p.getE()); boolean currentT = (rsi < 2 ? false : p.getT()); Position currentPosition = new Position(p.getI(),currentE, currentT); State s = currentPosition.transitionInternal(mdi, rsi, hii); if(currentE == 0 && currentE < mdi) { switch(rsi) { case 0: insertionTransitionAssertion(currentPosition, s); break; case 1: { switch(hii) { case 0: matchTransitionAssertion(currentPosition, s); break; default: defaultTransitionAssertion(currentPosition, s); break; } break; } default: { switch(hii) { case -1: defaultTransitionAssertion(currentPosition, s); break; case 0: matchTransitionAssertion(currentPosition, s); break; case 1: preTranspositionTransitionAssertion(currentPosition, s, hii); break; default: deletionTransitionAssertion(currentPosition, s, hii); break; } break; } } } else if(currentE > 0 && currentE < mdi) { switch(rsi) { case 0: insertionTransitionAssertion(currentPosition, s); break; case 1: { switch(hii) { case 0: matchTransitionAssertion(currentPosition, s); break; default: defaultTransitionAssertion(currentPosition, s); break; } break; } default: { if(!currentT) { switch(hii) { case -1: defaultTransitionAssertion(currentPosition, s); break; case 0: matchTransitionAssertion(currentPosition, s); break; case 1: preTranspositionTransitionAssertion(currentPosition, s, hii); break; default: deletionTransitionAssertion(currentPosition, s, hii); break; } break; } else { switch(hii) { case 0: transpositionTransitionAssertion(currentPosition, s); break; default: assert s == null; break; } } } } } else { switch(rsi) { case 0: assert (s == null); break; default: { if(!currentPosition.getT()) { switch(hii) { case 0: matchTransitionAssertion(currentPosition, s); break; default: assert (s == null); break; } break; } else { switch(hii) { case 0: transpositionTransitionAssertion(currentPosition, s); break; default: assert (s == null); break; } break; } } } } } } } } | public State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex) { Position.EditDistanceRelationType edRelationType = (E < maxEditDistance ? (E == 0 ? Position.EditDistanceRelationType.AT_ZERO_AND_NOT_AT_MAX : Position.EditDistanceRelationType.NOT_AT_ZERO_AND_NOT_AT_MAX) : Position.EditDistanceRelationType.AT_MAX); Position.StateRelevantSubwordSizeType stateRSSizeType = (relevantSubwordSize >= 2 ? Position.StateRelevantSubwordSizeType.ATLEAST_TWO : (relevantSubwordSize == 1 ? Position.StateRelevantSubwordSizeType.ONE : Position.StateRelevantSubwordSizeType.ZERO)); Position.PositionType pType = (T ? Position.PositionType.TRANSPOSITION_POSITION : Position.PositionType.STANDARD_POSITION); Position.RelevantSubwordHitIndexType rsHitIndexType; switch(hitIndex) { case -1: rsHitIndexType = Position.RelevantSubwordHitIndexType.NO_INDEX; break; case 0: rsHitIndexType = Position.RelevantSubwordHitIndexType.FIRST_INDEX; break; case 1: rsHitIndexType = Position.RelevantSubwordHitIndexType.SECOND_INDEX; break; default: rsHitIndexType = Position.RelevantSubwordHitIndexType.TRAILING_INDEX; break; } Position.ElementaryTransitionTerm[] elementaryTransition = procureTransition(edRelationType, stateRSSizeType, pType, rsHitIndexType); HashSet<Position> possibleNewPositionHashSet = new HashSet<Position>(); for(Position.ElementaryTransitionTerm currentTerm : elementaryTransition) { Position transitionPosition = currentTerm.execute(this, hitIndex); if(transitionPosition != null) possibleNewPositionHashSet.add(transitionPosition); } if(!possibleNewPositionHashSet.isEmpty()) { Position[] positionArray = possibleNewPositionHashSet.toArray(new Position[possibleNewPositionHashSet.size()]); Arrays.sort(positionArray); return new State(positionArray); } else return null; } | Position implements Comparable<Position> { public State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex) { Position.EditDistanceRelationType edRelationType = (E < maxEditDistance ? (E == 0 ? Position.EditDistanceRelationType.AT_ZERO_AND_NOT_AT_MAX : Position.EditDistanceRelationType.NOT_AT_ZERO_AND_NOT_AT_MAX) : Position.EditDistanceRelationType.AT_MAX); Position.StateRelevantSubwordSizeType stateRSSizeType = (relevantSubwordSize >= 2 ? Position.StateRelevantSubwordSizeType.ATLEAST_TWO : (relevantSubwordSize == 1 ? Position.StateRelevantSubwordSizeType.ONE : Position.StateRelevantSubwordSizeType.ZERO)); Position.PositionType pType = (T ? Position.PositionType.TRANSPOSITION_POSITION : Position.PositionType.STANDARD_POSITION); Position.RelevantSubwordHitIndexType rsHitIndexType; switch(hitIndex) { case -1: rsHitIndexType = Position.RelevantSubwordHitIndexType.NO_INDEX; break; case 0: rsHitIndexType = Position.RelevantSubwordHitIndexType.FIRST_INDEX; break; case 1: rsHitIndexType = Position.RelevantSubwordHitIndexType.SECOND_INDEX; break; default: rsHitIndexType = Position.RelevantSubwordHitIndexType.TRAILING_INDEX; break; } Position.ElementaryTransitionTerm[] elementaryTransition = procureTransition(edRelationType, stateRSSizeType, pType, rsHitIndexType); HashSet<Position> possibleNewPositionHashSet = new HashSet<Position>(); for(Position.ElementaryTransitionTerm currentTerm : elementaryTransition) { Position transitionPosition = currentTerm.execute(this, hitIndex); if(transitionPosition != null) possibleNewPositionHashSet.add(transitionPosition); } if(!possibleNewPositionHashSet.isEmpty()) { Position[] positionArray = possibleNewPositionHashSet.toArray(new Position[possibleNewPositionHashSet.size()]); Arrays.sort(positionArray); return new State(positionArray); } else return null; } } | Position implements Comparable<Position> { public State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex) { Position.EditDistanceRelationType edRelationType = (E < maxEditDistance ? (E == 0 ? Position.EditDistanceRelationType.AT_ZERO_AND_NOT_AT_MAX : Position.EditDistanceRelationType.NOT_AT_ZERO_AND_NOT_AT_MAX) : Position.EditDistanceRelationType.AT_MAX); Position.StateRelevantSubwordSizeType stateRSSizeType = (relevantSubwordSize >= 2 ? Position.StateRelevantSubwordSizeType.ATLEAST_TWO : (relevantSubwordSize == 1 ? Position.StateRelevantSubwordSizeType.ONE : Position.StateRelevantSubwordSizeType.ZERO)); Position.PositionType pType = (T ? Position.PositionType.TRANSPOSITION_POSITION : Position.PositionType.STANDARD_POSITION); Position.RelevantSubwordHitIndexType rsHitIndexType; switch(hitIndex) { case -1: rsHitIndexType = Position.RelevantSubwordHitIndexType.NO_INDEX; break; case 0: rsHitIndexType = Position.RelevantSubwordHitIndexType.FIRST_INDEX; break; case 1: rsHitIndexType = Position.RelevantSubwordHitIndexType.SECOND_INDEX; break; default: rsHitIndexType = Position.RelevantSubwordHitIndexType.TRAILING_INDEX; break; } Position.ElementaryTransitionTerm[] elementaryTransition = procureTransition(edRelationType, stateRSSizeType, pType, rsHitIndexType); HashSet<Position> possibleNewPositionHashSet = new HashSet<Position>(); for(Position.ElementaryTransitionTerm currentTerm : elementaryTransition) { Position transitionPosition = currentTerm.execute(this, hitIndex); if(transitionPosition != null) possibleNewPositionHashSet.add(transitionPosition); } if(!possibleNewPositionHashSet.isEmpty()) { Position[] positionArray = possibleNewPositionHashSet.toArray(new Position[possibleNewPositionHashSet.size()]); Arrays.sort(positionArray); return new State(positionArray); } else return null; } Position(int I, int E, boolean T); } | Position implements Comparable<Position> { public State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex) { Position.EditDistanceRelationType edRelationType = (E < maxEditDistance ? (E == 0 ? Position.EditDistanceRelationType.AT_ZERO_AND_NOT_AT_MAX : Position.EditDistanceRelationType.NOT_AT_ZERO_AND_NOT_AT_MAX) : Position.EditDistanceRelationType.AT_MAX); Position.StateRelevantSubwordSizeType stateRSSizeType = (relevantSubwordSize >= 2 ? Position.StateRelevantSubwordSizeType.ATLEAST_TWO : (relevantSubwordSize == 1 ? Position.StateRelevantSubwordSizeType.ONE : Position.StateRelevantSubwordSizeType.ZERO)); Position.PositionType pType = (T ? Position.PositionType.TRANSPOSITION_POSITION : Position.PositionType.STANDARD_POSITION); Position.RelevantSubwordHitIndexType rsHitIndexType; switch(hitIndex) { case -1: rsHitIndexType = Position.RelevantSubwordHitIndexType.NO_INDEX; break; case 0: rsHitIndexType = Position.RelevantSubwordHitIndexType.FIRST_INDEX; break; case 1: rsHitIndexType = Position.RelevantSubwordHitIndexType.SECOND_INDEX; break; default: rsHitIndexType = Position.RelevantSubwordHitIndexType.TRAILING_INDEX; break; } Position.ElementaryTransitionTerm[] elementaryTransition = procureTransition(edRelationType, stateRSSizeType, pType, rsHitIndexType); HashSet<Position> possibleNewPositionHashSet = new HashSet<Position>(); for(Position.ElementaryTransitionTerm currentTerm : elementaryTransition) { Position transitionPosition = currentTerm.execute(this, hitIndex); if(transitionPosition != null) possibleNewPositionHashSet.add(transitionPosition); } if(!possibleNewPositionHashSet.isEmpty()) { Position[] positionArray = possibleNewPositionHashSet.toArray(new Position[possibleNewPositionHashSet.size()]); Arrays.sort(positionArray); return new State(positionArray); } else return null; } Position(int I, int E, boolean T); int getI(); int getE(); boolean getT(); Position.ElementaryTransitionTerm[] procureTransition(Position.EditDistanceRelationType edRelationType, Position.StateRelevantSubwordSizeType sRSSizeType, Position.PositionType pType, Position.RelevantSubwordHitIndexType rsHitIndexType); State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex); int[] procurePositionTransitionData(int maxEditDistance, int relevantSubwordStartIndex, AugBitSet parentStateRelevantSubwordCharacteristicVector); State transition(int maxEditDistance, int parentStateRelevantSubwordLocationIndex, AugBitSet parentStateRelevantSubwordCharacteristicVector); boolean subsumes(Position p, int maxEditDistance); @Override int compareTo(Position p2); boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } | Position implements Comparable<Position> { public State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex) { Position.EditDistanceRelationType edRelationType = (E < maxEditDistance ? (E == 0 ? Position.EditDistanceRelationType.AT_ZERO_AND_NOT_AT_MAX : Position.EditDistanceRelationType.NOT_AT_ZERO_AND_NOT_AT_MAX) : Position.EditDistanceRelationType.AT_MAX); Position.StateRelevantSubwordSizeType stateRSSizeType = (relevantSubwordSize >= 2 ? Position.StateRelevantSubwordSizeType.ATLEAST_TWO : (relevantSubwordSize == 1 ? Position.StateRelevantSubwordSizeType.ONE : Position.StateRelevantSubwordSizeType.ZERO)); Position.PositionType pType = (T ? Position.PositionType.TRANSPOSITION_POSITION : Position.PositionType.STANDARD_POSITION); Position.RelevantSubwordHitIndexType rsHitIndexType; switch(hitIndex) { case -1: rsHitIndexType = Position.RelevantSubwordHitIndexType.NO_INDEX; break; case 0: rsHitIndexType = Position.RelevantSubwordHitIndexType.FIRST_INDEX; break; case 1: rsHitIndexType = Position.RelevantSubwordHitIndexType.SECOND_INDEX; break; default: rsHitIndexType = Position.RelevantSubwordHitIndexType.TRAILING_INDEX; break; } Position.ElementaryTransitionTerm[] elementaryTransition = procureTransition(edRelationType, stateRSSizeType, pType, rsHitIndexType); HashSet<Position> possibleNewPositionHashSet = new HashSet<Position>(); for(Position.ElementaryTransitionTerm currentTerm : elementaryTransition) { Position transitionPosition = currentTerm.execute(this, hitIndex); if(transitionPosition != null) possibleNewPositionHashSet.add(transitionPosition); } if(!possibleNewPositionHashSet.isEmpty()) { Position[] positionArray = possibleNewPositionHashSet.toArray(new Position[possibleNewPositionHashSet.size()]); Arrays.sort(positionArray); return new State(positionArray); } else return null; } Position(int I, int E, boolean T); int getI(); int getE(); boolean getT(); Position.ElementaryTransitionTerm[] procureTransition(Position.EditDistanceRelationType edRelationType, Position.StateRelevantSubwordSizeType sRSSizeType, Position.PositionType pType, Position.RelevantSubwordHitIndexType rsHitIndexType); State transitionInternal(int maxEditDistance, int relevantSubwordSize, int hitIndex); int[] procurePositionTransitionData(int maxEditDistance, int relevantSubwordStartIndex, AugBitSet parentStateRelevantSubwordCharacteristicVector); State transition(int maxEditDistance, int parentStateRelevantSubwordLocationIndex, AugBitSet parentStateRelevantSubwordCharacteristicVector); boolean subsumes(Position p, int maxEditDistance); @Override int compareTo(Position p2); boolean equals(Object obj); @Override int hashCode(); @Override String toString(); } |
@Test @Override public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> listOfPairsOfStringAndJsonObjects = getWrongParameters(); for (int i = 0; i < listOfPairsOfStringAndJsonObjects.size(); i++) { IDistribution<SPACE> distribution = getDistribution(); try { distribution.setParameters(listOfPairsOfStringAndJsonObjects.get(i).getSecond()); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, listOfPairsOfStringAndJsonObjects.get(i).getSecond())); } catch (ParameterValidationFailedException e) { Assert.assertEquals(ERROR_WRONG_OUTPUT, listOfPairsOfStringAndJsonObjects.get(i).getFirst(), e.getMessage()); } } } | @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); @Override List<SPACE> generateSamples(int numberOfSamples); abstract CONFIG createDefaultDistributionConfiguration(); @Override ADistributionConfiguration getDefaultDistributionConfiguration(); @Override @SuppressWarnings("unchecked") void setDistributionConfiguration(ADistributionConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getDistributionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override String toString(); } | ADistribution implements IDistribution<SPACE> { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getDistributionConfiguration().overrideConfiguration(jsonObject); } ADistribution(); @Override List<SPACE> generateSamples(int numberOfSamples); abstract CONFIG createDefaultDistributionConfiguration(); @Override ADistributionConfiguration getDefaultDistributionConfiguration(); @Override @SuppressWarnings("unchecked") void setDistributionConfiguration(ADistributionConfiguration algorithmConfiguration); @Override @SuppressWarnings("unchecked") CONFIG getDistributionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override String toString(); } |
@Override @Test public void testCorrectParameters() throws JsonParsingFailedException { List<JsonObject> testPairs = getCorrectParameters(); for (int i = 0; i < testPairs.size(); i++) { IEvaluation evaluation = getEvaluation(); JsonObject object = testPairs.get(i); try { evaluation.setParameters(object); } catch (ParameterValidationFailedException e) { fail(String.format(ERROR_CORRECT_PARAMETER_NOT_ACCEPTED, object.toString())); } } } | @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } AEvaluation(ELearningProblem eLearningProblem); } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } |
@Override @Test public void testWrongParameters() throws JsonParsingFailedException { List<Pair<String, JsonObject>> testPairs = getWrongParameters(); for (int i = 0; i < testPairs.size(); i++) { IEvaluation evaluation = getEvaluation(); JsonObject object = testPairs.get(i).getSecond(); try { evaluation.setParameters(object); fail(String.format(ERROR_INCORRECT_PARAMETER_ACCEPTED, testPairs.get(i).getSecond().toString())); } catch (ParameterValidationFailedException exception) { Assert.assertEquals(ERROR_WRONG_OUTPUT, exception.getMessage(), testPairs.get(i).getFirst()); } } } | @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } AEvaluation(ELearningProblem eLearningProblem); } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } | AEvaluation implements IEvaluation { @Override public void setParameters(JsonObject jsonObject) throws ParameterValidationFailedException { getEvaluationConfiguration().overrideConfiguration(jsonObject); } AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } |
@Test public void testCorrectEvaluationSettings() { evaluation = (AEvaluation<?>) getEvaluation(); List<Pair<EvaluationSetting, EvaluationResult>> testPairs = getCorrectListOfEvaluationSettings(); for (int i = 0; i < testPairs.size(); i++) { EvaluationSetting evaluationSetting = testPairs.get(i).getFirst(); try { EvaluationResult evaluatedEvaluationResult = evaluation.evaluateSingleCombination(evaluationSetting); EvaluationResult expectedEvaluationResult = testPairs.get(i).getSecond(); String expectedResult = expectedEvaluationResult.getExtraEvaluationInformation(); String evaluatedResult = evaluatedEvaluationResult.getExtraEvaluationInformation(); Assert.assertEquals(String.format(ASSERT_EVALUATION_RESULT_EQUAL, expectedResult, evaluatedResult), expectedResult, evaluatedResult); for (int k = 0; k < expectedEvaluationResult.getEvaluationMetrics().size(); k++) { IMetric<?, ?> metric = expectedEvaluationResult.getEvaluationMetrics().get(k); Object expectedLoss = expectedEvaluationResult.getLossForMetric(metric); Object evaluatedLoss = evaluatedEvaluationResult.getLossForMetric(metric); if (expectedLoss instanceof Double) { String[] split = evaluationSetting.getDataset().getDatasetFile().toString().split("/"); String fileName = split[split.length - 1]; logger.debug(String.format(DEBUG_MESSAGE_EVALUATION_RESULT, fileName, metric.toString(), expectedLoss, evaluatedLoss)); String assertMessage = String.format(ASSERT_EVALUATION_LOSS_EQUAL, metric.toString(), expectedEvaluationResult.getLearningAlgorithm().toString()); Assert.assertEquals(assertMessage, (Double) expectedLoss, (Double) evaluatedLoss, ERROR_MARGIN); } else { Assert.assertEquals(String.format(ASSERT_EVALUATION_LOSS_EQUAL, metric.toString(), expectedEvaluationResult.getLearningAlgorithm().toString()), expectedLoss, evaluatedLoss); } } } catch (LossException | PredictionFailedException exception) { fail(String.format(ERROR_CORRECT_EVALUATION_RESULT_NOT_ACHIEVED_FOR_CORRECT_SETTING, testPairs.get(i).getSecond().toString(), evaluationSetting.toString())); } } } | public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; } | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; AEvaluation(ELearningProblem eLearningProblem); } | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } |
@Test public void testWrongEvaluationSettings() { List<Pair<EvaluationSetting, EvaluationResult>> testPairs = getWrongListOfEvaluationSettings(); AEvaluation<?> evaluation = (AEvaluation<?>) getEvaluation(); for (int i = 0; i < testPairs.size(); i++) { try { EvaluationSetting evaluationSetting = testPairs.get(i).getFirst(); EvaluationResult evaluatedEvaluationResult = evaluation.evaluateSingleCombination(evaluationSetting); EvaluationResult expectedEvaluationResult = testPairs.get(i).getSecond(); String expectedResult = expectedEvaluationResult.getExtraEvaluationInformation(); String evaluatedResult = evaluatedEvaluationResult.getExtraEvaluationInformation(); Assert.assertNotEquals(String.format(ASSERT_CORRECT_EVALUATION_RESULT_ACHIEVED_FOR_INCORRECT_SETTING, expectedResult, evaluationSetting.toString()), evaluatedResult, expectedResult); for (IMetric<?, ?> evaluationMetric : expectedEvaluationResult.getEvaluationMetrics()) { Object expectedLoss = expectedEvaluationResult.getLossForMetric(evaluationMetric); Object evaluatedLoss = evaluatedEvaluationResult.getLossForMetric(evaluationMetric); if (evaluatedLoss.getClass() == Double.class) { expectedLoss = (double) expectedLoss; evaluatedLoss = (double) evaluatedLoss; boolean compare = TestUtils.areDoublesEqual((double) expectedLoss, (double) evaluatedLoss, ERROR_MARGIN); Assert.assertFalse(String.format(ASSERT_CORRECT_LOSS_ACHIEVED_FOR_INCORRECT_SETTING, expectedLoss, evaluatedLoss), compare); } else { Assert.assertNotEquals(String.format(ASSERT_CORRECT_LOSS_ACHIEVED_FOR_INCORRECT_SETTING, expectedLoss, evaluatedLoss), expectedLoss, evaluatedLoss); } } } catch (LossException | PredictionFailedException exception) { Assert.fail(String.format(ERROR_EXCEPTION_NOT_OCCURR_ERROR_MESSAGE, testPairs.get(i).getFirst().getMetrics())); } } } | public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; } | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; AEvaluation(ELearningProblem eLearningProblem); } | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } | AEvaluation implements IEvaluation { public abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting) throws LossException, PredictionFailedException; AEvaluation(ELearningProblem eLearningProblem); @Override void evaluate(); @Override EvaluationResult runEvaluationForOneSetOfEvaluationSettings(Pair<Integer, List<EvaluationSetting>> evaluationSettingsForOneSet); abstract EvaluationResult evaluateSingleCombination(EvaluationSetting evaluationSetting); static EvaluationResult createCombinedEvaluationResultForOneSet(List<EvaluationResult> evaluationResultsForOneSet); List<EvaluationResult> getEvaluationResult(); @Override JsonObject getMetricParameterJsonObject(String metricIdentifier); boolean checkValidtiyOfEvalautionResult(); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms); @Override void setupEvaluation(List<DatasetFile> datasetFiles, List<ILearningAlgorithm> learningAlgorithms, List<IMetric<?, ?>> metrics); @Override int setupSingleEvaluationDatasetAndAlgorithm(int setNumber, DatasetFile datasetFile, ILearningAlgorithm learningAlgorithm,
List<IMetric<?, ?>> metrics); @Override String interpretEvaluationResult(); @SuppressWarnings("unchecked") @Override AEvaluationConfiguration getEvaluationConfiguration(); @Override AEvaluationConfiguration getDefaultEvalutionConfiguration(); @Override void setParameters(JsonObject jsonObject); @Override @SuppressWarnings("unchecked") void setEvaluationConfiguration(AEvaluationConfiguration evaluationConfiguration); @Override int hashCode(); @Override boolean equals(Object secondObject); } |
@Test public void testEvaluateAlgorithmsCommandWithCommandLineCompleteInput() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String correctResult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_COMMAND_POSITIVE_TEST), EEvaluation.SUPPLIED_TEST_SET_RANK_AGGREGATION.getEvaluationIdentifier(), ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_JSON_FILE)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier(), String.format(EVALUATE_ALGORITHM_IDENTIFIER_COMMAND_LINE, EvaluationsKeyValuePairs.EVALUATION_SUPPLIED_TEST_SET_IDENTIFIER), String.format(METRICS_IDENTIFIER_COMMAND_LINE, EMetric.KENDALLS_TAU.getMetricIdentifier(), EMetric.SPEARMANS_RANK_CORRELATION.getMetricIdentifier()) }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(commandResult.isExecutedSuccessfully()); assertTrue(command.getFailureReason().isEmpty()); assertTrue(commandResult.getException() instanceof NullException); assertTrue(commandResult.getResult().toString().equals(correctResult)); } | @Override public String getFailureReason() { return failureReason; } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigCompleteInput() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String correctResult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_COMMAND_POSITIVE_TEST), EEvaluation.SUPPLIED_TEST_SET_RANK_AGGREGATION.getEvaluationIdentifier(), ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_JSON_FILE)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(commandResult.isExecutedSuccessfully()); assertTrue(command.getFailureReason().isEmpty()); assertTrue(commandResult.getException() instanceof NullException); assertTrue(commandResult.getResult().toString().equals(correctResult)); } | @Override public String getFailureReason() { return failureReason; } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public String getFailureReason() { return failureReason; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigNullEvalaution() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(EvaluateAlgorithmsCommand.class, REFLECTION_CANNOT_CREATE_EVALUATION_FOR_LEARNING_PROBLEM), EEvaluation.CROSS_VALIDATION_DATASET_RANK_AGGREGATION.getEvaluationIdentifier(), ELearningProblem.RANK_AGGREGATION.getLearningProblemIdentifier()); runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_NULL_EVALUATION)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, CannotCreateEvaluationForLearningProblemException.class); assertTrue(commandResult.getException().getMessage().equals(inCorrectresult)); } | @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigWrongParameters() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String inCorrectresult = String.format( TestUtils.getStringByReflection(AEvaluationConfiguration.class, REFLECTION_VALIDATION_EVALUATION_METRIC), RANK_AGGREGATION_EVALUATION_WRONG_VALUE); runSystemConfigCommandWithFile(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_WRONG_PARAMETERS)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, ParameterValidationFailedException.class); assertTrue(commandResult.getException().getMessage().contains(inCorrectresult)); } | @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
@Test public void testEvaluateAlgorithmsCommandWithSystemConfigWrongParametersForMetrics() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { String invalidValue = TestUtils.getStringByReflection(FMeasureConfiguration.class, REFLECTION_TYPE_VALUE_INVALID); runSystemConfigCommandWithFileWithoutTrainingModels(getTestRessourcePathFor(SYSTEM_CONFIG_COMPLETE_WITH_WRONG_PARAMETERS_FORMETRICS)); currentCommand = new String[] { ECommand.EVALUATE_ALGORITHMS.getCommandIdentifier() }; String consoleOutput = TestUtils.simulateCommandLineInputAndReturnConsoleOutput(currentCommand); logger.debug(String.format(EVALUATIONS_CONSOLE_OUTPUT, consoleOutput)); Pair<ICommand, CommandResult> commandAndResult = TestUtils.getLatestPairOfCommandAndCommandResultInCommandHistory(); ICommand command = commandAndResult.getFirst(); CommandResult commandResult = commandAndResult.getSecond(); assertTrue(commandResult != null); assertTrue(command.canBeExecuted()); TestUtils.assertCorrectFailedEmptyCommandResult(commandResult, ParameterValidationFailedException.class); assertTrue(commandResult.getException().getMessage().contains(invalidValue)); } | @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } | EvaluateAlgorithmsCommand extends ACommand { @Override public boolean canBeExecuted() { try { checkInitialParametersForCommandExecution(); } catch (CommandCannotBeExecutedException commandCannotBeExecuted) { failureReason = String.format(COMMAND_CANNOT_BE_EXECUTED_ERROR_MESSAGE, commandCannotBeExecuted.getMessage()); logger.error(failureReason, commandCannotBeExecuted); } return canBeExecuted; } EvaluateAlgorithmsCommand(String evaluationIdentifierHandler, List<String> metricIdentifierHandler); @Override boolean canBeExecuted(); @Override CommandResult executeCommand(); @Override String getFailureReason(); @Override void undo(); static JsonObject getEvalautionMetricJsonArray(List<EvaluationMetricJsonElement> evaluationMetricElementArray); IEvaluation getEvaluation(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.