public class Person {
private String firstname;
private String lastname;
private PhoneNumber phone;
private PhoneNumber fax;
// ... constructors and methods
private void calculate()
{
}
}
I have serialized the Java object located on the server side and sent it to the client
XStream xstream = new XStream(new DomDriver());
Person joe = new Person("Joe", "Walnes");
joe.setPhone(new PhoneNumber(123, "1234-456"));
joe.setFax(new PhoneNumber(123, "9999-999"));
String xml = xstream.toXML(joe);
How can I deserialize that XML string into the Java object using JavaScript
and execute the methods of person class in the client side using the JavaScript?
Please help me with syntax or any guidelines.
You can call Java methods on the client side using JavaScript by using SOAP. This article explains how to create a WSDL web service that can be accessed by any SOAP client that supports WSDL.
You can then call the Java WSDL service using AJAX in JavaScript (if you can find a JS library that implements SOAP and WSDL).
Alternatively, you can write a simplified front-end to the Java WSDL service in PHP using PHP's built-in SoapClient library. Make it take some simple GET arguments and return JSON or XML. You could then trivially access the PHP web service using AJAX via jQuery (or an equivalent AJAX-supporting library).
If you're going for an applet and want to make Javascript calls from Java, checkout the LiveConnect with the JSObject wrapper class. This way you can excute javascript functions inside the applet (and pass information in between);
Executor exe = Executors.newSingleThreadExecutor();
final JSObject page = JSObject.getWindow(applet);
if (page == null) {
/* Break here, no connection could be made */
}
final String javascriptFunction = "yourJavaScriptFunction()";
executor.execute(new Runnable() {
public void run() {
page.eval(javascriptFunction);
}
});
Look into the IRIS applictation made for Flickr, it's open source and uses this technique. The Belgian JUG Parleys have a speech from a convention covering some of this, You can find it here.
XML is presented as a DOM tree to JavaScript
You can't run Java methods with Javascript. The only thing you could do is to read the properties of the Java object - this is the only information that is serialized in the XML file. It is very easy to read XML with javascript.
To be able to serialize a Java object, send it to a client and execute Java code there a totally different architecture would be needed. At first you need Java running on the client too. Then you would need to employ a method like RMI.
Related
I want to create a web service using C#. In web service I have a web method that accept list of a specific class:
[DataContract]
public class CompositeType
{
string stringValue = "Hello ";
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
[DataMember]
public List<Product> Products { get; set; }
}
[DataContract]
public class Product
{
[DataMember]
public int PID { get; set; }
[DataMember]
public string PName { get; set; }
}
and my web method:
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
I want to publish this service using BasicHttpBinding that Java users can call it too. Now since the Java programmer is not around me, I wanted to ask those who have the experience to do this :
1) Can Java programmers call my web method that accept List<Product>?
2)Should I change List to Array?
Thanks for you contribution
Presumably your HTTP API serializes this as JSON (or maybe XML). In either case, libraries such as Jackson can handle it just fine, and most REST clients will even handle that part automatically. Standards compliance is the rule, and so as long as your List<Product> is converted to/from a regular JSON array, everything should work smoothly.
JSON doesn't have separate list types, just the plain array, so either array or list-based serialization should be equivalent.
As a note, most APIs use either camelCase or snake_case for properties, so your property names (in JSON) would be expected to be stringValue, products, pid, and pName.
As with .Net client calling WCF using the Svcutil tool, most Java users use the asis2 library which is a webservice engine to invoke web service.
WebService is a specification that any service that implements it can be called WebService. they use SOAP message based on XML to communicate. they use WSDL to describe the service details, which is used for generating the client proxy class. The reason why WCF can be called across service boundaries by various platforms is that it is also a web service. Although there may be different data types on various platforms, as long as we specify how to represent it in XML and how to serialize it, the service can be called correctly by others platforms, By default, List is specified to be serialized using a one-dimensional array.
I have an android application that talks to a .NET server using WEB API web services. Currently, I have transfer objects on the server and on the client.
Java class
public class UserAction {
private String username;
private String action;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
My C# class on the server side
public class UserActionTO
{
public string Username { get; set; }
public string Action { get; set; }
}
I wish to share these models, between the two applications.
I found this question discussing sharing types but my situation is a bit different. Should I share types between a Web API service and its client ? What are the other options?
I am considering creating a C++ dll, which both my android application and C# application could use. Is this my best option?
EDIT
I am using JSON to transfer the data
The best option is to use a standard platform-neutral format (usually either JSON or XML). This gives you immense freedom to vary both client and server any way you wish and makes development and testing easier, since you can inspect or generate content easily.
If you're asking about an easy mechanism for representing the content in-memory on multiple endpoints, it's perfectly reasonable to create a "client SDK" (many online services publish them for multiple programming languages each) that has these DTOs and perhaps some utilities and use the appropriate one server-side. It is not generally a good idea to get overly clever and do something like drop into native code; keep the code for the DTOs in the appropriate language (such as Java for Android, or perhaps C# if using Xamarin).
Since you're already using JSON for the data I would suggest you write once in .NET and create your sample result JSON objects. Then use http://www.jsonschema2pojo.org/ to create your POJOS it'll even include the generated annotation so you know not to modify the class.
Another advantage is you can format it with jackson or GSON annotation styles to serialize/de-serialize the objects with little effort.
If you want to go crazy you could model everything in JSON, then have a script that uses http://json2csharp.com/ to create your .NET and http://www.jsonschema2pojo.org/ for Java POJOs for you. But I'm not sure it would be worth the trouble :)
I started to use apache thrift (programming for java) and It's very hard to find documentation which explain in deeply about it - so I hope you'll be able to help me.
I'm trying to make an service (interface) which has a function that return a field with functions (for example: another interface).
I tried this code:
namespace java test
service A {
string somefunc()
}
service B {
string somefunc2(),
A getA()
}
But I didn't success.. when I try to compile the thrift file I get an error that it in service B - A field is not defined.
I tried also:
namespace java test
struct A {
1: string somefunc()
}
service B {
A getA()
}
This time it compiled successfully but it didn't count somefunc as a function however as a field in type of string.
Is there anyway make something like what I want?
Thanks!
Thrift sends serialized data structures over the wire. There's no standart way to send executable code. Various languages allow transferring code over the wire (i.e., java .class file or python script in text form) but can't be made interoperable and thus not supported by thrift.
However, thrift might be used for service discovery, if it's what you need. Single thrift service is always bound on specific host/port. So, thrift definition for service discovery code might look like this:
namespace java test
struct Endpoint {
1: required string host;
2: required i32 port;
}
service A {
string somefunc()
}
service B {
string somefunc2(),
Endpoint getA()
}
The service discovery code might look like this:
B.Client bClient = <.....>
Endpoint endpoint = bClient.getA();
TTransport transport = new TSocket(endpoint.host, endpoint.port);
transport.open();
A.Client aClient = = new A.Client(new TBinaryProtocol(transport));
aClient.somefunc2();
If it's needed, Endpoint definition might be extended with protocol/transport metadata allowing to choose between binary/compact/JSON protocols and TTransport/TFramedTransport/etc..
Currently our application uses GWT-RPC for most client-server communication. Where this breaks down is when we need to auto generate images. We generate images based on dozens of parameters so what we do is build large complex urls and via a get request retrieve the dynamically built image.
If we could find a way to serialize Java objects in gwt client code and deserialize it on the server side we could make our urls much easier to work with. Instead of
http://host/page?param1=a¶m2=b¶m3=c....
we could have
http://host/page?object=?JSON/XML/Something Magicical
and on the server just have
new MagicDeserializer.(request.getParameter("object"),AwesomeClass.class);
I do not care what the intermediate format is json/xml/whatever I just really want to be able stop keeping track of manually marshalling/unmarshalling parameters in my gwt client code as well as servlets.
Use AutoBean Framework. What you need is simple and is all here http://code.google.com/p/google-web-toolkit/wiki/AutoBean
I've seen the most success and least amount of code using this library:
https://code.google.com/p/gwtprojsonserializer/
Along with the standard toString() you should have for all Object classes, I also have what's called a toJsonString() inside of each class I want "JSONable". Note, each class must extend JsonSerializable, which comes with the library:
public String toJsonString()
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return serializer.serializeToJson(this).toString();
}
To turn the JSON string back into an object, I put a static method inside of the same class, that recreates the class itself:
public static ClassName recreateClassViaJson(String json)
{
Serializer serializer = (Serializer) GWT.create(Serializer.class);
return (ClassName) serializer.deSerialize(json, "full.package.name.ClassName");
}
Very simple!
I know that GWT has a good RPC support. But for various purposes I need to build this on my own:
1.) How can I convert a Bean Object (on the Client Side) like;
class MyPerson {
String name;
String getName();
void setName(String name);
//..
}
with GWT into a JSON String? (Ideally only using libraries that come officially from GWT/Google).
2.) Secondly, how can I send this generated JSON String from the Client side to any Server also using any GWT Client Logik. (Ideally only using libraries that come officially from GWT/Google).
I have searched a lot, but the examples never show how to send data but only to receive JSON data.
Thank you very much!!!
Jens
There's a nifty class called AutoBeanFactory that GWT will create for you, no third-party libs required. See http://google-web-toolkit.googlecode.com/svn-history/r9219/javadoc/2.1/com/google/gwt/editor/client/AutoBeanFactory.html
Once you have your AutoBeanFactory, you can use it like this:
producing JSON from an object of type SimpleInterface
AutoBean<SimpleInterface> bean = beanFactory.create(SimpleInterface.class, simpleInterfaceInstance);
String requestData = AutoBeanCodex.encode(bean).getPayload();
useRequestBuilderToSendRequestWhereverYouWant(requestData);
parsing JSON from an object of type SimpleInterface
SimpleInterface simpleInterfaceInstance = AutoBeanCodex.decode(beanFactory, SimpleInterface.class, responseText).as();
You can use RequestBuilder to send these requests without GWT-RPC or the RF stuff.
I recommend you use RestyGWT it makes JSON rest services work just like GWT RPC services.
Take a look at GWT's AutoBean framework, which can be used to create and receive JSON payloads. The RequestBuilder type can be used to send HTTP requests to the server.
You have also another solution which is 3rd party solution, maybe a second place solution but it can be also the first place.
The 3rd party called GSON and it's a project open source on google code.
You can find it here.
I used it and it's very good and very simple.