Having problems getting a List of Objects back from Restful service - web-services

Hey guys. I've developed some services in REST that are running on Glassfish 3.1.
I have a Java SE application and I am using Jersey as the client api.
public <T> T findAll_JSON(Class<T> responseType) throws UniformInterfaceException {
WebResource resource = webResource;
return resource.accept(MediaType.APPLICATION_JSON).get(responseType);
}
This is the client code that is generated by Netbeans.
My main problem is passing a list of objects as the response type
Here is the client code.
List<PkgLine> pkgLine = service.findAll_JSON(List.class);
System.out.println(pkgLine.get(5).getLineStatus());
service.close();
Obviously this is not working because the response needs to be a List of PkgLine. How do I pass that as a generic? My service is set to return the List of PkgLine. Thanks.

The problem is "erasure". You can declare a List<PkgLine> in your program, but at runtime the information that the objects in the List are PkgLines is erased. List<String>, List<PkgLine> and List<Object> are all the same type at runtime. (There's a reason why this is so; I won't explain it here but you can look up "erasure" if you are interested.)
The objects in the List are still PkgLines of course, but to the List they are just Objects, and you'll have to cast each one to a PkgLine. It's not pretty.
List<?> pkgLine = service.findAll_JSON(List.class);
System.out.println(((PkgLine)(pkgLine.get(5))).getLineStatus());
service.close();

What about parsing an array? It has the same json represantation.
You could write something like this:
resource.accept(MediaType.APPLICATION_JSON).get(PkgLine[].class);

Related

How to call Soap\WSDL Service through a login required webpage using matlab?

I am new to the wsdl\soapmessage query\reply world( if i can put it in this way), and I am facing some difficulties using the following wsdl( which I really really hope, one will be so kind to look at at least one of the services described there)
http://almdemo.polarion.com/polarion/ws/services/TrackerWebService?wsdl
which was provided to me to develop a matlab webinterface. Right now my matlab code looks like this:
targetNamespace = 'http://ws.polarion.com/TrackerWebService';
method = 'queryWorkItems';
values= {'Query','Sort'}
names = {'query', 'sort'}
types ={'xsd:string','xsd:string'}
message = createSoapMessage( targetNamespace, method, values, names, types)
response = callSoapService('http://almdemo.polarion.com/polarion/ws/services',...
% Service's endpoint
'http://almdemo.polarion.com/polarion/#/workitems',...
% Server method to run
message)
% SOAP message created using createSoapMessage
author = parseSoapResponse(response)
Herewith to save you time I will just enonce my two problems:
Is the code correct?
Could someone tell me if such a wsdl link is just a definition of webservices or it is also a service's endpoint?
Normally to execute manually\per clicks this services on the weppage
http://almdemo.polarion.com/polarion, you have to login!
So how do I send a message in matlab which first log me in? Or must such a service be introduced into that wsdl for me to do it?? Could you be kind enough to write how it must be defined, because I don't really
write wsdl files, but I shall learn!**
I will be really thankful for your help and I wish you a happy week(-end) guys(& girls)!!!
Regards
Chrysmac
ps: I tried to use Soapui and gave that webpage as endpoint, but the toool crashes each time I enter my credentials! Maybe because of the dataload!??

Spring Web - Restful Webservice - pass/receive ArrayList as an argument/parameter in client/server side

I have created a sample application to get full idea of Spring MVC with REST Webservice. I have created an application which host webservice and a client which calls to this webservice and fetch the relevant data. I am able to pass the arguments from client side like String, and able to receive the data as List or single object, and till here it goes smooth..
Now I want to pass the List as an argument from client side, and also want to implement on webservice side to get the List which is passed from client application. Can anyone helpout with this scenario?
Please find code snippet of my working version.
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appContext.xml", Client.class);
RestTemplate restTemplate = applicationContext.getBean("restTemplate", RestTemplate.class);
String url;
// retrieve a list of customers
url = "http://localhost:8080/restful-ws/app/testlist.xml";
List<CustomerBean> custList = (List) restTemplate.getForObject(url, List.class);
for (CustomerBean cust : custList) {
System.out.println(">> cust :"+ cust.toString());}
Web Service side implementation.
#RequestMapping(method=RequestMethod.GET, value="/testlist")
public ModelAndView showCustomers() {
ModelAndView mv = new ModelAndView("customerListKey");
List<Customer> custs = new ArrayList<Customer>();
for (Customer customer:customers.values()) {
custs.add(customer);
}
mv.addObject("allCustomers", custs);
return mv;
}
also i have related files, but if will put all code snippets, it will become too much. Mainly my query is how can I pass List from client side and how can i get it from receiver/server side?, in both side i am using spring only
Thanks in advance for your time and help.
-Ronak.
Use an array of CustomerBean
CustomerBean[] custList = restTemplate.getForObject(url, CustomerBean[].class);
The conversion from array to list is left as an exercise for the interested reader...

Umbraco Document.getProperty(...).Value throws Null Reference Exception

I am writing a small app that links into Umbraco (a small stand-alone console application that will eventually run as a scheduled task on the server) and I'm using the Umbraco APIs (4.5.2) to make changes to the database/document.
Here is a fragment of what I'm doing:
IEnumerable<Document> documents = Document.GetChildrenForTree(parentDocumentId);
foreach (Document doc in documents.Where(d => d.Published))
{
doc.getProperty("myData").Value = "some data"; // Exception here
// ...other stuff here...
}
However I always get a NullReferenceException because there are no properties. This confuses me because I can see that there are 5 properties in the umbraco interface.
A colleague suggested that I use a Node instead of a document, however I can't even create one as I get a NullReferenceException from the Node class constructor.
Node myNode = new Node(-1); // NullReferenceException here
Does anyone have any ideas?
The document class gets/sets information from the umbraco database. Since your running code in an out of band console application it can't find the umbraco context. Therefore throwing a null reference exception.
You need to run the code inside of the umbraco process. There is a asmx webservice that exists for third party integration. /umbraco/webservices/api/documentservice.asmx
Another way of achieving this could be to use linq2umbraco.
for further details see http://our.umbraco.org/forum/core/41-feedback/7699-UmbracoLinq-in-console-app--Having-some-troubles
I checked out the 4.5.2 source recently, to find that populating Document and Node objects only requires a connection using umbracoDbDsn. So if you have an AppSetting called umbracoDbDsn which points to a valid Umbraco database instance, you'll be good.
HTH,
Benjamin

Complex Object in JAX-WS is created empty

I'm testing JAX-WS to access the Oracle IRM web serviecs. I can get it to work just fine with AXIS so this isn't an Oracle problem.
What's happening is that I'm getting the following error when making the call:
Expected xsd:anyType - unknown type provided
If I look at the SOAP packet is sent I see that the owner tag is blank under JAX-WS:
<ns1:browseAccounts>
<owner/>
<accountType>All</accountType>
</ns1:browseAccounts>
The same piece under AXIS is this:
<owner xsi:type="ns1:LicenseServer"
xmlns=""
xmlns:ns1="http://www.sealedmedia.com/ls/server/schema">
<serverKey>#############</serverKey>
</owner>
Obviously the owner tag is not getting properly created, this is what I'm using to create that:
AccountServicesPort AA = ORI.getAccountServices();
LicenseServer LicSer = new LicenseServer();
LicSer.setServerKey("#######################");
List<Account> Acts = AA.browseAccounts(LicSer,AccountAccountType.ALL);
Is there some other process that I need to go through to create the object properly?
EDIT
I thought maybe running the LicenseServer creation through ObjectFactory would help. Unfortunately, it doesn't.
Despite the Oracle IRM documentation stating that BrowseAccounts accepts either a LicenseServer object or a Context object for the owner parameter it actually accepts an LicenseServer_ref.
EDIT
Further, I was running JAX-WS under JDK 1.6.0 which is a lower version than JDK 1.6.0_14. The new version supports XMLSeeAlso annotation which allowed JAX-WS to use the proper class for serialization.

SOAP Webservice error - design practice

I need to design a SOAP api (my first one!). What are the best practices regarding errors returned to the caller.
Assuming an api as follow
[WebMethod]
public List<someClass> GetList(String param1)
{
}
Should I
Throw an exception. Let the SOAP infrastructure generate a SOAP fault -- and the caller would have to try/catch. This is not very explanatory to the caller
Have the return parameter be a XMLDOcument of some sort, with the first element being a return value and then the List.
Looking at the return SOAP packet I see that the response generated looks like the following
<GetListResponse>
<GetListResult>
...
...
</GetListResult>
</GetListResponse>
Can we somehow change the return packet so that the "GetListResult" element is changed to "GetListError" in case of error
Any other way?
Thanks!
Probably the most appropriate SOA pattern to follow would be a Fault Contract, which is essentially a Data Contract that is wrapped in the SOAPException.
I am posting examples in .NET, since it looks like that is what you are using (and that is what I know :) )
In WCF, you can define a DataContract, then decorate your OperationContract interface with a a "FaultContract" attribute that specifies it as the return value:
public partial interface MyServiceContract
{
[System.ServiceModel.FaultContract(typeof(MyService.FaultContracts.ErrorMessageFaultContract))]
[System.ServiceModel.OperationContract(...)]
ResponseMessage SOAMethod(RequestMessage request) {...}
}
For ASMX web services, (as it appears you are using from your code snippet), you can't use this attribute or setup. So to implement the pattern, you would need to:
Define a serializable class to hold your exception information (i.e. ErrorData)
When an exception is thrown in your service, catch it and in your error handling code, add the info to the ErrorData class
Append the serialized ErrorData class to a SoapException class:
SoapException mySoapException = new SoapException(message, SoapException.ServerFaultCode, "", serialzedErrorDataClass);
Throw the SoapException in your code
On your client side, you will need to deserialize the message to interpret it.
Kind of seems like a lot of work, but this way you have total control of what data gets returned. Incidentally, this is the pattern that is used by the ServiceFactory from Microsoft patterns & practices for ASMX web services.
There is some good information on Coding Horror.
You can cause the correct fault to be returned from old ASMX services, but it's not easy. First of all, you'll have to hand-code the WSDL, because the ASMX infrastructure will never create Fault elements in a WSDL. Then, you have to serialize the desired fault data into an XmlElement that you will then provide as the Detail property of the SoapException that you will throw.
It's much easier with WCF. You can declare a number of FaultContracts for each operation, and WCF will generate the correct WSDL to refer to them. You then simply throw a FaultException, where type T is the type of the FaultContract. Pass the T instance to the constructor, and you're all set.
I can't give you specifies for .net (which seems to be what you're asking), but SOAP provides a mechanism for expressing strongly-typed exceptions. The SOAP fault element can have an optional FaultDetail sub-element, and this can contain arbitrary XML documents, such as your GetListError. These document types should be defined in the WSDL as a wsdl:fault inside the wsdl:operation
The trick is persuading the web service stack to turn an exception (which is the "correct" way of writing your business logic) into a properly marshalled fault detail. And I can't help you with that bit.