Accessing WSO2 ESB proxy in java program - wso2

I have configured one wsdl proxy for external wsdl in WSO2 esb. Its successfully created proxy. While creating proxy, I have not selected Publish Same Service Contract check box. If we are consuming external web services, is it mandatory to check? When I click on try it, it is not showing operations which are available in wsdl.
If at all the above issues gets solved, we need to access the proxy from our java project. How can we access WSO2 ESB proxy in our java program?
Thanks in advance.
Thanks,
Raghu

Yes you need to check Publish Same Service Contract if you want to publish the same WSDL.
in java code you can write a simple axis2 client like shown below. To the enxpoint of your proxy.
public OMElement sendReceive(OMElement payload, String endPointReference, String operation)
throws AxisFault {
ServiceClient sender;
Options options;
OMElement response = null;
try {
sender = new ServiceClient();
options = new Options();
options.setTo(new EndpointReference(endPointReference));
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
options.setTimeOutInMilliSeconds(45000);
options.setAction("urn:" + operation);
sender.setOptions(options);
response = sender.sendReceive(payload);
} catch (AxisFault axisFault) {
throw new AxisFault("AxisFault while getting response :" + axisFault.getMessage(), axisFault);
}
Assert.assertNotNull(response);
return response;
}
You can get the sample payload by tying a tool like soap UI.
Thank You,
Dharshana.

Try like this:
CentralUuidService service = new CentralUuidService(new URL("http://wls02.tigeritbd.com:8280/services/CentralUuidService?wsdl"),new QName("http://bean.service.uuid.gov.bd/", "CentralUuidService"));
GetBirthPlaceServiceResponse response = service.getCentralUuidServiceHttpSoap11Endpoint().getBirthPlace(request);
if(response != null) {
System.out.println("Operation status is:"+response.isOperationStatus());
}
}

Related

Automatic NTLM Authentication for WSO2 ESB

I have a WCF Web Service sitting on a client's IIS server secured with NTLM authentication - I have no control over the authentication configuration on that server.
I need to integrate my WSO2 ESB server with this service, but I can't find a way to get the ESB to authenticate automatically. I have successfully pushed requests through the ESB to the service with web applications, but I was prompted to provide my Windows credentials during that process - I would like for this to not happen.
I have attempted to set up an NTLM proxy on my server, but couldn't figure this out either.
Any guidance would be much appreciated.
Strainy
Ok, i found your answer. As you know, WSO2 ESB uses Axis2 for web services. You must add NTLM configuration in Axis2 config file (ESB_HOME/repository/conf/axis2/axis2.xml).
This links, describes the configuration.
http://wso2.com/library/161/
http://axis.apache.org/axis2/java/core/docs/http-transport.html
There were a few components to getting this working correctly. It's hard to find it all written down in one place, so I'll attempt to provide an end-to-end overview here.
I first had to use a class mediator within my WSO2 ESB in-sequence to handle the sending and the NTLM authentication. The class mediator references a custom class which takes the message context from the mediation flow (called the Synapse message context) and extracts the SOAP envelope. I then loaded the Synapse SOAP envelope into an Axis2 message context object. I then used an Axis2 client along with the message context to submit my authenticated request to the server. The authentication for NTLM through Axis2 comes from the JCIFS_NTLMScheme class, which you can reference here.
Note: you'll have to play with the logging configuration in that class to make it work with WSO2. I just removed the " org.sac.crosspather.common.util* " libraries and altered any logging I saw to use the Apache Commons logging capability
Create a Custom Mediator Project in WSO2 Developer Studio
Create a new project in Developer studio. Right click the project node in the project explorer and select "New > Mediator Project".
This will generate a bit of boilerplate code for you - that is, a class which extends AbstractMediator and which implements an "mediate()" method which Synapse will call when it comes to executing the logic defined within your sequence.
public class NTLMAuthorisation extends AbstractMediator {
public boolean mediate(MessageContext context){
//Mediation Logic
return true;
}
}
Expose Some Variables/Properties to the User
The class mediator looks for variables which are publicly accessible and exposes them in the WSO2 configuration. This is helpful before you can create a re-usable mediator which adapts itself to properties or values defined in the WSO2 Carbon Web UI. Here we need to expose seven variables: soapAction, SoapEndpoint, domain, host, port, username, and password. Expose the variables by defining your instance variables, along with their accessors and mutators.
This is all really quite useful for using the WSO2 Secure Vault to store your NTLM password and fetching other configuration from a system registry with properties.
public class NTLMAuthorisation extends AbstractMediator {
private String soapAction;
private String soapEndpoint;
private String domain;
private String host;
private int port;
private String username;
private String password;
public boolean mediate(MessageContext context) {
//Mediation Logic
return true;
}
public void setSoapAction(String _soapAction){
soapAction = _soapAction;
}
public String getSoapAction(){
return soapAction;
}
public void setSoapEndpoint(String _soapEndpoint){
soapEndpoint = _soapEndpoint;
}
public String getSoapEndpoint(){
return soapEndpoint;
}
public void setDomain(String _domain){
domain = _domain;
}
public String getDomain(){
return domain;
}
public void setHost(String _host){
host = _host;
}
public String getHost(){
return host;
}
public void setPort(int _port){
port = _port;
}
public int getPort(){
return port;
}
public void setUsername(String _username){
username = _username;
}
public String getUsername(){
return username;
}
public void setPassword(String _password){
password = _password;
}
public String getPassword(){
return password;
}
}
The Custom Mediation Logic
Make sure you created an JCIFS_NTLMScheme class from here and have added the org.samba.jcifs dependency to your Maven dependencies like so:
<dependency>
<groupId>org.samba.jcifs</groupId>
<artifactId>jcifs</artifactId>
<version>1.3.17</version>
</dependency>
Now you can use the following mediate method in your custom mediator class:
public boolean mediate(MessageContext context) {
//Build NTLM Authentication Scheme
AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, JCIFS_NTLMScheme.class);
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername(username);
auth.setPassword(password);
auth.setDomain(domain);
auth.setHost(host);
auth.setPort(port);
ArrayList<String> authPrefs = new ArrayList<String>();
authPrefs.add(AuthPolicy.NTLM);
auth.setAuthSchemes(authPrefs);
//Force Authentication - failures will get caught in the catch block
try {
//Build ServiceClient and set Authorization Options
ServiceClient serviceClient = new ServiceClient();
Options options = new Options();
options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
options.setTransportInProtocol(Constants.TRANSPORT_HTTP);
options.setTo(new EndpointReference(soapEndpoint));
options.setAction(soapAction);
serviceClient.setOptions(options);
//Generate an OperationClient from the ServiceClient to execute the request
OperationClient opClient = serviceClient.createClient(ServiceClient.ANON_OUT_IN_OP);
//Have to translate MsgCtx from Synapse to Axis2
org.apache.axis2.context.MessageContext axisMsgCtx = new org.apache.axis2.context.MessageContext();
axisMsgCtx.setEnvelope(context.getEnvelope());
opClient.addMessageContext(axisMsgCtx);
//Send the request to the server
opClient.execute(true);
//Retrieve Result and replace mediation (synapse) context
SOAPEnvelope result = opClient.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE).getEnvelope();
context.setEnvelope(result);
} catch (AxisFault e) {
context.setProperty("ResponseCode", e.getFaultCodeElement().getText());
return false; //This stops the mediation flow, so I think it executes the fault sequence?
}
return true;
}
Package as an OSGi Bundle and Deploy to the Server
At this stage you should be able to your custom mediator project within the project explorer in WSO2 Developer Studio and from the context menu select Export Project as Deployable Archive. Follow the prompts to save the JAR file somewhere on your system. After generating the JAR file, locate it and transfer it to the [ESB_HOME]/repository/components/dropins directory. You may need to restart the server for it to detect the new external library.
Using the Custom Mediator
In your sequence, you should now be able to add a class mediator and reference your custom class using the package name and class name together, for example: org.strainy.ntlmauthorisation.

Azure web service as a client to an external service, using a client-side certificate

I need to write a web service and host it in Azure. This service in turn consumes another service from an external site. Therefore, my azure-hosted service is a client to this externally-hosted service. When I make a request of the other service, I need to include a client-side certificate in my request.
Has anybody successfully done this? Is it possible to install a certificate in a web instance in azure? Would it survive the instance restarting? If so, pointers would be appreciated.
I have never worked with client-side certificates (even on a "real" client) so please forgive me if this is a newbee question.
The certificates that are uploaded in the cloud service (see the certificates tab under that cloud service in azure portal), which will host your webrole, will be available in the VM of that webrole. So you can access it from the certificate store and use it while making the external web service call.
A sample is given in this stackoverflow post.
Accessing a web service and a HTTP interface using certificate authentication
You can either add certificate via azure management portal, and azure will add it to machine certificate store once it deploy your application on the VM, or you can keep it with your application, for example as embedded resource and load it manually and use with your webservice call. Like this :
private X509Certificate2 GetAuthCertificate()
{
var assembly = Assembly.GetExecutingAssembly();
Stream stream = null;
var resources = assembly.GetManifestResourceNames();
foreach (var resource in resources)
{
if (resource.EndsWith(certificateFilename))
{
stream = assembly.GetManifestResourceStream(resource);
break;
}
}
if (stream == null)
throw new Exception("Certificate not found in embedded rersources");
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
var result = new X509Certificate2(ms.ToArray(), "password", X509KeyStorageFlags.Exportable);
return result;
}
}

WSO2 ESB how to securize a proxy by default when deploy

I have a lot of proxies in WSO2 ESB that I have to securize. I need them to be securized using Username Token when deploy, instead of browsing to the dashboard and enabling it one by one.
Any help?
I guess currently, you need to use management console and do it. From the UI, it is calling a backend web service. You can automate process by automating this backend web service. This web service is exposed by following component [1]. You can use soapui or some client program to automate this web service.
[1] http://svn.wso2.org/repos/wso2/carbon/platform/trunk/components/security/org.wso2.carbon.security.mgt/
I had similar requirement, here is how I solved it
Apply Role security to WSO2 ESB Proxy using Java API
Also you can find the test case here on how to use the methods
http://svn.wso2.org/repos/wso2/tags/carbon/3.2.3/products/bps/2.1.1/modules/integration/org.wso2.bps.management.test/src/test/java/org/wso2/bps/management/SecurityTest.java
Well here how the code snippet goes to secure any proxy service with default security scenarios of WSO2 ESB. In WSO2 ESB "scenario1" signifies Usernametoken based security. Now if you wish to secure your proxy with scenario1 follow the below code snippet:
public void applySecurityOnService(String serviceName, String policyId,
String[] userGroups, String[] trustedKeyStoreArray,
String privateStore)
throws SecurityAdminServiceSecurityConfigExceptionException,
RemoteException {
ApplySecurity applySecurity;
applySecurity = new ApplySecurity();
applySecurity.setServiceName(serviceName);
applySecurity.setPolicyId("scenario" + policyId); //scenario1 i.e. for Usernametoken security policyId should be 1
applySecurity.setTrustedStores(trustedKeyStoreArray);
applySecurity.setPrivateStore(privateStore);
applySecurity.setUserGroupNames(userGroups);
stub.applySecurity(applySecurity);
_logger.info("Security Applied Successfully");
}
Here is how you may call this method from your client class:
applySecurityOnService("MyProxy", "1", new String[]{"TestRole"}, new String[]{"wso2carbon.jks"}, "wso2carbon.jks");

WSO2 BPS - mailing activity

I need to have an activity that send a mail at a certain point of the BPEL process.
Is there a "mail activity" or do I have to code a sort of web services to invoke so that I call the service and let it send the mail?
Could it be a solution to use the ESB for this business?
How to connect the two (again with a web services or there is a quicker and easiest way to link them)?
Could it be a good solution in this case to add the ESB feature to BPS to add it the transport feature without having to add the ESB just for this?
Also I've seen that there are some example around that uses the transportSender in axis2.xml than using a proxy, but it seems that this method send the mail always to the same address I need to be able to send a mail to a subject (an possible cc and bcc) from parameters of the process (on a previous step I read data from DB and there is the address information) could the tensportSender be the path to follow or I have to develop the mailing service?
Any hint?
Thanks
Luca
As mentioned before, currently there is no mailing activity built-in for WSO2 BPEL, but you can get this functionality by invoking an external web service(DSS, AS) from inside the BPEL workflow.
I've created one workflow with such functionality couple days ago. Basically I created and Axis2 service that is just Java code for sending email, in which I can provide the parameters such as subject, content and receiver, so once you invoke the service you can send the email to any email address. I deployed the Axis2 service mentioned into a WSO2 DSS and invoke it from BPEL workflow that later on I deployed into WSO2 BPS.
The Java code I used for sendin the email is the following:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
public static void main(String emailAddress, String content){
String host = "smtp.gmail.com";
String from = "example#gmail.com";
String subject = "Subject example";
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", "");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
try{
Session session = Session.getDefaultInstance(props, null);
InternetAddress to_address = new InternetAddress(emailAddress);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, to_address);
message.setSubject(subject);
message.setContent(content, "text/html; charset=UTF-8");
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","example#gmail.com","Password");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
}
}
Currently, there is no mailing activity in BPS as a built-in activity.
But Yes, you can achieve your task by combining ESB and BPS. You can do it as follows.
First expose ESB email sending service as a proxy and then call that service using BPS. It is better to use a separate ESB for this task, since I have faced some difficulties when integrating ESB features into BPS.

Writing Webservice clients using HttpURLConnection

I have a question related to Axis2 Webservices .
I have My Webservice deployed in Tomcat Server .
Right now i am writing a Client for my Webservice using
public static void main(String[] args) {
try {
samples.quickstart.StockQuoteServiceStub stub = new samples.quickstart.StockQuoteServiceStub();
samples.quickstart.StockQuoteServiceStub.GetPrice request = new samples.quickstart.StockQuoteServiceStub.GetPrice();
request.setSymbol("ABCDE");
samples.quickstart.StockQuoteServiceStub.GetPriceResponse response = stub
.getPrice(request);
}
catch (org.apache.axis2.AxisFault e) {
e.printStackTrace();
} catch (java.rmi.RemoteException e) {
e.printStackTrace();
}
}
This works fine.
I have seen from net some clients are written using HttpURLConnection.
Please tell me what is the difference between writing clients by using the former way and the later way.
The way you have done give you a more abstract way. It has generated the code for you and you need only to provide the parameters to pass. Here Axis2 users the commons httpclient as to send message using http transport. As you can see Axis2 handles all the transport specific things for you.
On the other hand you can create the soap message to send from your own and send using an httpClient. But there you need to do a lot of work.