Can we a static ( A Utility class) method for a webservice - web-services

Inside a Webservice method , i have created a helper class whose responsibility is to take the XML String passed as a Method arguement to it and then construct
Array List obect from that .
My question is can i have this method as static ??
This utility methos will be called from a Webservice ?? Is this okay ??
public class UtilStaxParser {
public static List parseData(String XMLdocument) {
}
}

Of course you can... you would have found that if you had simply tried it :)
The webservice method can call a static method, but the webservice method cannot be static.

Related

Extending mail object in a cfc

I use the mail() object in cfscript. I want to extend that object so I can overwrite the setTo() method. Here is the cfc code I have written.
component extends="com.adobe.coldfusion.mail"
{
public void function setTo(String recipients) {
machineName = createObject("java", "java.net.InetAddress").localhost.getCanonicalHostName();
if (FindNoCase("devcomputer", machinename) == 0)
{
super.setTo(arguments.recipients);
}
else
{
super.setTo(this.getFrom());
}
}
}
When this runs however, I get a message saying the setTo() method does not exist at the line calling super.setTo(). Digging further I looked at the super object and it inherits from java.lang.Class, not com.adobe.coldfusion.email.
What is the proper way to extend ColdFusion's mail object so I can override the setTo() method?
The getters/setters in com.adobe.coldfusion.mail are actually not functions, but accessors. Accessors are automatically generated by ColdFusion based on the properties in the component. Properties are inherited, accessors are not!
The accessors in the mail component do nothing but set/get the value of the property. The equivalent of super.setTo(arguments.recipients); thus is variables.to = arguments.recipients;. The equivalent of this.getTo() is variables.to etc.
Note: Using accessors="true" with the component that extends="com.adobe.coldfusion.mail" does not work with inherited properties either.

return type for controller method in play framework 1.2.5

I am using play framework 1.2.5. I am using a helper method being called from the controller (its in the controller - I am not sure if it really belongs in the model or elsewhere) but its return type is void. I believe that causes the controller to return from that method and not get back to the calling method (from where the helper was called). Besides passing a return type like int or boolean, is there anything else I can do to avoid this issue?
public class TestController extends Controller {
public static controllerMethod() {
helperMethod();
}
public static void helperMethod() {
//some code
}
}
I am guessing I can either move the helper method into a model or simply pass in boolean/int as return type - any other suggestions?
Thanks
In your controllerMethod, you have to call some render method :
public static controllerMethod() {
helperMethod();
render() // or ok() to return http code 200
}
And declare your helperMethod private. Making the method private prevents the browser redirection behaviour of normal controller methods.
You don't want any extra helper methods or variables in your Controller classes! Move it to a Model class (the model class does not even have to extend Model - just don't extend Controller).
Each call to a controller method is not like a normal Java method invocation. It does a lot of extra stuff and forces the browser to redirect to the method. It will never resume the code in your original method!
So code like this in a controller method (where computeSomething is a static method of the controller)
...
computeSomething();
renderText("this will never be shown")
The only time you want to call another method in the controller is if you want to do a redirect. A typical example is checking authentication and redirecting to a login page.
You can choose to use the helper method without the browser having access to it by annotating the helper method with #Util
public class TestController extends Controller {
public static controllerMethod() {
helperMethod();
}
#Util
protected static String helperMethod() {
//some code
}
}

Zend Framework 2 + Doctrine: get Entity Manager in Model

Edit 1: it seems like I didn't explain myself very well. Class Foo is not an entity. Just a general purpose model that I would like to have an access to the entity manager.
Edit 2: I don't think there is an answer to my question. Basically, I wanted a class that can have access to the EntityManager without this class being called by the service manager, simply due to the fact that it may be called by a class who is also not called by the service manager. In other words, I was trying to achieve what Zend_Registry used to achieve in ZF1. I'll have to find another way of doing what I am trying to do.
I am trying to access Doctrine's entity manager in a model, in a similar way as it done in a controller:
$this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
The ZF2 manual (http://framework.zend.com/manual/2.0/en/modules/zend.service-manager.quick-start.html) says:
By default, the Zend Framework MVC registers an initializer that will inject the ServiceManager instance, which is an implementation of Zend\ServiceManager\ServiceLocatorInterface, into any class implementing Zend\ServiceManager\ServiceLocatorAwareInterface.
So I created a the following class:
<?php
namespace MyModule\Model;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class Foo implements ServiceLocatorAwareInterface
{
protected $services;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->services = $serviceLocator;
}
public function getServiceLocator()
{
return $this->services;
}
public function test()
{
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
}
}
Then, from another class I call this class as such:
$foo = new \MyModule\Model\Foo();
$foo->test()
which throws the following error:
PHP Fatal error: Call to a member function get() on a non-object
So, I guess I am missing something somewhere, but what? Where? How? Perhaps there is an easier to access the entity manager?
Thanks!
From your question, I see that you have mainly two misunderstandings, one about your design strategy (injecting an EntityManager on your model) and one about how things work with the service manager (ServiceLocatorAwareInterface). In my answer I'll try to focus on the second one.
Initializers are php closures that are called over each instance accessed from the Service Manager before this one returns it to you.
Here is an example of an Initializer :
// Line 146 - 150 of Zend\Mvc\Service\ServiceManagerConfig class + comments
$serviceManager->addInitializer(function ($instance) use ($serviceManager) {
if ($instance instanceof ServiceManagerAwareInterface) {
$instance->setServiceManager($serviceManager);
}
});
As you can see each time Service Manager is asked to return an instance/object that implements the ServiceManagerAwareInterface interface, it will setup/inject the Service Manager instance to it.
By the way in your previous code you omitted to implement correctly the interface as you didn't define the setServiceManager method. However, this is not your only problem.
First, if you want the Service Manager to inject itself in your Model, you need to call/construct your model instance from it (during this process it will call the initializers) through a factory for example if your class has complex dependencies.
[EDIT]
Example:
In your MyModule
namespace MyModule;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use MyModule\Model\Foo;
class Module implements ServiceProviderInterface{
//Previous code
public function getServiceConfig()
{
return array(
'instances' => array(
'myModelClass' => new Foo(),
),
);
}
Now, when you need a Foo instance you should call the Service Manager:
$serviceManager->get('myModelClass');
Don't forget defining setServiceManager method, otherwise your'e not correctly implementing the ServiceManagerAwareInterface!
I think, the only thing you’re missing, is to add your model class to the list of invokables and retreive it through the service manager.
So basically add this to your module.conf.php:
return array(
'service_manager' => array(
'invokables' => array(
'MyModule\Model\Foo' => 'MyModule\Model\Foo',
),
),
);
And instantiate your model object like this (if in a controller):
$foo = $this->getServiceLocator()->get('MyModule\Model\Foo');
$foo->test();

How to unit test a class that consumes a web service?

I have a class (lets call it A) that:
In the constructor takes a config and based on it, creates a stub of
a web service and stores a reference to it in a private field.
Has a few methods that call web methods and some stuff inbetween.
I started to create a unit test that:
Creates an instance of a class A with a dummy configuration.
Through reflection it injects the mocked web service stub.
Although that web service has plenty of methods.
Should I mock them all (in every test, with different data)?
Or maybe I should create another layer that encapsulates only the web methods that are being used?
Or there is another approach?
You should create a wrapper interface around your webservice, and make your class under test take a dependency on that interface, rather than directly on the webservice; you can then mock the interface. Only make that interface expose the methods of the webservice that you find interesting. This is known as a facade pattern, and is detailed here.
Without having a clue about what you're testing, aim for something like this:
public interface IWebserviceWrapper
{
Whatever DoStuff(int something);
}
public class WebserviceWrapper : IWebserviceWrapper
{
private WebService _theActualWebservice;
public WebserviceWrapper(Webservice theService)
{
_theActualWebService = theService;
}
public Whatever DoStuff(int something)
{
return _theActualWebservice.DoSomething(something);
}
}
Then your test would look like this (in this case, using MOQ)
public void Test_doing_something()
{
Mock<IWebserviceWrapper> _serviceWrapperMock = new Mock<IWebserviceWrapper>();
_serviceWrapperMock.SetUp(m => m.DoStuff(12345)).Returns(new Whatever());
var classUnderTest = new ClassUnderTest(_serviceWrapperMock.Object);
var result = classUnderTest.Dothings(12345);
Assert.Whatever....
}
Short answer Yes :). Long answer you should use some kind of mocking lib for example: http://code.google.com/p/mockito/ and in your unit test mock the WS stub and pass it to the tested class. That is the way of the force :)
When you unit test a class, you always want to make sure to only test that class and not include its dependencies. To do that, you will have to mock your WS to have it return dummy data when methods are called. Depending on your scenarios, you do not have to mock ALL the methods for each test, I would say only those that are used.
For an example about mocking, you can read this article: http://written-in-codes.blogspot.ca/2011/11/unit-tests-part-deux.html

Unit Testing, using properties to pass in an interface

Im reading "The art of unit testing" atm and im having some issues with using properties to pass in an interface. The book states the following: "If you want parameters to be optional, use property getters/setters, which is a better way of defining optional parameters than adding different constructors to the class for each dependency."
The code for the property example is as follows:
public class LogAnalyzer
{
private IExtensionManager manager;
public LogAnalyzer ()
{
manager = new FileExtensionManager();
}
public IExtensionManager ExtensionManager
{
get { return manager; }
set { manager = value; }
}
public bool IsValidLogFileName(string fileName)
{
return manager.IsValid(fileName);
}
}
[Test]
Public void
IsValidFileName_NameShorterThan6CharsButSupportedExtension_ReturnsFalse()
{
//set up the stub to use, make sure it returns true
...
//create analyzer and inject stub
LogAnalyzer log = new LogAnalyzer ();
log.ExtensionManager=someFakeManagerCreatedEarlier;
//Assert logic assuming extension is supported
...
}
When/how would i use this feature?? The only scenario i can think of (This is probably wrong!) is if i had two methods in one class,
Method1() retrieves the database connection string from the config file and contains some form of check on the retrieved string.
Method2() then connect to the database and returns some data. The check here could be that that returned data is not null?
In this case, to test Method1() i could declare a stub that implements the IExtensionManager Interface, where the stub has a string which should pass any error checks i have in method1().
For Method2(), i declare a stub which implements the interface, and declare a datatable which contains some data, in the stub class. id then use the properties to assign this to the private manager variable and then call Method2?
The above may be complete BS, so if it is, id appreciate it if someone would let me know and ill remove it.
Thanks
Property injection used to change object's behavior after it was created.
BTW your code is tight coupled to FileExtensionManager, which is concrete implementation of IExtensionManager. How you are going to test LogAnalyzer with default manager? Use constructor injection to provide dependencies to your objects - this will make them testable:
public LogAnalyzer (IExtensionManager manager)
{
this.manager = manager();
}