Here i am trying to read the list of sharepoint. For this i have done the following:
I have downloaded the WSDL file which i got from The URL like: sharepointsite.com/_vti_bin/Lists.asmx?WSDL.
and i have executed the following command to generate the classes in the directory
“C:\Program Files\Java\jdk1.6.0_12\bin\wsimport.exe” -p com.microsoft.schemas.sharepoint.soap -keep -extension Lists.wsdl.
Imported those classes in my eclipse IDE java application.
and i have written the following code
/* Creates a port connected to the SharePoint Web Service given.
* Authentication is done here. It also prints the authentication details
* in the console.
* #param userName SharePoint username
* #param password SharePoint password
* #return port ListsSoap port, connected with SharePoint
* #throws Exception in case of invalid parameters or connection error.
*/
public static ListsSoap sharePointListsAuth(String userName, String password) throws Exception {
ListsSoap port = null;
if (userName != null && password != null) {
try {
Lists service = new Lists();
port = service.getListsSoap();
System.out.println("Web Service Auth Username: " + userName);
((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, userName);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
} catch (Exception e) {
throw new Exception("Error: " + e.toString());
}
} else {
throw new Exception("Couldn't authenticate: Invalid connection details given.");
}
return port;
}
/**
* Creates a string from an XML file with start and end indicators
* #param docToString document to convert
* #return string of the xml document
*/
public static String xmlToString(Document docToString) {
String returnString = "\n-------------- XML START --------------\n";
try {
//create string from xml tree
//Output the XML
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans;
trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult streamResult = new StreamResult(sw);
DOMSource source = new DOMSource(docToString);
trans.transform(source, streamResult);
String xmlString = sw.toString();
//print the XML
returnString = returnString + xmlString;
} catch (TransformerException ex) {
Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
}
returnString = returnString + "-------------- XML END --------------";
return returnString;
}
/**
02
* Connects to a SharePoint Lists Web Service through the given open port,
03
* and reads all the elements of the given list. Only the ID and the given
04
* attributes (column names) are displayed, as well as a dump of the SOAP
05
* response from the Web Service (for debugging purposes).
06
* #param port an already authentificated SharePoint Online SOAP port
07
* #param listName original name of the Sharepoint list that is going to be read
08
* #param listColumnNames arraylist containing the various names of the Columns
09
* of the SharePoint list that are going to be read. If the column name isn't
10
* found, then an exception will be thrown
11
* #param rowLimit limits the number of rows (list items) that are going to
12
* be returned
13
* #throws Exception
14
*/
public static void displaySharePointList(ListsSoap port, String listName, ArrayList<String> listColumnNames, String rowLimit) throws Exception {
if (port != null && listName != null && listColumnNames != null && rowLimit != null) {
try {
//Here are additional parameters that may be set
String viewName = "";
GetListItems.ViewFields viewFields = null;
GetListItems.Query query = null;
GetListItems.QueryOptions queryOptions = null;
String webID = "";
//Calling the List Web Service
GetListItemsResponse.GetListItemsResult result = port.getListItems(listName, viewName, query, viewFields, rowLimit, queryOptions, webID);
Object listResult = result.getContent().get(0);
if ((listResult != null) && (listResult instanceof ElementNSImpl)) {
ElementNSImpl node = (ElementNSImpl) listResult;
//Dumps the retrieved info in the console
Document document = node.getOwnerDocument();
System.out.println("SharePoint Online Lists Web Service Response:" + Manager.xmlToString(document));
//selects a list of nodes which have z:row elements
NodeList list = node.getElementsByTagName("z:row");
System.out.println("=> " + list.getLength() + " results from SharePoint Online");
//Displaying every result received from SharePoint, with its ID
for (int i = 0; i < list.getLength(); i++) {
//Gets the attributes of the current row/element
NamedNodeMap attributes = list.item(i).getAttributes();
System.out.println("******** Item ID: " + attributes.getNamedItem("ows_ID").getNodeValue()+" ********");
//Displays all the attributes of the list item that correspond to the column names given
for (String columnName : listColumnNames) {
String internalColumnName = "ows_" + columnName;
if (attributes.getNamedItem(internalColumnName) != null) {
System.out.println(columnName + ": " + attributes.getNamedItem(internalColumnName).getNodeValue());
} else {
throw new Exception("Couldn't find the '" + columnName + "' column in the '" + listName + "' list in SharePoint.\n");
}
}
}
} else {
throw new Exception(listName + " list response from SharePoint is either null or corrupt\n");
}
} catch (Exception ex) {
throw new Exception("Exception. See stacktrace." + ex.toString() + "\n");
}
}
}
public static void main(String[] args) {
try {
//Authentication parameters
String userName = "domain\\username";
String password = "pass";
//Opening the SOAP port of the Lists Web Service
ListsSoap port = Manager.sharePointListsAuth(userName, password);
/*
* Lists Web service parameters
* The list names below must be the *original* names of the list.
* if a list or column was renamed from SharePoint afterwards,
* these parameters don't change.
*/
String listName = "listname";
String rowLimit = "2";
ArrayList<String> listColumnNames = new ArrayList<String>();
listColumnNames.add("Name");
listColumnNames.add("ID");
//Displays the lists items in the console
Manager.displaySharePointList(port, listName, listColumnNames, rowLimit);
} catch (Exception ex) {
System.err.println(ex);
}
}
I am getting following exception :
Web Service Auth Username: "domain\username"
java.lang.Exception: Exception. See stacktrace.javax.xml.ws.soap.SOAPFaultException: Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown.
It would be helpfull if i get the specific exception from the server.With this expection i am unable to track my pgm.
I dont know where did i go wrong? am i missing anything ? any configuration is required ?
Thanks in advance for your help
I had the same problem, try with an Authenticator :
new BasicAuthentication(userName,password).authenticate();
My BasicAuthentication class :
import java.net.Authenticator;
import java.net.PasswordAuthentication;
public class BasicAuthentication extends Authenticator
{
private String username;
private String password;
public BasicAuthentication(String username, String password)
{
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return (new PasswordAuthentication(username,password.toCharArray()));
}
public void authenticate()
{
Authenticator.setDefault(this);
}
}
Related
I have been reading https://powerbi.microsoft.com/en-us/blog/announcing-data-refresh-apis-in-the-power-bi-service/
In this post, it mentions "To get the group ID and dataset ID, you can make a separate API call".
Does anybody know how to do this from the dashboard URL, or do I have to embed the group id and dataset id in my app alongside the dashboard URL???
To get the group ID and dataset ID, you can make a separate API call.
This sentence isn't related to a dashboard, because in one dashboard you can put visuals showing data from many different datasets. These different API calls are Get Groups (to get list of groups, find the one you want and read it's id) and Get Datasets In Group (to find the dataset you are looking for and read it's id).
But you should already know the groupId anyway, because the dashboard is in the same group.
Eventually, you can get datasetId from particular tile using Get Tiles In Group, but I do not know a way to list tiles in dashboard using the Rest API.
This is a C# project code to get the dataset id from Power BI.
Use the below method to call the 'Get' API and fetch you the dataset Id.
public void GetDatasetDetails()
{
HttpResponseMessage response = null;
HttpContent responseContent = null;
string strContent = "";
PowerBIDataset ds = null;
string serviceURL = "https://api.powerbi.com/v1.0/myorg/admin/datasets";
Console.WriteLine("");
Console.WriteLine("- Retrieving data from: " + serviceURL);
response = client.GetAsync(serviceURL).Result;
Console.WriteLine(" - Response code received: " + response.StatusCode);
try
{
responseContent = response.Content;
strContent = responseContent.ReadAsStringAsync().Result;
if (strContent.Length > 0)
{
Console.WriteLine(" - De-serializing DataSet details...");
// Parse the JSON string into objects and store in DataTable
JavaScriptSerializer js = new JavaScriptSerializer();
js.MaxJsonLength = 2147483647; // Set the maximum json document size to the max
ds = js.Deserialize<PowerBIDataset>(strContent);
if (ds != null)
{
if (ds.value != null)
{
foreach (PowerBIDatasetValue item in ds.value)
{
string datasetID = "";
string datasetName = "";
string datasetWeburl = "";
if (item.id != null)
{
datasetID = item.id;
}
if (item.name != null)
{
datasetName = item.name;
}
if (item.qnaEmbedURL != null)
{
datasetWeburl = item.qnaEmbedURL;
}
// Output the dataset Data
Console.WriteLine("");
Console.WriteLine("----------------------------------------------------------------------------------");
Console.WriteLine("");
Console.WriteLine("Dataset ID: " + datasetID);
Console.WriteLine("Dataset Name: " + datasetName);
Console.WriteLine("Dataset Web Url: " + datasetWeburl);
} // foreach
} // ds.value
} // ds
}
else
{
Console.WriteLine(" - No content received.");
}
}
catch (Exception ex)
{
Console.WriteLine(" - API Access Error: " + ex.ToString());
}
}
points to remember:
Make sure these classes exist in your project
PowerBIDataset is a class with List
PowerBIDatasetValue is a class with id, name and webUrl (all string data type) data members
provide below constants in your project class
const string ApplicationID = "747d78cd-xxxx-xxxx-xxxx-xxxx";
// Native Azure AD App ClientID -- Put your Client ID here
const string UserName = "user2#xxxxxxxxxxxx.onmicrosoft.com";
// Put your Active Directory / Power BI Username here (note this is not a secure place to store this!)
const string Password = "xyxxyx";
// Put your Active Directory / Power BI Password here (note this is not secure pace to store this! this is a sample only)
call this GetDatasetDetails() method in the Main method of your project class
and finally
use the below 'Get' API to get the Group Id
https://api.powerbi.com/v1.0/myorg/groups
I have seen this example documented by microsoft, but cannot get it to work in visual studio 2012, under a console project.
https://msdn.microsoft.com/en-us/library/ms676877(v=vs.85).aspx
Is there something I am missing, ie. is a console application correct.
The Errors I get are:
Error 1 error LNK2019: unresolved external symbol __imp__ldap_openW referenced in function "int __cdecl GetChangeNotifications(wchar_t *)" (?GetChangeNotifications##YAHPA_W#Z) C:\projects\AD_Notifications\AD_Change_Notifications\AD_Change_Notifications\AD_Change_Notifications.obj AD_Change_Notifications
From what I have been reading its a linker error, which is kinda obvious, but it is all in 1 file, so I don't understand what I am suppose to be linking?
The best answer I found in java is quoted below from https://community.oracle.com/thread/1158217
/**
* ldapnotify.java
* December 2004
* Sample JNDI application that uses AD LDAP Notification Control.
*
**/
import java.util.Hashtable;
import java.util.Enumeration;
import javax.naming.*;
import javax.naming.ldap.*;
import com.sun.jndi.ldap.ctl.*;
import javax.naming.directory.*;
class NotifyControl implements Control {
public byte[] getEncodedValue() {
return new byte[] {};
}
public String getID() {
return "1.2.840.113556.1.4.528";
}
public boolean isCritical() {
return true;
}
}
class ldapnotify {
public static void main(String[] args) {
Hashtable env = new Hashtable();
String adminName = "CN=Administrator,CN=Users,DC=antipodes,DC=com";
String adminPassword = "XXXXXXXX";
String ldapURL = "ldap://mydc.antipodes.com:389";
String searchBase = "DC=antipodes,DC=com";
//For persistent search can only use objectClass=*
String searchFilter = "(objectClass=*)";
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
//set security credentials, note using simple cleartext authentication
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,adminName);
env.put(Context.SECURITY_CREDENTIALS,adminPassword);
//connect to my domain controller
env.put(Context.PROVIDER_URL,ldapURL);
try {
//bind to the domain controller
LdapContext ctx = new InitialLdapContext(env,null);
// Create the search controls
SearchControls searchCtls = new SearchControls();
//Specify the attributes to return
String returnedAtts[] = null;
searchCtls.setReturningAttributes(returnedAtts);
//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//Specifiy the search time limit, in this case unlimited
searchCtls.setTimeLimit(0);
//Request the LDAP Persistent Search control
Control[] rqstCtls = new Control[]{new NotifyControl()};
ctx.setRequestControls(rqstCtls);
//Now perform the search
NamingEnumeration answer = ctx.search(searchBase,searchFilter,searchCtls);
SearchResult sr;
Attributes attrs;
//Continue waiting for changes....forever
while(true) {
System.out.println("Waiting for changes..., press Ctrl C to exit");
sr = (SearchResult)answer.next();
System.out.println(">>>" + sr.getName());
//Print out the modified attributes
//instanceType and objectGUID are always returned
attrs = sr.getAttributes();
if (attrs != null) {
try {
for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
Attribute attr = (Attribute)ae.next();
System.out.println("Attribute: " + attr.getID());
for (NamingEnumeration e = attr.getAll();e.hasMore();System.out.println(" " + e.next().toString()));
}
}
catch (NullPointerException e) {
System.err.println("Problem listing attributes: " + e);
}
}
}
}
catch (NamingException e) {
System.err.println("LDAP Notifications failure. " + e);
}
}
}
I am using soap service to authenticate request by sabre as in the document https://developer.sabre.com/docs/read/soap_basics/Authentication.
I generate the proxy classes using wsdl. i put authentication credential in the code. This is my Code for test purpose:
using ConsoleApplication1.SessionReference1;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
// Set user information, including security credentials and the IPCC.
string username = "my-username";
string password = "my-password";
string ipcc = "not-understand";
string domain = "EXT";
string temp = Environment.GetEnvironmentVariable("tmp"); // Get temp directory
string PropsFileName = temp + "/session.properties"; // Define dir and file name
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header and provide the conversation ID.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = "TestSession"; // Set the ConversationId
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
//Add the value for eb:CPAId, which is the IPCC.
//Add the value for the action code of this Web service, SessionCreateRQ.
msgHeader.CPAId = ipcc;
msgHeader.Action = "SessionCreateRQ";
Service service = new Service();
service.Value = "SessionCreate";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security security = new Security();
SecurityUsernameToken securityUserToken = new SecurityUsernameToken();
securityUserToken.Username = username;
securityUserToken.Password = password;
securityUserToken.Organization = ipcc;
securityUserToken.Domain = domain;
security.UsernameToken = securityUserToken;
SessionCreateRQ req = new SessionCreateRQ();
SessionCreateRQPOS pos = new SessionCreateRQPOS();
SessionCreateRQPOSSource source = new SessionCreateRQPOSSource();
source.PseudoCityCode = ipcc;
pos.Source = source;
req.POS = pos;
SessionCreatePortTypeClient s = new SessionCreatePortTypeClient();
SessionCreateRS resp = s.SessionCreateRQ(ref msgHeader, ref security, req);
//SessionCreateRQService serviceObj = new SessionCreateRQService();
//serviceObj.MessageHeaderValue = msgHeader;
//serviceObj.SecurityValue = security;
//SessionCreateRS rs = new SessionCreateRS();
//SessionCreateRS = serviceObj.SessionCreateRQ(req); // Send the request
if (resp.Errors != null && resp.Errors.Error != null)
{
Console.WriteLine("Error : " + resp.Errors.Error.ErrorInfo.Message);
}
else
{
// msgHeader = serviceObj.MessageHeaderValue;
// security = serviceObj.SecurityValue;
Console.WriteLine("**********************************************");
Console.WriteLine("Response of SessionCreateRQ service");
Console.WriteLine("BinarySecurityToken returned : " + security.BinarySecurityToken);
Console.WriteLine("**********************************************");
string ConvIdLine = "convid=" + msgHeader.ConversationId; // ConversationId to a string
string TokenLine = "securitytoken=" + security.BinarySecurityToken; // BinarySecurityToken to a string
string ipccLine = "ipcc=" + ipcc; // IPCC to a string
// File.Delete(PropsFileName); // Clean up
// TextWriter tw = new StreamWriter(PropsFileName); // Create & open the file
// tw.WriteLine(DateTime.Now); // Write the date for reference
// tw.WriteLine(TokenLine); // Write the BinarySecurityToken
// tw.WriteLine(ConvIdLine); // Write the ConversationId
// tw.WriteLine(ipccLine); // Write the IPCC
// tw.Close();
//Console.Read();
}
}
catch (Exception e)
{
Console.WriteLine("Exception Message : " + e.Message);
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
Console.Read();
}
}
}
}
Please Help me
I didn't check the sequence of the code in detail, but checking the values you set for organization and domain:
string ipcc = "not-understand";
string domain = "EXT";
Unless you did it intentionally to mask the values, you should have received your ipcc value from Sabre after getting a SOAP webservices account.
The value for SOAP APIs domain is normally "DEFAULT".
Registering on dev studio only gives you REST test credentials (not SOAP), so you can use this form to request SOAP test credentials:
https://developer.sabre.com/contact
Finally, I don't quite see the environment/target url you're using to test the SessionCreate service...CERT one is: https://sws3-crt.cert.sabre.com/
I am new to AWS, Can any one please help me how to create users on virtual machine using java code. I have created windows ec2 instance and able to connect using sshClient, but unable to create users. I dont have any idea about how it can be done.
[I am new to stack overflow please forgive me if wrong formatting]
Answering my own question... It may help someone..
You can use execute command to create user on remote windows...
Example:
public boolean executeCommands(String commands, SSHRequestParam param)
throws Exception,IOException {
boolean response = false;
try {
Connection conn = getConnection(param);
Session sess = conn.openSession();
sess.execCommand(commands);
sess.waitForCondition(ChannelCondition.EXIT_SIGNAL, 0);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(
new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
response=true;
System.out.println(line);
}
InputStream stderr = new StreamGobbler(sess.getStderr());
BufferedReader br1 = new BufferedReader(new InputStreamReader(
stderr));
while (true) {
String line = br1.readLine();
if (line == null)
break;
response=false;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
System.out.println("closing session");
sess.close();
closeConnection(conn);
} catch (IOException e) {
System.out.println("Exception..while executing command.: " + commands);
e.printStackTrace();
}
System.out.println("Command executed : "+response);
return response;
}
public void createUser(String userName, String password,SSHRequestParam param)
throws Exception,IOException {
String command = "net user " +userName+" "+password+" /add" ;
if(executeCommands(command,param))
System.out.println("User created successfully");
else
System.out.println("User didn't create....");
}
In above example param variable stores the parameters to connect to the server i.e. hostname, username, password....
I am calling a BPM web service that sends HTML email. I generated a web service proxy in JDeveloper 11.1.1.7. The type of the body of the email is xsd:string which should map to java String. I understand that certain characters, for example < > &, are reserved and converted during the xml document creation during the proxy operation.
Using SOAPUI to call the service, I can pass the body as <h1>My Heading</h1> and service responds correctly, sending the email with HTML as expected. When doing the same from a POJO that calls the proxy, <h1> is converted to <h1>My heading</h1>.
I have tried passing the body as a CDATA section but this makes no difference. I have tried converting the body to bytes then back to a UTF-8 string before the call but still no difference. I have access to the BPM service code. Is there a way I can send html to the service from a proxy, that retains the special characters?
I figured this out finally. While the JDeveloper web service proxy generator is useful most of the time, in this case it was not since I needed to send xml special characters to the service. Perhaps there is a way to manipulate the proxy code to do what you want but I couldn't figure it out.
Of particular help was this AMIS blog entry. And if you ever need to handle special characters during JAXB marshalling, this entry will help you too. A great summary of the steps to use the java URLConnection class is here and that answer points to a library that would probably make life even easier.
So here is the raw wrapper code below. The particular BPM email service we wrote also writes to a log and that explains the complex types in the raw xml input. Naturally I will populate the email values from a passed in POJO object in the main sendMail wrapper method.
package com.yourdomain.sendmail.methods;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import oracle.adf.model.connection.url.URLConnectionProxy;
import oracle.adf.share.ADFContext;
public class SendMailWrapper {
public SendMailWrapper() {
super();
}
public static void main(String[] args) throws MalformedURLException, IOException {
SendMailWrapper w = new SendMailWrapper();
w.sendMail();
}
public void sendMail() throws MalformedURLException, IOException {
String xmlInput =
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
"xmlns:sen=\"http://xmlns.oracle.com/bpmn/bpmnProcess/SendEmailProcess\" " +
"xmlns:ema=\"http://www.wft.com/BPM/SendEmail/Email\">\n" +
"<soapenv:Header/>" +
"<soapenv:Body>\n" +
"<sen:start>\n" +
"<ema:emailInput>\n" +
"<ema:emailContent>\n" +
"<ema:toAddr>your.name#yourdomain.com</ema:toAddr>\n" +
"<ema:fromAddr></ema:fromAddr>\n" +
"<ema:ccAddr></ema:ccAddr>\n" +
"<ema:bccAddr></ema:bccAddr>\n" +
"<ema:subject>SendMail HTML</ema:subject>\n" +
"<ema:body><h1>My Heading</h1><p>Text</p></ema:body>\n" +
"<ema:contentType>text/html</ema:contentType>\n" +
"</ema:emailContent>\n" +
"<ema:emailHistory>\n" +
"<ema:projectName>Soap Test</ema:projectName>\n" +
"<ema:reqID></ema:reqID>\n" +
"<ema:compositeID></ema:compositeID>\n" +
"<ema:processID></ema:processID>\n" +
"<ema:processName></ema:processName>\n" +
"<ema:activityName></ema:activityName>\n" +
"<ema:insertDate></ema:insertDate>\n" +
"<ema:insertByID></ema:insertByID>\n" +
"<ema:insertByName></ema:insertByName>\n" +
"<ema:commentType></ema:commentType>\n" +
"<ema:commentInfo></ema:commentInfo>\n" +
"</ema:emailHistory>\n" +
"</ema:emailInput>\n" +
"</sen:start>\n" +
"</soapenv:Body>\n" +
"</soapenv:Envelope>\n";
System.out.println(xmlInput);
String wsURL = getWsdlUrl();
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "start"; //this is the method in the service
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
//some other props available but don't need to be set...
//httpConn.setRequestProperty("Accept-Encoding", "gzip,deflate");
//httpConn.setRequestProperty("Host", "your.host.com:80");
//httpConn.setRequestProperty("Connection", "Keep-Alive");
//httpConn.setRequestProperty("User-Agent", "Apache-HttpClient/4.1.1 (java 1.5)");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
out.write(b);
out.close();
//check response code...
int status = httpConn.getResponseCode();
String respMessage = httpConn.getResponseMessage();
System.out.println("RESPONSE CODE: " + status + " RESPONSE MESSAGE: " + respMessage);
//check response headers...
for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
//check error stream - this helps alot when debugging...
InputStream errorStream = ((HttpURLConnection)connection).getErrorStream();
if (errorStream != null) {
System.out.println("Error Stream: " + convertStreamToString(errorStream));
}
//if there was an expected response, you need to parse it...
/* String responseString = "";
String outputString = "";
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
isr.close();
System.out.println("OUT: " + outputString); */
}
static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static String getWsdlUrl() {
String result = null;
try {
URLConnectionProxy wsConnection = (URLConnectionProxy)ADFContext.getCurrent().getConnectionsContext().lookup("SendMailProxyConnection");
result = wsConnection.getURL().toExternalForm();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
Happy coding.