This question already has answers here:
Why method overloading is not allowed in WCF?
(3 answers)
Closed 8 years ago.
Can I have two operations with the same name (but diferentt signature) in the same service?
Example:
[ServiceContract]
public interface IMyService {
[OperationContract]
bool MyOperation(string target);
[OperationContract]
bool MyOperation(List<string> targets); }
I really need to support different signatures because I have several teams consuming my service and only one team needs the second signature (I don't want the rest of the team having to change their code).
Any thoughts?
No, you really cannot have the same named operations for the contract, but you can separate them between two contracts:
[ServiceContract]
public interface IMyService
{
[OperationContract]
bool MyOperation(string target);
}
[ServiceContract]
public interface IMyServiceV2
{
[OperationContract]
bool MyOperation(List<string> targets);
}
[ServiceContract]
public class MyService : IMyService, IMyServiceV2
{
public bool MyOperation(string target)
{
/* your code*/
return true;
}
public bool MyOperation(List<string> targets)
{
/* your code*/
return true;
}
}
And expose two endpoints:
<services>
<service name="YourNamespace.MyService ">
<endpoint
address="http://localhost:8000/v1"
binding="webHttpBinding"
contract="YourNamespace.IMyService" />
<endpoint
address="http://localhost:8000/v2"
binding="webHttpBinding"
contract="YourNamespace.IMyServiceV2" />
</service>
</services>
Or you can set Name param for OperationContract, but for SOA service it will have the same result as renaming function name.
Related
In iTop, How is it possible to save caller's IP address in tickets (User Request and Incident)
I tried to modify datamodel.itop-tickets.xml in my extension module. I added a field named 'ip' successfully but in <methods> section I can not get client's IP using $_SERVER['REMOTE_ADDR'] .
<methods>
<method id="DBInsertNoReload" _delta="redefine">
<static>false</static>
<access>public</access>
<type>Overload-DBObject</type>
<code><![CDATA[
public function DBInsertNoReload()
{
$oMutex = new iTopMutex('ticket_insert');
$oMutex->Lock();
$iNextId = MetaModel::GetNextKey(get_class($this));
$sRef = $this->MakeTicketRef($iNextId);
$this->Set('ref', $sRef);
$iKey = parent::DBInsertNoReload();
$oMutex->Unlock();
return $iKey;
$this->Set('ip', $_SERVER['REMOTE_ADDR'] );
}
]]></code>
</method>
</methods>
There is another option, in itop customs extension you can include another datamodel. (you can use XML or PHP datamodel).
So, you have to create a new php file and write the class you want inside to extend the datamodel. You have to extends them with : https://www.combodo.com/documentation/api-ref-extensions/packages/Extensibility.html
If you use the interface "iApplicationObjectExtension", you can use the method OnDBInsert to set other field in your object/
for example
Class YourClassName implements iApplicationObjectExtension {
public function OnIsModified($oObject){}
public function OnCheckToWrite($oObject){}
public function OnCheckToDelete($oObject){}
public function OnDBUpdate($oObject, $oChange = null){}
public function OnDBDelete($oObject, $oChange = null){}
public function OnDBInsert($oObject, $oChange = null) {
if ($oObject instanceof UserRequest) {
// Do what you want with $oObject
$oObject->DBUpdate(); // Update object
}
}
}
After lots of attempts I finally found the solution :)
We must redefine a method of type LifeCycleAction and so I've just redefined ComputeImpactedItems method in both Inciudent and UserRequest classes.
For make it much clear I show one of them here:
<class id="Incident">
<methods>
<method id="ComputeImpactedItems" _delta="redefine">
<static>false</static>
<access>public</access>
<type>LifecycleAction</type>
<code><![CDATA[ public function ComputeImpactedItems()
{
// This method is kept for backward compatibility
// in case a delta redefines it, but you may call
// UpdateImpactedItems directly
$this->UpdateImpactedItems();
// This line is added by this exstension for saving caller's ip
$this->Set('ip', $_SERVER['REMOTE_ADDR']);
}]]></code>
</method>
</methods>
</class>
I m confused about using annotations #beforeClass,afterClass, beforeSuite,afterSuite in testNG.
I understand test structure below:
package mytestNG.learning.it ;
public class sample_not_working {
#Test
//take action - click on links, input data etc
public void main() {
}
#BeforeMethod
//do stuff like setup browser etc
public void beforeMethod() {
}
#AfterMethod
//close browser
public void afterMethod() {
}
}
But what do you do in beforeclass,afterClass and test? What file is it?
Is it a class that runs other classes?
Next, afterSuite, beforeSuite and #test :
public class sample_not_working {
#Test
public void main() {
//WHAT KINDA CODE YOU PUT HERE?
}
#BeforeSuite
//WHAT KINDA CODE YOU PUT HERE?
public void beforeMethod() {
}
#AfterSuite
public void afterMethod() {
//WHAT KINDA CODE YOU PUT HERE?
}
}
My question is about semantics, the meaning, not actual code. I read the testNG docs - did not help.
If you have the following testng.xml:
<suite name="MySuite">
<test name="MyBigTest">
<classes>
<class name="test.sample.firstTestClass"/>
<methods>
<include name="a" />
<include name="b" />
</methods>
<class name="test.sample.secondTestClass"/>
<methods>
<include name="c" />
<include name="d" />
</methods>
</classes>
</test>
</suite>
Then...
#BeforeSuite and #AfterSuite will run before/after MySuite
#BeforeTest and #AfterTest will run before/after MyBigTest
#BeforeClass and #AfterClass will run before/after firstTestClass and secondTestClass
#BeforeMethod and #AfterMethod will run before/after a, b, c and d methods
For example you can set up your environment in #BeforeSuite or you can use #BeforeTest to open a browser and at the end of the testmethods you can close it by using #AfterTest, etc...
That's really depend on what are you testing and how you are doing it. I usually put drivers in #BeforeSuite and i quit them in #AfterSuite.
in #AfterClass (if im using it) i'm placing logs for whole class [about fields] and for example change value of some variables.
in #BeforeClass i sometimes initialize variables/fields.
But in the end, thoes annotation are for helping you and they have been created for easily executed your ideas.
You may want to understad it using below example. It does not have #AfterClass / #BeforeClass. But it helps to understand structure.
package com.kagrana.base;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import com.kagrana.DTO.TestCase;
import com.kagrana.DTO.WebDriverConfig;
import com.kagrana.util.Log;
public abstract class BaseActions {
protected WebDriver driver;
protected static Log log;
protected WebDriverConfig config;
protected String baseURL;
protected TestCase testCase;
private static int testCaseCount = 1;
/**
* This gets invoked even before suite starts.
* #param ReportLocation
*/
#Parameters({"ReportLocation"})
#BeforeSuite
public void beforeSuite(#Optional String ReportLocation){
log = new Log();
}
#BeforeMethod
#Parameters({ "remoteURL", "baseURL", "OS", "browser",
"version", "internal" })
public void beforeTest(String remoteURL, String baseURL,
String OS, String browser, String version, String internal)
throws IOException {
this.testCase = new TestCase();
this.testCase.setExecutionEnvironment("{browser:"+browser+",browserVersion:"+version+",OperatingSystem:"+OS+"}");
this.testCase.setParentURL(baseURL);
this.testCase.setTestCaseId("KT"+testCaseCount++);
this.testCase.setScreenshotDirectory(log.getReportDirectory()+"\\images");
config = new WebDriverConfig();
config.setRemoteURL(remoteURL);
this.baseURL = baseURL;
config.setOS(OS);
config.setBrowserName(browser);
config.setBrowserVersion(version);
config.setIntenal(Boolean.parseBoolean(internal));
driver = xRemoteWebDriver.getInstance(config, log);
driver.manage().window().maximize();
driver.get(this.baseURL);
}
#AfterMethod
public void afterTest(ITestResult itr) {
testCase.setExecutionTime((itr.getEndMillis() - itr.getStartMillis()));
testCase.setTestCaseName(itr.getName());
log.addTestCase(testCase);
try {
driver.close();
} catch (Exception ignore) {
}
try {
driver.quit();
} catch (Exception ignore) {
}
}
#AfterSuite
public void afterSuite(ITestContext itc) throws IOException{
log.setTestSuiteName(itc.getSuite().getName());
log.writeReport();
log.zipAndEmailFile();
}
}
Source: https://github.com/selenium-webdriver-software-testing/kspl-selenium-helper/blob/master/src/main/java/in/mayurshah/base/BaseActions.java
Most of the time people use #BeforeMethod and #AfterMethod for setup and tearing down driver.
For this and other common automation needs, there are TestNG extensions available to use Selenium with TestNG that provides such implementation inbuilt. For example, one of the framework abstracting driver management outside the code so you test and related code be neat and clean and you don't need to worry about driver management and other common automation needs for web or mobile automation.
I would like to do an ESB solution, where I want to use a generic based webservice.
I can do the definition, generate all needed classes, the service exists, but the wsdl deficient. Missing the "generic part", that part what defined by generic type.
The ancestor:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(propOrder = { "header", "body" })
public abstract class WSRequest<T> {
protected RequestHeader header;
protected T body;
public RequestHeader getHeader()
{
return header;
}
public void setHeader(RequestHeader header)
{
this.header = header;
}
public T getBody()
{
return body;
}
public void setBody(T body)
{
this.body = body;
}
}
And the descendant:
public class PartnerRequest extends WSRequest<PartnerData>
{
}
The service work correctly, but the generated wsdl doesn't contain the PartnerData structure.
I'm new in WS part, so that is the real possibility it is impossible.
Please help me to solve the problem (or reject this idea)
Thx!
Feri
So, the problem was that, the base XSD was too complex. (I generated it by an XML, and th generator program made very elegant xsd, what was unusable! :-( )
Too complex mean:
....
<xs:element ref="ugyfelKod"/>
...
<xs:element name="ugyfelKod" type="xs:NCName"/>
...
In my JavaEE7-project, I am using spring-data-neo4j standalone in "Advanced Mapping" mode (using spring-aspects). Everything works fine so far: CRUD on entities within a transaction, where the transaction is started manually or via #Transactional-annotation.
In my usecase, my view accesses an entity "directly":
// User
#NodeEntity
public class User {
private String firstName;
// getter, setter, ...
}
// SessionBean
#SessionScoped
#Named
public class SessionBean {
#Transactional
public User getUser() {
User user = ...;
System.out.println(user.getFirstName()); // (1) gives firstName-value.
return user;
}
}
// sometpl.xhtml
${sessionBean.user.firstName} // (2) gives "null".
Somehow, this behavior (difference between (1) and (2)) is wanted, as spring-data-neo4j supposes read-access only within a transaction.
But I want to have my usecase(2) working (returning the user's firstName, not "null"). Is there any way to achieve this? So let's say, starting transaction automatically in read-access-case? Implicit read-transactions-support?
My workaround:
Use a RequestScoped bean to start a transaction in "preRenderView" and to close this tx when the bean is destroyed.
This does not work on ajax-calls!
#Named
#RequestScoped
public class SpringDataNeo4jHelperBean {
#Inject
#Named
private Neo4jTemplate neoTemplate;
private Transaction tx;
#PreDestroy
public void finishTransaction() {
if (this.tx != null) {
this.tx.success();
this.tx.finish();
}
}
public void startReadOnlyTransaction() {
if (!this.neoTemplate.getGraphDatabase().transactionIsRunning()) {
this.tx = this.neoTemplate.getGraphDatabaseService().beginTx();
}
}
}
In some template, for example s.th. like a central layout.xhtml:
<f:metadata>
<f:event type="preRenderView" listener="#{springDataNeo4jHelperBean.startReadOnlyTransaction()}" />
</f:metadata>
I'm trying to test my Session Beans with JUnit, but I can't. I've tried a lot of method, but still get some exceptions.
Here is what I need:
I have a few Stateless Session Beans I need to test. Each has the same #PersistenceContext and uses an EntityManager
With my test cases I need to test their methods. For instance: if I add an user with username X and then I try to add another one with the same username, I want to catch an Exception.
Can someone provide a simple and short generic test example? I've already read many, but I always get an error (I get NullPointerException for the EntityManager when I call a method like: sessionBean.method() (which does, for instance, entityManager.find(...)), or I am not able to initialize the Context, or other PersistenceException).
You might be interested in one of the latest posts of Antonio Goncalves:
WYTIWYR : What You Test Is What You Run
It tells about testing EJB with EntityManager using:
Mockito,
Embedded EJB Container,
Arquillian.
I solved creating a Stateless Session Bean and injecting its Entity Manager to test classes. I post the code in case someone will need it:
#Stateless(name = "TestProxy")
#Remote({TestProxyRemote.class})
public class TestProxy implements TestProxyRemote {
#PersistenceContext(unitName = "mph")
private EntityManager em;
#Override
public void persist(Object o) {
em.persist(o);
}
#Override
public void clear() {
em.clear();
}
#Override
public void merge(Object o) {
em.merge(o);
}
#Override
#SuppressWarnings({ "rawtypes", "unchecked" })
public Object find(Class classe, String key) {
return em.find(classe, key);
}
#Override
#SuppressWarnings({ "rawtypes", "unchecked" })
public Object find(Class classe, long key) {
return em.find(classe, key);
}
#SuppressWarnings("rawtypes")
#Override
public List getEntityList(String query) {
Query q = em.createQuery(query);
return q.getResultList();
}
}
public class MyTest {
#BeforeClass
public static void setUpBeforeClass() throws NamingException {
Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
env.setProperty(Context.PROVIDER_URL, "localhost:1099");
env.setProperty("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
jndiContext = new InitialContext(env);
try {
proxy = (TestProxyRemote) jndiContext.lookup("TestProxy/remote");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
Then I can use proxy.find() to get the entities I need, o proxy.getEntityList() to execute a query to retrieve all the instance of an Entity. Or I can add other methods if I want.
Unitils provides a really cool support for JPA. Unitils can be used with JUnit or TestNG and in case you need a mocking framework, Unitils provides its own mocking module as well as support for EasyMock.
#JpaEntityManagerFactory(persistenceUnit = "testPersistenceUnit")
#DataSet(loadStrategy = RefreshLoadStrategy.class)
public class TimeTrackerTest extends UnitilsTestNG {
#TestedObject
private TimeTrackerBean cut = new TimeTrackerBean();
#InjectInto(target="cut",property="em")
#PersistenceContext
private EntityManager em;
#Test
#DataSet("TimeTrackerTest.testAddTimeSlot.xml")
public void yourTest() {
...
}
}
#JpaEntityManagerFactory - Used to specify your persistence unit. It automatically picks up the persistence.xml from your project classpath.
#DataSet - Just in case you need to load any test data you can use this.
#TestedObject - Marks your Class Under Test
#PersistenceContext - Automatically creates your EntityManager instance from the configurations made in the persistence.xml - PersistenceUnit.
#InjectInto - Injects the em instance into the target (cut)
For more information refer this.
Hope this helps.
I'm using Needle for this. It works well with Mockito and EasyMock if you want to mock other objects.
First I write a persistencte.xml for tests (src/test/resources/META-INF) like this:
<persistence-unit name="rapPersistenceTest" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:~/test"/>
...
</properties>
</persistence-unit>
In my Junit-Testclass I write:
public class DaoNeedleTest {
//here Needle will create persistenceContext for your testclass
public static DatabaseRule databaseRule = new DatabaseRule("rapPersistenceTest");
//here you can get the entityManager to manipulate data directly
private final EntityManager entityManager = databaseRule.getEntityManager();
#Rule
public NeedleRule needleRule = new NeedleRule(databaseRule);
//here you can instantiate your daoService
#ObjectUnderTest
DAOService daoService;
#Test
public void test() {
//if your method needs a transaction here you can get it
entityManager.getTransaction().begin();
daoService.yourMethod();
entityManager.getTransaction().commit();
}
You also need a Needle-configuration File in src/test/resources, where you tell what kind of Mock-provider you are using. E.g. I'm using Mockito:
mock.provider=de.akquinet.jbosscc.needle.mock.MockitoProvider
That's it.