Custom Phing task with nested elements - phing

I'm creating a custom phing task and trying to pass data to it via nested xml elements. My task executes fine but errors out when it attempts to "create" a nested element. For example:
Portion of xml build file:
<mycustomtask>
<option name="opt1" value="val1"/>
</mycustomtask>
Portion of task class file:
...
public function createOption(){
return new Option;
}
...
Portion of Option class file:
class Option{
...
public function setName($str){
$this->name = $str;
}
public function setValue($str){
$this->value = $str;
}
}
My task always errors out with an exception from the Introspection Helper with "...doesn't support 'name' attribute".
Can anyone show me what I'm doing wrong here? I've started tracing back through the introspection helper class but didn't get very far. I've also tried adding the #return doc directive in my method phpdoc as I can see the introspection helper tries to parse them.
Alternatively, is there another way of passing lots of arguments/options to a custom task in xml?

Your tag class should extend the DataType class. Without that, phing will give you problems.
If that does not help, provide a paste with the minimal (but complete) code to reproduce the problem.

Related

GWT.create and wrap existing html element

Is it possible to create a TextBox using GWT.create, not the constructor, and wrap an existing HTML element?
I tried:
TextBox text=GWT.create(TextBox.class)
text.setElement(DOM.createInput()) (2)
The above fails on line (2) with "cannot set element twice ..."
I need this in order to use GwtMockito and test a component that needs to create a TextBox.
Thank you!
UIObject have a package protected replaceElement Method which will do what you like to do.
Building a wrapper in the right package like this:
package com.google.gwt.user.client.ui;
import com.google.gwt.dom.client.Element;
public class ElementReplace
{
public static void replaceElement(UIObject obj, Element elem)
{
obj.replaceElement(elem);
}
}
and it is possible to access the method.
It seems you'd have to resort to using some sort of factory:
public interface TextBoxFactory {
TextBox wrap(Element element);
}
This will get injected into your view and you'll use the factory to wrap the existing element in a TextBox. The default implementation will, of course, just use TextBox#wrap(Element), as suggested by Baz. For the purposes of your tests, you'll use an implementation that returns a Mockito mock.
Not the prettiest solution, but given the circumstances, I can't think of a "cleaner" one.

Having difficulties extending Zend_Form

Currently I have big difficulties extending Zend_Form.
I have the basic class called Forms_LpaManageEmailForm.
It is used separately and works fine.
Next I've created a new class form
called Default_Form_CartReport witch extends Forms_LpaManageEmailForm.
So the task is to render Default_Form_CartReport and slitely modificate it.
In other words I need all functionality of
Forms_LpaManageEmailForm class but with overriden _addMultiOptionsForMultiSelect() function
(what is done) and changed button label (doesn't solved).
In basic class I have hidden element named id which value is filled with
$this->_entry_id['entry_id']. When I use basic form separately - its woks fine. But
when I run extended form(Forms_LpaManageEmailForm) I see that hidden id element's value is empty. In basic class in construct section I run
Zend debugger(with this line Zend_Debug::dump($this->_entry_id['entry_id'])) to see if the
value is passed. And it's passed :) When I repeat this in init() section it shows NULL...
As I barely understand - the problem lays in init() functions, in the way it is called.
I think something is wrong with Default_Form_CartReport class skeleton.
I've uploaded code to: PASTEBIN
Really need help in this question.
Thank you!
I believe your issues are causing my the fact that Forms_LpaManageEmailForm:: __construct is calling $this->init() directly. if you open the Zend_Form, you will notice that the __construct is also calling the $this->init() function. This cause your init() function to executed twice.
Try to load all your logic & elements solely in the __construct function, and don't use the init() function. also, the __construct function in each form class should always call the parent::__construct before any additional logic.

Zend Framework Data Mapper problem

It has been a rough task to learn this framework. I am still stuck at quick start.
I am using PDO_MYSQL as my adapter. I have followed the tutorial to the letters.
At a point, it says to create application/models/GuestbookMapper.php and put the following code
class Application_Model_GuestbookMapper
{
public function save($model);
public function find($id, $model);
public function fetchAll();
}
Then it say to run this command
zf create model GuestbookMapper
The tutorials claims to insert additional methods. But in my case, it emptied the my GuestbookMapper class with this
class Application_Model_GuestbookMapper
{
}
Same goes with another command zf create model Guestbook. It empties the scripts, with just plain class defination.
Please help me !
Re-read the QuickStart carefully. You're probably skimming and getting hung up.
Here is the text:
A typical API for a data mapper is as follows:
class Application_Model_GuestbookMapper
{
public function save($model);
public function find($id, $model);
public function fetchAll();
}
And then...
In addition to these methods, we'll add methods for setting and retrieving the Table Data Gateway. To create the initial class, use the zf CLI tool:
% zf create model GuestbookMapper
Lastly...
Now, edit the class Application_Model_GuestbookMapper found in application/models/GuestbookMapper.php to read as follows:
Note that the first example is just that - an example. They are providing a sample interface of what your class will probably look like. The second block of text explains how to create your initial (empty) class. And the last block gives you the exact final code of the GuestbookMapper class.
Just add those methods again ;) Won't that work?

How to access the NUnit test name programmatically?

Is there some global state somewhere that I can access the currently-running test name?
I have tests which output files into a directory and read them back in. I'd like each test to create a directory to play in and then clean up after itself, and I don't want to push that name in (I'd have to make it unique, and then make sure each test keeps it unique; ew). I could use a GUID, but I'd like helper methods to be able to assume "this is the place where test files should be stored" without having to push that GUID around to them. Again, this augers for a global state somewhere.
Basically, I want a call like TestRunner.Current.CurrentTest.Name. Does such a thing exist?
(Assuming c#)
NUnit.Framework.TestContext.CurrentContext.Test.Name
or
NUnit.Framework.TestContext.CurrentContext.Test.FullName
or if you are really lazy and aren't driving your tests with TestCaseSource (thanks #aolszowka):
this.GetType().ToString()
I haven't upgraded to 2.5.7 yet myself, but it includes a TestContext class that seems to provide just what you're looking for: http://www.nunit.org/index.php?p=releaseNotes&r=2.5.7
Assuming one method per Test, in your NUnit code, you can use reflection to get the method name from the stacktrace.
If you write a helper method in your NUnit code called by other methods to do this file logging, you can use this syntax to check for the previous method:
string MethodName = new StackFrame(1).GetMethod().Name;
See the answers to question 44153, "Can you use reflection to find the name of the currently executing method?" for more details.
If we are using TestCaseSource tag then above solutions might not give correct answer
Try using TestContext.CurrentContext.Test.MethodName
Follow the below example
namespace NunitTests
{
public class Class1
{
static List<TestData> Data = new List<TestData>()
{
new TestData()
{
...
}
};
[Test]
[TestCaseSource(nameof(TenMBInstance))]
public void TestCase(TestData value)
{
TestContext.CurrentContext.Test.Name; //TestCase(NunitTests..TestData)
TestContext.CurrentContext.Test.MethodName; //TestCase
}
}
}

GWT Dynamic loading using GWT.create() with String literals instead of Class literals

GWT.create() is the reflection equivalent in GWT,
But it take only class literals, not fully qualified String for the Class name.
How do i dynamically create classes with Strings using GWT.create()?
Its not possible according to many GWT forum posts but how is it being done in frameworks like Rocket-GWT (http://code.google.com/p/rocket-gwt/wiki/Ioc) and Gwittir (http://code.google.com/p/gwittir/wiki/Introspection)
It is possible, albeit tricky. Here are the gory details:
If you only think as GWT as a straight Java to JS, it would not work. However, if you consider Generators - Special classes with your GWT compiler Compiles and Executes during compilation, it is possible. Thus, you can generate java source while even compiling.
I had this need today - Our system deals with Dynamic resources off a Service, ending into a String and a need for a class. Here is the solutuion I've came up with - btw, it works under hosted, IE and Firefox.
Create a GWT Module declaring:
A source path
A Generator (which should be kept OUTSIDE the package of the GWT Module source path)
An interface replacement (it will inject the Generated class instead of the interface)
Inside that package, create a Marker interface (i call that Constructable). The Generator will lookup for that Marker
Create a base abstract class to hold that factory. I do this in order to ease on the generated source code
Declare that module inheriting on your Application.gwt.xml
Some notes:
Key to understanding is around the concept of generators;
In order to ease, the Abstract base class came in handy.
Also, understand that there is name mandling into the generated .js source and even the generated Java source
Remember the Generator outputs java files
GWT.create needs some reference to the .class file. Your generator output might do that, as long as it is referenced somehow from your application (check Application.gwt.xml inherits your module, which also replaces an interface with the generator your Application.gwt.xml declares)
Wrap the GWT.create call inside a factory method/singleton, and also under GWT.isClient()
It is a very good idea to also wrap your code-class-loading-calls around a GWT.runAsync, as it might need to trigger a module load. This is VERY important.
I hope to post the source code soon. Cross your fingers. :)
Brian,
The problem is GWT.create doen't know how to pick up the right implementation for your abstract class
I had the similar problem with the new GWT MVP coding style
( see GWT MVP documentation )
When I called:
ClientFactory clientFactory = GWT.create(ClientFactory.class);
I was getting the same error:
Deferred binding result type 'com.test.mywebapp.client.ClientFactory' should not be abstract
All I had to do was to go add the following lines to my MyWebapp.gwt.xml file:
<!-- Use ClientFactoryImpl by default -->
<replace-with class="com.test.mywebapp.client.ClientFactoryImpl">
<when-type-is class="com.test.mywebapp.client.ClientFactory"/>
</replace-with>
Then it works like a charm
I ran into this today and figured out a solution. The questioner is essentially wanting to write a method such as:
public <T extends MyInterface> T create(Class<T> clz) {
return (T)GWT.create(clz);
}
Here MyInterface is simply a marker interface to define the range of classes I want to be able to dynamically generate. If you try to code the above, you will get an error. The trick is to define an "instantiator" such as:
public interface Instantiator {
public <T extends MyInterface> T create(Class<T> clz);
}
Now define a GWT deferred binding generator that returns an instance of the above. In the generator, query the TypeOracle to get all types of MyInterface and generate implementations for them just as you would for any other type:
e.g:
public class InstantiatorGenerator extends Generator {
public String generate(...) {
TypeOracle typeOracle = context.getTypeOracle();
JClassType myTYpe= typeOracle.findType(MyInterface.class.getName());
JClassType[] types = typeOracle.getTypes();
List<JClassType> myInterfaceTypes = Collections.createArrayList();
// Collect all my interface types.
for (JClassType type : types) {
if (type.isInterface() != null && type.isAssignableTo(myType)
&& type.equals(myType) == false) {
myInterfaceTypes.add(type);
}
for (JClassType nestedType : type.getNestedTypes()) {
if (nestedType.isInterface() != null && nestedType.isAssignableTo(myType)
&& nestedType.equals(myTYpe) == false) {
myInterfaceTypes.add(nestedType);
}
}
}
for (JClassType jClassType : myInterfaceTypes) {
MyInterfaceGenerator generator = new MyInterfaceGenerator();
generator.generate(logger, context, jClassType.getQualifiedSourceName());
}
}
// Other instantiator generation code for if () else if () .. constructs as
// explained below.
}
The MyIntefaceGenerator class is just like any other deferred binding generator. Except you call it directly within the above generator instead of via GWT.create. Once the generation of all known sub-types of MyInterface is done (when generating sub-types of MyInterface in the generator, make sure to make the classname have a unique pattern, such as MyInterface.class.getName() + "_MySpecialImpl"), simply create the Instantiator by again iterating through all known subtypes of MyInterface and creating a bunch of
if (clz.getName().equals(MySpecialDerivativeOfMyInterface)) { return (T) new MySpecialDerivativeOfMyInterface_MySpecialImpl();}
style of code. Lastly throw an exception so you can return a value in all cases.
Now where you'd call GWT.create(clz); instead do the following:
private static final Instantiator instantiator = GWT.create(Instantiator.class);
...
return instantiator.create(clz);
Also note that in your GWT module xml, you'll only define a generator for Instantiator, not for MyInterface generators:
<generate-with class="package.rebind.InstantiatorGenerator">
<when-type-assignable class="package.impl.Instantiator" />
</generate-with>
Bingo!
What exactly is the question - i am guessing you wish to pass parameters in addition to the class literal to a generator.
As you probably already know the class literal passed to GWT.create() is mostly a selector so that GWT can pick and execute a generator which in the end spits out a class. The easist way to pass a parameter to the generator is to use annotations in an interface and pass the interface.class to GWT.create(). Note of course the interface/class must extend the class literal passed into GWT.create().
class Selector{
}
#Annotation("string parameter...")
class WithParameter extends Selector{}
Selector instance = GWT.create( WithParameter.class )
Everything is possible..although may be difficult or even useless. As Jan has mentioned you should use a generator to do that. Basically you can create your interface the generator code which takes that interface and compile at creation time and gives you back the instance. An example could be:
//A marker interface
public interface Instantiable {
}
//What you will put in GWT.create
public interface ReflectionService {
public Instantiable newInstance(String className);
}
//gwt.xml, basically when GWT.create finds reflectionservice, use reflection generator
<generate-with class="...ReflectionGenerator" >
<when-type-assignable class="...ReflectionService" />
</generate-with>
//In not a client package
public class ReflectionGenerator extends Generator{
...
}
//A class you may instantiate
public class foo implements Instantiable{
}
//And in this way
ReflectionService service = GWT.create(ReflectionService.class);
service.newInstance("foo");
All you need to know is how to do the generator. I may tell you that at the end what you do in the generator is to create Java code in this fashion:
if ("clase1".equals(className)) return new clase1();
else if ("clase2".equals(className)) return new clase2();
...
At the final I thought, common I can do that by hand in a kind of InstanceFactory...
Best Regards
I was able to do what I think you're trying to do which is load a class and bind it to an event dynamically; I used a Generator to dynamically link the class to the event. I don't recommend it but here's an example if it helps:
http://francisshanahan.com/index.php/2010/a-simple-gwt-generator-example/
Not having looked through the code of rocket/gwittir (which you ought to do if you want to find out how they did it, it is opensource after all), i can only guess that they employ deferred binding in such a way that during compile time, they work out all calls to reflection, and statically generate all the code required to implement those call. So during run-time, you cant do different ones.
What you're trying to do is not possible in GWT.
While GWT does a good job of emulating Java at compile time the runtime is of course completely different. Most reflection is unsupported and it is not possible to generate or dynamically load classes at runtime.
I had a brief look into code for Gwittir and I think they are doing their "reflection stuff" at compile time. Here: http://code.google.com/p/gwittir/source/browse/trunk/gwittir-core/src/main/java/com/totsp/gwittir/rebind/beans/IntrospectorGenerator.java
You might be able to avoid the whole issue by doing it on the server side. Say with a service
witch takes String and returns some sort of a serializable super type.
On the server side you can do
return (MySerializableType)Class.forName("className").newInstance();
Depending on your circumstances it might not be a big performance bottleneck.