I have two mock soap service. Through groovy script, i need to declare a global variable in one mock service and access / modify that variable in another mock service when the mock service get invoke.
Declared a global variable like this in mockservice1 --> mockresponse --> operation.
myData = "12345"
I would like to access and modify 'myData' value inside, mockservice2 --> mockresponse --> operation.
I was able to access the value between different operations which are under one service(service where the value is declared).
Am using soapui free version 5.2.1.
This can be achieved by using a file to store variable value.
If both mock services are in the same SoapUI project you can use relative file path (relative to project folder)
def path = new com.eviware.soapui.support.GroovyUtils(context)
def file = new File(path.projectPath+"//YourFile.txt")
Otherwise, you can use absolute path
Reading from and writing to a file:
someVariable = file.text
file.text = "Text to be written into file"
Related
I've registered the flask-mongoengine extension in my Flask app and initialized it.
I now want to access its conn property as I want to do pure MongoDB queries too.
>> app.extensions
{'csrf': <flask_wtf.csrf.CSRFProtect object at 0x00000213B72AB940>,
'mail': <flask_mail._Mail object at 0x00000213B72ABCF8>,
'mongoengine': {
<flask_mongoengine.MongoEngine object at 0x00000213B72ABDD8>: {
'app': <Flask 'app'>,
'conn': MongoClient(host=['xxx'], document_class=dict, tz_aware=False, connect=True, ssl=True, replicaset='Cluster0-shard-0', authsource='admin', retrywrites=True, read_preference=Primary())
}
},
'rq2': <flask_rq2.app.RQ object at 0x00000213B5DE8940>,
'security': <flask_security.core._SecurityState object at 0x00000213B734EE10>
}
Is there a way to access the conn property other than the very convoluted (and error-prone):
>> list(app.extensions.get('mongoengine').values())[0].get('conn')
MongoClient(host=['xxx'], document_class=dict, tz_aware=False, connect=True, ssl=True, replicaset='Cluster0-shard-0', authsource='admin', retrywrites=True, read_preference=Primary())
Does flask-mongoengine have a method to access its properties?
The MongoEngine instance has a connection attribute, use that.
You don't need to use app.extensions; that's more of an internal data structure for extensions to keep track of their own state when they need to access this from the current app context.
In your own code, just keep a reference to the MongoEngine instance you created. The documentation uses:
db = MongoEngine(app)
or
db = MongoEngine()
# in an app factory, attach to an app with db.init_app(app)
and so you can use:
db.connection
Next, there is also a current_mongoengine_instance() utility function that essentially gives you the same object as what your code already achieved. Use it like this:
from flask_mongoengine import current_mongoengine_instance
current_mongoengine_instance().connection
As a side note: the way this extension uses app.extensions is ... over-engineered and redundant. The rationale in the source code is:
# Store objects in application instance so that multiple apps do not
# end up accessing the same objects.
but multiple apps already have separate app.extensions dictionaries. While this method does let you use multiple mongoengine connections, you still then can't use this data structure to distinguish between different connections with only the current app context. The implementation for current_mongoengine_instance() only further illustrates that the extension doesn't have a proper strategy for handling multiple connections. You just get the 'first' one, whatever that may mean in the context of unordered dictionaries. The Flask SQLAlchemy extension instead uses a single extension instance to manage multiple connections via a system called binds.
You can also reach the underlying pymongo.Collection from any of your Document class by
class MyDocument(Document):
name = StringField()
MyDocument(name='John').save()
coll = MyDocument._get_collection()
print(coll.find_one({'name': 'John'}))
I'm new to WireMoc. How do i go about Downloading a file using WireMoc stubbing framework?
This is what i have so far
var stub = FluentMockServer.Start(new FluentMockServerSettings
{
Urls = new[] { "http://+:5001" },
StartAdminInterface = true
});
stub.Given(
Request.Create()
.WithPath("/myFile")
.UsingPost()
.WithBody("download file"))
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/multipart")
you can use withBodyFile api of wiremock
stubFor(get(urlEqualTo("/body-file"))
.willReturn(aResponse()
.withBodyFile("path/to/myfile.xml")));
However
To read the body content from a file, place the file under the __files directory. By default this is expected to be under src/test/resources when running from the JUnit rule. When running standalone it will be under the current directory in which the server was started. To make your stub use the file, simply call bodyFile() on the response builder with the file’s path relative to __files:
But you can set custom path while starting wiremock using
wireMockServer = new WireMockServer(wireMockConfig().port(portNumber).usingFilesUnderClasspath("src/main/resources/"));
Now it will look for files in /src/main/resources/__files/
The source for above information
http://wiremock.org/docs/stubbing/
https://github.com/tomakehurst/wiremock/issues/129
Given a JAX-RS web service deployed under Tomcat, how can I make some of the files accessible directly from the browser by specifying the URL like http://site/path/file?
Let's say I have web service method returning an HTML web page and I need, within that page, to load a CSS file or an image file stored in the web service directory. For example:
#GET
#Path("/")
#Produces(MediaType.TEXT_HTML)
public synchronized String root() {
String head = "<head><link href=\"path/style.css\" rel=\"stylesheet\"></head>";
String head = "<body><img src=\"path/image.jpg\"/></body>";
return "<html>"+ head + body + "<html>";
}
Where should I put the file within the web service directories (WebContent, META-INF, WEB-INF, etc) and what path should I put in the html page?
You basically have three choices: absolute, relative or root links.
Absolute links work if you have your files as external resources. Relative URLs are most of the time a pain for static resources like styles, scripts or images because they must be resolved starting from the location that refers to them (they can be in various forms like images/image.jpg, ../image.jpg, ../images/image.jpg etc).
So a preferred way is to have styles, scripts or images at known positions within your application and access it with root links (slash prefixed URLs) like /Images/image.jpg.
Your folders must be in the folder of the application (WebContent in your question). Placing something under WEB-INF hides the resource and clients can no longer access it.
These links resolve to the root of your application so you must account for the context path. A basic example would be something like this:
#GET
#Path("whatever_path_might_be")
#Produces(MediaType.TEXT_HTML
public String root(#Context ServletContext ctx) {
String ctxPath = ctx.getContextPath();
String stylesFolder = ctxPath + "/Styles";
String imagesFolder = ctxPath + "/Images";
String head = "<head><link href=\"" + stylesFolder + "/style.css\" rel=\"stylesheet\"></head>";
String body = "<body><img src=\"" + imagesFolder + "/image.jpg\"/></body>";
return "<html>"+ head + body + "<html>";
}
This is a basic example, I'm sure you can find ways to improve it. You could event have these paths in a .properties file and loaded as general configuration. This will later allow you to switch from something like:
resources.cssFolder=/appcontext/styles
resources.imgFolder=/appcontext/images
to something like:
resources.cssFolder=http://external.server.com/styles
resources.imgFolder=http://external.server.com/images
without changing a line of code.
i need to create a webservices with symfony2 ive read the official article http://symfony.com/doc/current/cookbook/web_services/php_soap_extension.html
in the example it creates a instance of SoapServer with a parameter routing a .wsdl file, what is this file? i didnt found too much documentation about soap in symfony. some help with this please?
public function indexAction()
{
$server = new \SoapServer('/path/to/hello.wsdl');
$server->setObject($this->get('hello_service'));
$response = new Response();
$response->headers->set('Content-Type', 'text/xml; charset=ISO-8859-1');
ob_start();
$server->handle();
$response->setContent(ob_get_clean());
return $response;
}
I'm not sure if you've found your answer or not. Just for anybody else that might run into such a problem:
WSDL is the language in which the Web Services are defined and described. It's basically a XML file containing the input/output parameters of each and every function that are served by a server. it also contains some information about the server itself, that's providing the services.
in order to be able to create a webservice, you need to use the code you've provided, which would in fact prepare Symfony to serve the clients on "/path/to/hello.wsdl" (in my example this path is /YourDesiredPathFor/services.wsdl), and also, you need to provide a valid WSDL document that contains the information mentioned above in correct WSDL format. the problem is that Symfony (or even PHP itself for this matter) has no means of creating the file automatically.
to solve the matter, you need to use an external WSDL generator. I'd suggest using PHP-WSDL-Creator. It uses annotations written inside php files to create the WSDL file and also runs the SoapServer. that means that you won't even need the code that you've provided. it also has proper interfaces and addons that provide you with clients for different protocols and languages.
you need to tweak it a little bit though! if you want it to be by symfony standards, i think you would need to rewrite some parts of it; but if you'd like to use it as an external library, it could also work!
the way i did it was by copying the extracted files into ./vendor/php_wsdl/lib/php_wsdl/src (long it is, isn't it? maybe an easier path would also work!); then defined a php_wsdl.php in ./vender/php_wsdl/lib/php_wsdl:
<?php
require_once __DIR__. '/src/class.phpwsdl.php';
class WSDL_PhpWsdl extends PhpWsdl{
}
next, in the "./app/autoload.php", i added the following line to enable Symfony to use the created extension:
require_once __DIR__. '/../vendor/php_wsdl/lib/php_wsdl/php_wsdl.php';
just one thing! the extension needs a "cache" folder in order to cache the created wsdl files and all. unfortunately because i need to finish the project quickly, i don't have enough time to manage the cache folder as it should be. there are definitely better ways than my way, and i would really be glad to know about them.
anyway, now you need to use the extension's capabilities! to do so, i created a "ServerController" for the bundle i was using:
<?php
namespace Tara\PageControllerBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class ServiceController extends Controller
{
function wsdlAction(){
\PhpWsdlServers::$EnableRest = false;
$soap= \WSDL_PhpWsdl::CreateInstance(
null, // PhpWsdl will determine a good namespace
$this->generateUrl('service_wsdl', array(), true), // Change this to your SOAP endpoint URI (or keep it NULL and PhpWsdl will determine it)
__DIR__. '/cache', // Change this to a folder with write access
Array( // All files with WSDL definitions in comments
dirname(__FILE__). '/../Services/MyService.php'
),
null, // The name of the class that serves the webservice will be determined by PhpWsdl
null, // This demo contains all method definitions in comments
null, // This demo contains all complex types in comments
false, // Don't send WSDL right now
false // Don't start the SOAP server right now
);
if($soap->IsWsdlRequested()) // WSDL requested by the client?
$soap->Optimize=false; // Don't optimize WSDL to send it human readable to the browser
$soap->RunServer();
}
}
as you can see, the path to the cache folder is on a local directory, which means it has to be created manually and in ./src/Tara/PageControllerBundle/Controller (obviously in my case; you will need to change the paths). I'm sure there are better ways to manage the cache folder.
there is a line there:
dirname(__FILE__). '/../Services/MyService.php
this line tells the extension where to look for annotations in order to create the WSDL page. you also need to define a route to "service_wsdl":
service_wsdl:
pattern: /YourDesiredPathFor/services.wsdl
defaults: {_controller: TaraPageControllerBundle:Service:wsdl}
as you can see, the controller is ServiceController and the function responsible for it is wsdlAction; the exact function that was defined!
just as an example, i would provide my own MyService.php:
<?php
namespace Tara\PageControllerBundle\Services;
use Tara\PageControllerBundle\Model\...
/**
* #service Tara\PageControllerBundle\Services\MyService
*/
class MyService
{
/**
* Function Create
*
* #param string $link
* #param string $title
* #param string $image
* #param string $description
* #return boolean Status of the creation
* #pw_rest POST /YourDesiredPathForAction/create Create The Object
*
*/
public function Create($link, $title, $image, $description)
{
// your code that handles the data goes here. this is not a part of the annotations!
return (bool)$result;
}
}
now, you might be able to use a SoapClient to connect to your web service at
http: //your-server.something/YourDesiredPathFor/services.wsdl?wsdl
and call the Create function! you can also check the output of the extension by opening the above written address. the extension also provides a "human-readable" version at
http: //your-server.something/YourDesiredPathFor/services.wsdl.
i would be glad to know if this was any help to anyone! :)
SOAP is a more general concept that Symfony assumes you are familiar with. There is an example WSDL at the bottom of the page that you link to. Take a look at tutorials about SOAP and WSDL and then try to recreate what they're doing in the Symfony page.
SOAP Tutorial
WSDL Tutorial
Goal:
Retrieve data from Dynamics CRM 2011 to my database from SQL server R2 by using webservice through integration services (SSIS). Webservice needed to be located inside of SSIS. Gonna use the data for data warehouse.
Problem:
How do I do it?
We only write to Dynamics so I can't address the specific method name but the general idea below should get you started.
Assumptions
Two variables have been defined in your package and they are passed to the script component as ReadOnlyVariables: CrmOrganizationName, CrmWebServiceUrl.
A script component has been added to the dataflow as a Source component. On the Inputs and Outputs tab, an appropriate number of columns have been added to Output 0 (or whatever you define your output collection as) with appropriate data types.
Inside the script, add a web reference to your CRM instance. This code assumes it's called CrmSdk.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
// web reference
using CrmSdk;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
public override void CreateNewOutputRows()
{
// Get a reference to the CRM SDK
CrmSdk.CrmService CrmService = new CrmSdk.CrmService();
// An Authentication Token is required because CRM requires an OrganizationName
// to identify the Organization to be used
CrmSdk.CrmAuthenticationToken token = new CrmSdk.CrmAuthenticationToken();
token.AuthenticationType = 0;
token.OrganizationName = this.Variables.CrmOrganizationName;
CrmService.CrmAuthenticationTokenValue = token;
// Use default credentials
CrmService.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Get the web service url from the config file
CrmService.Url = this.Variables.CrmWebServiceUrl;
//////////////////////////////////////////////////
// This code is approximate
// Use the appropriate service call to get retrieve
// data and then enumerate through it. For each
// row encountered, call the AddRow() method for
// your buffer and then populate fields. Be wary
// of NULLs
//////////////////////////////////////////////////
foreach (CrmSdk.entity person in CrmService.Get())
{
Output0Buffer.AddRow();
Output0Buffer.FirstName = person.FirstName;
Output0Buffer.LastName = person.LastName;
}
}
}
Caveats
There is no error handling, checks for nulls or anything elegant. The service should probably have been defined with the using statement, etc, etc, etc. It should provide an appropriate starting point for understanding how to consume a web service and load data into the pipeline.
The easiest solution for your requirement is to use a third-party library for SSIS. The commercial COZYROC SSIS+ library includes Dynamics CRM adapters, which support all deployment models: Premise, Live, Hosted, Federation, Office 365.