How do you bind elements to SwiXML in JRuby? - jruby

I am trying to recreate SwiXML examples in JRuby. But the objects
created in JRuby never seem to be visible to SwiXML. Here is an example.
<frame size="200,200" title="Action Test">
<menubar>
<menu text="File">
<menuitem action="quit" accelerator="meta X" />
</menu>
</menubar>
<button action="quit" text="A Quit Button"
ToolTipText="This is a quit button." />
</frame>
The Java code from the SwiXML example is as follows:
public class ActionTest {
// Create an Action as a member variable
public Action quit = new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
};
public ActionTest() throws Exception {
// set the Action's name
quit.putValue(Action.NAME, "Quit");
// build the GUI
new SwingEngine(this).render("ActionTest.xml")
.setVisible(true);
}
public static void main(String[] args) throws Exception {
new ActionTest();
}
}
I have created some JRuby code to correspond to this, but it seems as if
the #quit member is never seen. Also tried referencing other named
elements (not in this example):
require 'java'
require 'java/swixml.jar'
require 'java/jdom.jar'
include_class 'javax.swing.AbstractAction'
include_class 'javax.swing.Action'
include_class 'javax.swing.JButton'
class MyAction < AbstractAction
def actionPerformed(ae)
exit # puts "Clicked"
end
end
class Main < Object # Java::JavaLang::Object
def initialize
#quit = MyAction.new
#quit.putValue(Action.NAME, "Quit")
#f = java.io.File.new("sample.xml")
#se = org.swixml.SwingEngine.new(self).render(#f).setVisible(true)
end
end
Main.new

I've been struggling with integrating JRuby and SwiXml this week. I've come to the conclusion that you can't have SwiXml automatically bind your variables/actions from the XML. (I think this is because in Java the variables already exist, whereas in JRuby they are created 'on-the-fly', so SwiXml isn't sure what to do. That's my conclusion, anyway, after hours of digging through source code. JRuby is fairly new to me, so someone more advanced might be able to tell me why this won't work.)
The solution is to simply bind them manually in the JRuby code. It's actually fairly easy, since this is Ruby.
include Java
java_import 'org.swixml.SwingEngine'
class HelloWorld
def initialize
#swix = SwingEngine.new(self)
#swix.render("xml/helloworld.xml")
btn = #swix.find("submit")
btn.add_action_listener { |event| btn.text = 'Hi' }
end
def run
#swix.getRootComponent.setVisible(true)
end
end
See? Not too bad. In my case, "submit" is defined as the <button>'s ID attribute. So in my XML file I have <button text="Click Here" id="submit" /> Think of the find() method like a findById() method (if you're familiar with DOM manipulation through JavaScript...).
Note that since the add_action_listener takes a block, instance variables (ivars) can be included in the block (in other words, it acts like you would expect a Java anonymous class/block to work). There's other ways to implement/add an action listener. See this page: https://github.com/jruby/jruby/wiki/FAQs and scroll down to the section with a heading that says How can I implement a Java Interface using a Ruby Class?
Any element (as far as I know), can be retrieved by the SwingEngine class's find() method, as long as it's id is defined in the XML file.
A few minor things: include_class is now deprecated. You should use java_import instead. Also, your class that you're passing to SwingEngine does not need to inherit from Object or anything like that. JRuby is getting much better about making things more 'ruby-like' when integrating with Java.
Hope this helps. There's not much info out there about this stuff.
P.S. I found the info about 'manually binding' from this link: http://www.mail-archive.com/forum#carlsbadcubes.com/msg00062.html

I don't have your answer here (My Ruby isn't good enough) - but I having a similar issue trying to use Jython here; this example partially works (it picks up the 'quit' action).
from org.swixml.jsr296 import SwingApplication
from org.jdesktop.application import Application
from javax.swing import JButton, JFrame
class MyFrame(JFrame):
def __init__(self):
pass
class Tester(SwingApplication):
def __init__(self):
self.frame=MyFrame()
#self.frame=JFrame()
def startup(self):
print "Application Started"
self.render(self.frame,"frame.xml").show()
def shutdown(self):
print "Application Shutdown"
#def quit(self,evt):
# print "Over-ridden quit"
def action1(self,evt):
print "action1"
if __name__=='__main__':
Application.launch(Tester,None)
I added in a second button in the XML like this:
<button action="action1" text="action1" ToolTipText="action1" />
But the additional 'action1' method is never seen by swixml it seems, I get the following output when I start (and then quit) the application:
Application Started
SwixML 2.5
11-Nov-2011 12:10:38 org.swixml.XAction <init>
WARNING: error on Action initialization [org.python.proxies.__main__$MyFrame$1.action1()]
Application Shutdown
The interesting thing is, if you uncomment the 'def quit(self,evt)' method ; this method IS seen by SXIWML; and the behaviour of the 'quit' button changes from shutting down the Application to printing out a message.
So it seems that something about the way SWIXML reflects to look for actions fails when the action is purely defined in Jython (Method signatures?): but over-riding an existing action method does work.
It would be really nice to see what is going on here - I might log a new StackOverFlow question on this example and reference this one.
It would be great to be able to quickly throw together simple SWING apps using JRuby / Jython (etc) using SWIXMl; but a working template of how to do this is needed I think.
The other strange thing that I cannot explain ; if the line 'self.frame=MyFrame()' is changed to instantiate a standard JFrame: 'self.frame.JFrame()' - this results in classloader errors:
SwixML 2.5
11-Nov-2011 12:19:14 org.swixml.XAction <init>
WARNING: error on Action initialization [null ClassLoader]
11-Nov-2011 12:19:14 org.swixml.XAction <init>
WARNING: error on Action initialization [null ClassLoader]
11-Nov-2011 12:19:14 org.swixml.XAction <init>
WARNING: error on Action initialization [null ClassLoader]

Related

Chisel: getting signal name in final Verilog

I'd like to automate as much as possible the instantiation of an ILA directly from the Chisel code. This means instantiating a module that looks like this:
i_ila my_ila(
.clk(clock),
.probe0(a_signal_to_monitor),
.probe1(another_signal_to_monitor),
// and so on
);
I'm planning to store the signals that I want to monitor in a list of UInt so that at the end of module elaboration I can generate the instantiation code above, which I will copy/paste in the final Verilog code (or write a Python script that does that automatically).
First, is there a better way of doing this, perhaps at the level of FIRRTL?
Even if I go with this semi-manual approach, I need to know what would be the name of the signals in the final Verilog, which is not necessarily the name of the UInt vals in the code (and which, besides, I don't know how to get automatically without having to retype the name of the variable as a string somewhere). How can I get them?
I'd like to provide a more complete example, but I wanted to make sure to at least write something up. This also needs to be fleshed out as a proper example/tutorial on the website.
FIRRTL has robust support for tracking names of signals across built-in and custom transformations. This is a case where the infrastructure is all there, but it's very much a power user API. In short, you can create FIRRTL Annotations that will track Targets. You can then emit custom metadata files or use the normal FIRRTL annotation file (try the CLI option -foaf / --output-annotation-file).
An example FIRRTL Annotation that has will emit a custom metadata file at the end of compilation:
// Example FIRRTL annotation with Custom serialization
// FIRRTL will track the name of this signal through compilation
case class MyMetadataAnno(target: ReferenceTarget)
extends SingleTargetAnnotation[ReferenceTarget]
with CustomFileEmission {
def duplicate(n: ReferenceTarget) = this.copy(n)
// API for serializing a custom metadata file
// Note that multiple of this annotation will collide which is an error, not handled in this example
protected def baseFileName(annotations: AnnotationSeq): String = "my_metadata"
protected def suffix: Option[String] = Some(".txt")
def getBytes: Iterable[Byte] =
s"Annotated signal: ${target.serialize}".getBytes
}
The case class declaration and duplicate method are enough to track a single signal through compilation. The CustomFileEmission and related baseFileName, suffix, and getBytes methods define how to serialize my custom metadata file. As mentioned in the comment, as implemented in this example we can only have 1 instance of this MyMetadataAnno or they will try to write the same file which is an error. This can be handled by customizing the filename based on the Target, or writing a FIRRTL transform to aggregate multiple of this annotation into a single annotation.
We then need a way to create this annotation in Chisel:
def markSignal[T <: Data](x: T): T = {
annotate(new ChiselAnnotation {
// We can't call .toTarget until end of Chisel elaboration
// .toFirrtl is called by Chisel at the end of elaboration
def toFirrtl = MyMetadataAnno(x.toTarget)
})
x
}
Now all we need to do is use this simple API in our Chisel
// Simple example with a marked signal
class Foo extends MultiIOModule {
val in = IO(Flipped(Decoupled(UInt(8.W))))
val out = IO(Decoupled(UInt(8.W)))
markSignal(out.valid)
out <> in
}
This will result in writing the file my_metadata.txt to the target directory with the contents:
Annotated signal: ~Foo|Foo>out_valid
Note that this is special FIRRTL target syntax saying that out_valid is the annotated signal that lives in module Foo.
Complete code in an executable example:
https://scastie.scala-lang.org/moEiIqZPTRCR5mLQNrV3zA

Mockito - You cannot use argument matchers outside of verification or stubbing - have tried many things but still no solution

I have the following piece of code:
PowerMockito.mockStatic(DateUtils.class);
//And this is the line which does the exception - notice it's a static function
PowerMockito.when(DateUtils.isEqualByDateTime (any(Date.class),any(Date.class)).thenReturn(false);
The class begins with:
#RunWith(PowerMockRunner.class)
#PrepareForTest({CM9DateUtils.class,DateUtils.class})
And I get org.Mockito.exceptions.InvalidUseOfMatchersException...... You cannot use argument matchers outside of verification or stubbing..... (The error appears twice in the Failure Trace - but both point to the same line)
In other places in my code the usage of when is done and it's working properly. Also, when debugging my code I found that any(Date.class) returns null.
I have tried the following solutions which I saw other people found useful, but for me it doesn't work:
Adding
#After
public void checkMockito() {
Mockito.validateMockitoUsage();
}
or
#RunWith(MockitoJUnitRunner.class)
or
#RunWith(PowerMockRunner.class)
Change to
PowerMockito.when(new Boolean(DateUtils.isEqualByDateTime(any(Date.class), any(Date.class)))).thenReturn(false);
Using anyObject() (it doesn't compile)
Using
notNull(Date.class) or (Date)notNull()
Replace
when(........).thenReturn(false);
with
Boolean falseBool=new Boolean(false);
and
when(.......).thenReturn(falseBool);
As detailed on the PowerMockito Getting Started Page, you'll need to use both the PowerMock runner as well as the #PrepareForTest annotation.
#RunWith(PowerMockRunner.class)
#PrepareForTest(DateUtils.class)
Ensure that you're using the #RunWith annotation that comes with JUnit 4, org.junit.runner.RunWith. Because it's always accepted a value attribute, it's pretty odd to me that you're receiving that error if you're using the correct RunWith type.
any(Date.class) is correct to return null: Rather than using a magic "matches any Date" instance, Mockito uses a hidden stack of matchers to track which matcher expressions correspond to matched arguments, and returns null for Objects (and 0 for integers, and false for booleans, and so forth).
So in the end,what worked for me was to export the line that does the exception to some other static function. I called it compareDates.
My implementation:
In the class that is tested (e.g - MyClass)
static boolean compareDates(Date date1, Date date2) {
return DateUtils.isEqualByDateTime (date1, date2);
}
and in the test class:
PowerMockito.mockStatic(MyClass.class);
PowerMockito.when(MyClass.compareDates(any(Date.class), any(Date.class))).thenReturn(false);
Unfortunately I can't say I fully understand why this solution works and the previous didn't.
maybe it has to do with the fact that DateUtils class is not my code, and I can't access it's source, only the generated .class file, but i'm really not sure about it.
EDIT
The above solution was just a workaround that did not solve the need to cover the DateUtils isEqualByDateTime call in the code.
What actually solved the real problem was to import the DateUtils class which has the actual implementation and not the one that just extends it, which was what I imported before.
After doing this I could use the original line
PowerMockito.mockStatic(DateUtils.class);
PowerMockito.when(DateUtils.isEqualByDateTime (any(Date.class),any(Date.class)).thenReturn(false);
without any exception.
I had a similar problem with TextUtils in my Kotlin Test Class
PowerMockito.`when`(TextUtils.isEmpty(Mockito.anyString())).thenReturn(true)
Resolved it by adding below code on top of my Test Class
#PrepareForTest(TextUtils::class)
and called mockStatic this before PowerMockito.`when`
PowerMockito.mockStatic(TextUtils::class.java)

How to access to a function of a controller from inside another controller in Symfony2?

I would like to know how to access to a function of a controller from inside another controller in Symfony2. In fact I have two controllers: "EventgroupeController" and "GroupeController". In the code of the controller "EventgroupeController" I put the instruction below:
return GroupeController::AfficheGroupeAction();
But when I run the code (or let's say the project I am developing), it displays this error message in Symfony2:
ContextErrorException: Runtime Notice: Non-static method Ikproj\GroupeBundle\Controller\GroupeController::AfficheGroupeAction() should not be called statically, assuming $this from incompatible context in C:\wamp\www\Wkayet_project\PFESymfony2\src\Ikproj\GroupeBundle\Controller\EventgroupeController.php line 104
After having a look at this link: How to access a different controller from inside a controller Symfony2 in order to know how to access a different controller from inside a controller in Symfony2, I modified the content of the file services.yml as below:
parameters:
# ikproj_groupe.example.class: Ikproj\GroupeBundle\Example
services:
# ikproj_groupe.example:
# class: %ikproj_groupe.example.class%
# arguments: [#service_id, "plain_value", %parameter%]
controllerservice:
class: Ikproj\GroupeBundle\Controller\GroupeController
Then, I replaced the instruction: return GroupeController::AfficheGroupeAction(); by the lines below:
$yourController = $this->get('controllerservice');
$yourController1 = $yourController::AfficheGroupeAction();
return $yourController1;
But I still see this error message:
ContextErrorException: Runtime Notice: Non-static method Ikproj\GroupeBundle\Controller\GroupeController::AfficheGroupeAction() should not be called statically, assuming $this from incompatible context in C:\wamp\www\Wkayet_project\PFESymfony2\src\Ikproj\GroupeBundle\Controller\EventgroupeController.php line 106
So, my question is: how can I resolve this problem and how can I access to the function AfficheGroupeAction() of the controller "GroupeController" from inside the controller "EventgroupeController"?
An action method must not be static.
$this->get('controllerservice')->youMethod();
Should work !
But with a good "application design", you should not have this need except if you want to forward a request from a controller to another ( example : backward compatibility ). In this case you can use the forward method provided by symfony2 base controller. ( http://symfony.com/doc/current/book/controller.html )

JRuby: Documentation of mappings/conversions between Java and Ruby types/classes?

I am writing a Java wrapper library around a ruby gem so I am embedding ruby within Java and not the other way around. I seem to be in the vast minority!
If I have a ruby method that returns a Time object then I can very easily convert it into a java.util.Date object on the Java side like this:
public Date getStartTime() {
IRubyObject result = RuntimeHelpers.invoke(runtime.getCurrentContext(),
this, "start_time");
return (Date) result.toJava(Date.class);
}
But I think I got lucky working this out by trial and error and not all like-seeming types can be converted in this way. I have another ruby method that returns a URI object (it could be a URI::HTTP or a URI::HTTPS in fact) but trying the obvious (given the above) conversion to a java.net.URI doesn't work (I also tried it with java.net.URL):
public URI getUri() {
IRubyObject result = RuntimeHelpers.invoke(runtime.getCurrentContext(),
this, "uri");
return (URI) result.toJava(URI.class);
}
This code compiles, but fails at run time:
Exception in thread "main" org.jruby.exceptions.RaiseException: (TypeError) cannot
convert instance of class org.jruby.RubyObject to class java.net.URI
I realise that in ruby a URI is actually a module and URI::HTTPS, etc are the classes, so I'm not entirely surprised that the above didn't work. But there's clearly a bit of internal "magic" being done for the Time/Date example so I was wondering if there were similar conversions provided for other types, which types and where they are documented.
Any pointers much appreciated.
https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby says "Conversion of Types – Ruby to Java – See the JRuby rspec source code dir spec/java_integration for many more examples. [examples, ...]".
Sure enough, coercion_spec.rb contains a lot of examples/specifications. Here's the case you already use:
describe "Time\"to_java" do
describe "when passed java.util.Date" do
it "coerces to java.util.Date" do
t = Time.now
d = t.to_java(java.util.Date)
d.class.should == java.util.Date
end
end
# [...]
end
I believe this is the best documentation currently available.

NUnit / Moq throwing a NullReferenceException error on the constructor of a variable

I am using Moq, NUnit, WPF, MVVM, Ninject.
I am writing a test for my LoginViewModel, and in the test when I use the constructor of the LoginViewModel to create a new instance, I am getting a NullReferenceException error. The code compiles and runs, (i.e. when I run the program the LoginView shows, and works with the LoginViewModel to create the correct behaviour etc) but for some reason the UnitTest is crashing.
this is the constructor:
public LoginViewModel(ILoginServices loginServices,IDialogService dialogServices)
{
InitializeFields();
_loginServices = loginServices;
_dialogService = dialogServices;
DomainList = _loginServices.GetDomainListing();
}
I have mocked the dependencies as follows:
Mock<ILoginServices> moq = new Mock<ILoginServices>();
moq.Setup(log =>
log.LoginUser(It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()))
.Callback<string, string, string>((i, j, k) => CheckArgs(i, j, k));
moq.Setup(log2 =>
log2.GetDomainListing()).Returns(new List<string> { "Domain" });
Mock<IDialogService> moq2 = new Mock<IDialogService>();
I have also tried inserting real services as the parameters.
I have verified that the mocks do work, and the objects these mocks
return are not null.
I have commented out all the code in the constructor.
I have tried inserting the line
LoginViewModel test = new LoginViewModel(_fakeLoginService,_fakeDialogService);
in front of the call to the constructor (to see if it had to do with the original local variable being disposed or something before) and this line crashed instead.
From all I can see this must be the constructor,(but not the code I have written inside it) and that this is solely related to NUnit / Moq as my code still compiles and runs fine.
I have no idea on this one guys, can anyone point me in the right direction?
[Edit]
Ok so I have run through the code and the error comes from this line of code:
ImageSource = (ImageSource)Application.Current.FindResource(_imageName);
This code is going to a ImageDictionary and getting a reference to the image for an undo button in the WindowViewModel (which my LoginViewModel inherits).
My hypotheses as to why its working in the normal running of the application, but not in the testing are:
1) Because I am running the program code through NUnit, the Application.Current object isnt getting property assigned/there is no Application.Current object to get.
**or**
2) Something to do with the fact that because the program code is being run in NUnit, the code doesn't have access to/can't resolve the ImageDictionary to find the image.
I'm leaning more strongly to the first hypothesis, but I'm as of yet not 100% sure, and I am having trouble finding the values of the Application.Current at runtime, cause when I move my cursor over the code the tooltip that normally appears showing the detail of the object that is not appearing.
My new question is: Does any of this make sense? Do you guys know if the Application.Current object exists / can be accessed when running the testing project through NUnit?
Any help will be appreciated.
You are correct. Application.Current is null for Unit tests. You can work around this by injecting the Application object as referencing singletons in code can make life tricky.