Override interface method in jruby - jruby

I'd like to implement the following in jruby:
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object document = dataSnapshot.getValue();
System.out.println(document);
}
});
Ther ValueEventListener:
public interface ValueEventListener {
void onDataChange(DataSnapshot snapshot);
void onCancelled(DatabaseError error);
}

Much simpler than I had initially assumed. Include the interface in a class with the on change method and pass in a proc to the listener.
class EventListenerValue
include com.google.firebase.database.ValueEventListener
def on_data_change(data_snapshot)
puts data_snapshot
document = data_snapshot.val
puts document
end
end
event_listener = EventListenerValue.new
ref.add_value_event_listener { |snapshot| event_listener.on_data_change(snapshot) }

Related

Index of an invalid object within a list

Is there an equivalent to the getPropertyPath method in the Oval validation framework?
The example code below prints the properties of all nested invalid values of an object. I'd like to also print the index of the invalid object within the list but I'm not sure how this can be done in Oval.
With javax.validation, I can call ConstraintViolation#getPropertyPath but there doesn't seem to be an equivalent in Oval. Am I missing something?
The output is
list[].value: example.ValidationDemo$Child.value cannot be null
list[].value: example.ValidationDemo$Child.value cannot be null
Here's the code:
package example;
import java.util.List;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.constraint.AssertValid;
import net.sf.oval.constraint.NotNull;
import net.sf.oval.context.FieldContext;
public class ValidationDemo {
public static void main(String[] args) {
Validator validator = new Validator();
validator.validate(new Parent())
.forEach(ValidationDemo::printViolation);
}
private static void printViolation(ConstraintViolation violation) {
printViolation(violation, "");
}
private static void printViolation(ConstraintViolation violation, String property) {
FieldContext fieldContext = (FieldContext) violation.getContext();
if (!property.isEmpty()) {
property += ".";
}
property += fieldContext.getField().getName();
if (List.class.isAssignableFrom(fieldContext.getField().getType())) {
property += "[]"; // How do I find the index of violation.getInvalidValue() within the list?
}
if (violation.getCauses() == null) {
System.out.format("%s: %s\n", property, violation.getMessage());
} else {
for (ConstraintViolation cause : violation.getCauses()) {
printViolation(cause, property);
}
}
}
public static class Parent {
#AssertValid
public final List<Child> list = List.of(new Child("value"),
new Child(null), new Child(null));
}
public static class Child {
#NotNull
public final String value;
public Child(String value) {
this.value = value;
}
}
}
This is currently not possible. This code part would need to be extended to keep track of the index.
ConstraintViolation.getContextPath() was added in 3.1.0

Unit test WCMUsePOJO class

I am writing unit test cases for following class which extends WCMUsePOJO. Now, this class is using a getSlingScriptHelper method shown below.
public class ConstantsServiceProvider extends WCMUsePojo {
private static final Logger logger = LoggerFactory.getLogger(ConstantsServiceProvider.class);
private String var1;
#Override
public void activate() throws Exception {
ConstantsService constantsService = getSlingScriptHelper().getService(ConstantsService.class);
if(constantsService != null) {
var1 = constantsService.getVar1();
}
}
public string getVar1() { return var1; }
}
The question is how do I mock getSlingScriptHelper method? Following is my unit test code.
public class ConstantsServiceProviderTest {
#Rule
public final SlingContext context = new SlingContext(ResourceResolverType.JCR_MOCK);
#Mock
public SlingScriptHelper scriptHelper;
public ConstantsServiceProviderTest() throws Exception {
}
#Before
public void setUp() throws Exception {
ConstantsService service = new ConstantsService();
scriptHelper = context.slingScriptHelper();
provider = new ConstantsServiceProvider();
provider.activate();
}
#Test
public void testGetvar1() throws Exception {
String testvar1 = "";
String var1 = provider.getVar1();
assertEquals(testvar1, var1);
}
}
The only thing that you should "have to"* mock is the SlingScriptHelper instance itself, so that it will mimic the dependency injection of the declared service.
Everything else (e.g. the Bindings instance) can be a concrete implementation, for example:
import org.apache.sling.api.scripting.SlingBindings;
import org.apache.sling.api.scripting.SlingScriptHelper;
import org.junit.Test;
import javax.script.Bindings;
import javax.script.SimpleBindings;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ConstantsServiceProviderTest {
private SlingScriptHelper mockSling = mock(SlingScriptHelper.class);
private ConstantsServiceProvider constantsServiceProvider = new ConstantsServiceProvider();
private Bindings bindings = new SimpleBindings();
#Test
public void testFoo() throws Exception {
//Arrange
final String expected = "Hello world";
final ConstantsService testConstantsService = new TestConstantsService(expected);
when(mockSling.getService(ConstantsService.class)).thenReturn(testConstantsService);
bindings.put(SlingBindings.SLING, mockSling);
//Act
constantsServiceProvider.init(bindings);
//Assert
final String actual = constantsServiceProvider.getVar1();
assertThat(actual, is(equalTo(expected)));
}
class TestConstantsService extends ConstantsService {
String var1 = "";
TestConstantsService(String var1) {
this.var1 = var1;
}
#Override
String getVar1() {
return var1;
}
}
}
The entry point here, as you said above, is via the init() method of the WCMUsePojo superclass (as this method is an implementation of the Use.class interface, this test structure also works for testing that via that interface, even if you don't use WCMUsePojo directly.)
*this could be any type of test-double, not necessarily a mock.
You shouldn't create a mock for ConstantsServiceProvider.class if you want to unit-test it. Instead, you should create mocks of its internal objects. So:
Create real instance of ConstantsServiceProvider with new
Mock objects that are returned by getSlingScriptHelper().getService(.) methods. Usually, dependencies are provided (injected) to classes by some container like Spring or simply provided by other classes of your app using setters. In both cases mocks creation is easy.
If your current implementation doesn't allow this - consider refactoring.
You are testing void activate() method which doesn't return anything. So, you should verify calling constantsService.getVar1() method.
I strongly advice you to study Vogella unit-testing tutorial
Here one of possible solution.
The main idea is to have a real object of your class but with overridden getSlingScriptHelper() to return mocked scriptHelper.
I mocked the ConstantsService as well but may be not needed, I don't know your code.
public class ConstantsServiceProviderTest {
#Mock
public SlingScriptHelper scriptHelper;
#Test
public void getVar1ReturnsActivatedValue() throws Exception {
// setup
final String expectedResult = "some value";
// Have a mocked ConstantsService, but if possible have a real instance.
final ConstantsService mockedConstantsService =
Mockito.mock(ConstantsService.class);
Mockito.when(
mockedConstantsService.getVar1())
.thenReturn(expectedResult);
Mockito.when(
scriptHelper.getService(ConstantsService.class))
.thenReturn(mockedConstantsService);
// Have a real instance of your class under testing but with overridden getSlingScriptHelper()
final ConstantsServiceProvider providerWithMockedHelper =
new ConstantsServiceProvider() {
#Override
SlingScriptHelper getSlingScriptHelper() {
return scriptHelper;
}
};
// when
String actualResult = providerWithMockedHelper.getVar1();
// then
assertEquals(expectedResult, actualResult);
}
}

Junit runs all Test with the parameter marked with #Parameter

In the following code, I would like to run TestMethod1 with the parameters marked with #Parameters
#RunWith(Parameterized.class)
public class Foo{
private boolean input;
private boolean expected;
public Foo(boolean input, boolean expected{
this.input=input;
this.expected=expected;
}
#Parameters
public static List<Object[]> data() {
return Arrays.asList(new Object[][]{{false, false}, {false, false}});
}
#Test
public void TestMethod1(){
assertEquals(expected, Baar.StaticMethod(input);
}
#Test
public void TestMethod2(){
assertEquals(expected, Baar.StaticMethod2(false);
}
The Problem is when I run junittes, both methods TestMethod1 and TestMethod2 are run with these parameters. How to tell the testrunner to run only TestMethod1 with the parameters marked with #Parameters?
not sure if pure junit allows it but there is plenty of plugins. in your case (all parameters known up-front) the simplest way would be to do parametrized testing with zohhak:
#RunWith(ZohhakRunner.class)
public class TestMyClass {
#TestWith({
"true, false".
"false, true"
})
public void test1(int actual, int expected) { //test }
#TestWith({
"false, false".
"true, true"
})
public void test2(int actual, int expected) { //test }
#Test
public void test3() { //test }
}
if you need to build parameters in run-time (generating, reading from file etc.) then you can check things like junit-dataprovider or junit-params

registering open generic decorators for typed implementations in castle windsor

While trying to coerce Windsor into wrapping an implementation with a random number of decorators, i've stumbled upon the following:
i have 3 decorators and an implementation all using the same interface.
if you run this code, windsor resolves icommandhandler<stringcommand> as implementation, which, as far as i can tell, is expected behaviour, because the typed implementation can not be registered with the open typed decorators.
However, if you uncomment the line container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<Decorator1<stringCommand>>());, all three decorators will be used to resolve implementation, which is the desired result (sort of : ).
class Program
{
static void Main(string[] args)
{
var container = new WindsorContainer();
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator1<>)));
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator2<>)));
container.Register(Component.For(typeof(ICommandHandler<>)).ImplementedBy(typeof(Decorator3<>)));
//uncomment the line below and watch the magic happen
//container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<Decorator1<stringCommand>>());
container.Register(Component.For<ICommandHandler<stringCommand>>().ImplementedBy<implementation>());
var stringCommandHandler = container.Resolve<ICommandHandler<stringCommand>>();
var command = new stringCommand();
stringCommandHandler.Handle(command);
Console.WriteLine(command.s);
Console.ReadKey();
}
}
public interface ICommandHandler<T>
{
void Handle(T t);
}
public class stringCommand
{
public string s { get; set; }
}
public abstract class Decorator<T> : ICommandHandler<T>
{
public abstract void Handle(T t);
};
public class Decorator1<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator1(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator1;";
_handler.Handle(t);
}
}
public class Decorator2<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator2(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator2;";
_handler.Handle(t);
}
}
public class Decorator3<T> : Decorator<T>
where T : stringCommand
{
private ICommandHandler<T> _handler;
public Decorator3(ICommandHandler<T> handler)
{
_handler = handler;
}
public override void Handle(T t)
{
t.s += "Decorator3;";
_handler.Handle(t);
}
}
public class implementation : ICommandHandler<stringCommand>
{
public void Handle(stringCommand t)
{
t.s += "implementation;";
}
}
Why exactly is this happening, is this a feature of windsor that i am not aware of? Is there perhaps a different way to achieve the same effect? (without resorting to reflection)
When windsor tries to resolve a component it will first try to resolve the more specific interface. So when you register Component.For it will prefer to resolve this over an open generic type.
If the same interface is registered multiple times, it will use the first one specified.
So if you don't uncommment the line your application will resolve implementation since this is the most specific component.
If you do uncomment the line decorator1 will be resolved and indeed the magic starts. The decorator will now start looking for the first registered component that satisfies it's constructor, in this case that would be decorator1 again (you did notice that your output show decorator1 2 times ?). Which will the resolve the next registered component and so on till it comes to the actual implementation.
So the only thing I can think about is not registering decorator1 as an open generic but as a specific type.
Kind regards,
Marwijn.

VAADIN client component logic

I use VAADIN framework in my simple application.
I have my 2 custom components e.g.
#ClientWidget(value = VComponent1.class)
public class Component1 {
private Component2 cmp2;
public void setDataSource(Component2 cmp2) {
this.cmp2 = cmp2;
}
}
and
#ClientWidget(value = VComponent2.class)
public class Component2 {
}
I would like to bind them on server side.
...
Component2 cmp2 = new Component2();
Component1 cmp1 = new Component1();
cmp1.setDataSource(cmp2);
mainWindow.addComponent(cmp1);
mainWindow.addComponent(cmp2);
...
Question is that I don't know how to send bind infomation to VComponent1.
VComponent1 should have direct link to VComponent2
public class VComponent2 implements Paintable {
public String getCurrentData() {
return "Hello";
}
}
public class VComponent1 implements Paintable,
ClickHandler {
VComponent2 dataSource;
#Override
public void onClick(ClickEvent event) {
super.onClick(event);
String data = dataSource.getCurrentData();
client.updateVariable(uidlId, "curData", data, true);
}
}
I need to avoid communication through server part of Component2 because of some specific time issues.
VComponent1 should have direct access to VComponent2.
Could you please help me with my scenario.
Thanks,
Aritomo
You can communicate a reference to another Vaadin component like this:
Server-side:
public void paintContent(PaintTarget target) throws PaintException {
..
target.addAttribute("mycomponent", component);
..
}
Client-side:
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
..
Paintable componentPaintable = uidl.getPaintableAttribute("mycomponent", client);
..
}