Server side (main) :
Registry rmiRegistry = LocateRegistry.createRegistry(ServerImpl.port);
IServer obj = new ServerImpl();
String url = "//"+InetAddress.getLocalHost().getHostName()+":"+ServerImpl.port+"/obj_server";
Naming.rebind(url, obj);
System.out.println(obj);
Client side (main):
IServer server_obj = (IServer)Naming.lookup("obj_server");
server_obj.sayHello();
System.out.println(server_obj);
Hey im new to RMI and i want to know how we can explain that the reference of server_obj and obj are the same (.hashcode() are equals) even if server_obj is a reference "pointing to" a local stub ( in Client_JVM) and obj is reference of the real obj (in Server_JVM).
Thanks,
i expected that &obj_server $\neq$ &obj
Related
I'm a novice in both Java and C#, so please bear with me.
I've made a Web Service in C# with the .Net Framework that is connected to one table in my MSSQL Server database. I've made a Java Application in Eclipse with a Web Service Client that is connected to the Web Service in Visual Studio with a SoapProxy through localhost.
The problem is that the webmethod I've made in C# is returning the Library table from MSSQL as a DataSet which I have no idea how to call as a method and print in the console of my Java Client.
Is there any better way going about the webmethod to get my table from MSSQL to VisualStudio and then printing it in my Eclipse Console?
Java Web Service Client
http://imgur.com/a/oCGzy
C# Web Service
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WSDB : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public DataSet getBooks()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=.;database=Library;user=sa;password=1234";
SqlDataAdapter da = new SqlDataAdapter("select * from Library", con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
What should the code in my Java Web Service Client look like to call and print this DataSet in the console the easiest most basic way? (formatting doesn't have to be pretty)
Update
I tried a different approach with a new WebMethod, connecting to my database with ADO.Net Entity Framework.
But I'm still clueless how to call and print the method in my Java Web Client, any suggestions?
[WebMethod]
public Library GetLibInfo(string booknr)
{
return libEnt.Libraries.Single(x=> x.booknr == booknr);
}
I'm not a c# programmer but from what I read about Dataset I see that is a stateful object, you should only return serializable objects from a WS.
So put your result into a simple array and return that.
Anyway you should call somethink like this:
you should have something like this:
WSDBLocator service = new WSDBLocator();
GetBooksReponseGetBookResults res = service.getGetBooks();
SomeKindOfCollection col = res.someMethod();
for(SomeKindOfObject o : col){
System.out.print(o.getProperty1());
System.out.print(",");
System.out.print(o.getProperty2());
System.out.print(",");
System.out.printLn(o.getProperty3());
}
If formatting isn't an issue you can just import the data from your DataTable into an object array and return it.
[WebMethod]
public object[] javaCustomer()
{
connectCronus(); //changes the ConnectionString
int count = 0;
cmd = new SqlCommand("select [Name],[City] from [CRONUS Sverige AB$Customer];");
dt = returnDataTable();
object[] ar = new string[dt.Rows.Count];
foreach (DataRow row in dt.Rows)
{
ar[count] = row["Name"].ToString() + "\t" + row["City"].ToString();
count++;
}
return ar;
}
Then it's just a matter of printing it in your java client.
for(Object o : proxy.javaEmployee()){
System.out.println(o);
}
Does Java codemodel support GenericEntity ?
I am trying to generate a code like below using jcodemodel:
Object obj = new GenericEntity<List<java.lang.String>>(listStr){}
But I am not able do that. I used below code :
JType jObjType = ((JClass) jcodemodel._ref(GenericEntity.class)).narrow(jcodemodel.ref(List.class).narrow(
jcodemodel.ref(String.class)));
JVar jvobj = jMethodResource.body().decl(jcm.ref(Object.class), "obj", JExpr._new(jObjType).arg(.....listStr reference...));
The code obtained using this is as follows :
Object obj = new GenericEntity>(listStr)
But "{}" is missing.
Can anyone help me here? How do a code so that I am obtained with {} :
Object obj = new GenericEntity<List<java.lang.String>>(listStr){}
Use this method (https://codemodel.java.net/nonav/apidocs/com/sun/codemodel/JCodeModel.html#anonymousClass(com.sun.codemodel.JClass)). Something like that:
JClass listOfEmplType = jcodemodel.ref(List.class).narrow(jcodemodel.ref(
Emplyee.class.getName()));
JVar listOfEmpl = jMethodResource.body().decl(listOfEmplType, "listStr", JExpr._null());
JClass jObjType = ((JClass) jcodemodel._ref(GenericEntity.class)).narrow(listOfEmplType);
JVar jvobj = jMethodResource.body().decl(jcodemodel.ref(Object.class), "obj",
JExpr._new(jcodemodel.anonymousClass(jObjType)).arg(listOfEmpl));
I am using Jersey client to access rest service.
I am using JSONObject and setting a "null" literal in it. It fails while it is serialized.
Upon investigating, I found JSONNull.equals() method has this "null".equals(value) then it considers the value as JSONNull object.
And then, JSONNull#isEmpty() throws exceptions.
net.sf.json.JSONObject params = new net.sf.json.JSONObject();
params.put("PGHIDENTIFIE", "null");
And when serialized it throws:
Caused by: com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.JsonMappingException: Object is null (through reference chain: net.sf.json.JSONObject["PGHIDENTIFIE"]->net.sf.json.JSONNull["empty"])
How can I serialize that "null" value inside JSONObject? Thanks!
DefaultClientConfig defaultClientConfig = new DefaultClientConfig();
defaultClientConfig.getClasses().add(JacksonJsonProvider.class);
Client client = Client.create(defaultClientConfig);
WebResource webResource = client.resource(apiUrl);
ClientResponse response =
webResource.path(apiUrl).accept("application/json")
.type("application/json").post(ClientResponse.class, params);
I am hitting a wall trying to get data loaded in a JSON array successfully passed to a java class that runs over the Neo4j server. My intent is to pass a list of entries from the client side to the server - nothing special here. What I am doing is reading the entries on the client side, loading those entries into JSON objects and then putting each JSON object into a JSON array which is then to be passed to the server for further processing.
Here is a section of the client side code that loads the json object and array. NOTE: the below is
just the json related code stripped down w/o the try/catch and other items resident in the code.
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value1);
jsonObject.put("field2", field2Value1);
jsonObject.put("field3", field3Value1);
jsonArray.put(jsonObject);
JSONObject jsonObject = new JSONObject();
jsonObject.put("field1", field1Value2);
jsonObject.put("field2", field2Value2);
jsonObject.put("field3", field3Value2);
jsonArray.put(jsonObject);
Here is the client side code that handles the http post part of the equation - I believe this is ok.
StringEntity stringEntity = new StringEntity(jsonArray.toString());
stringEntity.setContentType("application/json");
HttpPost post = new HttpPost(
"http://"server":7474/db/data/ext/serverSideClass/graphdb/processJSONData");
post.setEntity(stringEntity);
HTTPPostResponseResults httpResponse = new HTTPPostResponseResults();
httpResponse.checkResponse(post);
Here is the method interface to the server side code and this is where I believe my problem lies. I am thinking the parameter type needs to something other than JSONArray but am not sure what.
#Name("processJSONData")
#Description("process the data passed in.")
#PluginTarget(GraphDatabaseService.class)
public String processJSONData(#Source GraphDatabaseService graphDb,
#Parameter(name = "jsonArray") JSONArray jsonArray) {
And... here is the error being thrown.
"message" : "java.util.ArrayList cannot be cast to java.util.Map",
"exception" : "BadInputException",
"fullname" : "org.neo4j.server.rest.repr.BadInputException",
"stacktrace" : [ "org.neo4j.server.rest.repr.formats.JsonFormat.readMap(JsonFormat.java:92)",
"org.neo4j.server.rest.repr.RepresentationFormat.readParameterList(RepresentationFormat.java:97)",
"org.neo4j.server.rest.web.ExtensionService.invokeGraphDatabaseExtension
The above should cover it for the items related to this posting. If there is anything needed to clarify this please let me know and I'll provide it. Thank you in advance.
I am using BlazeDS java client to get info from this page.
This page has a form in the middle that when you select a type, the location combo on the button gets updated.
I am trying to use BlazeDS to get those values in java.
I have been using Charles web proxy to debug, and this are the screenshots from the request and the response:
My code so far is the following:
// Create the AMF connection.
AMFConnection amfConnection = new AMFConnection();
// Connect to the remote url.
String url = "http://orlandoinfo.com/flex2gateway/";
try
{
amfConnection.connect(url);
}
catch (ClientStatusException cse)
{
System.out.println(cse);
return;
}
// Make a remoting call and retrieve the result.
try
{
// amfConnection.registerAlias("flex.messaging.io.ArrayCollection", "flex.messaging.io.ArrayCollection");
amfConnection.call("ColdFusion.getLocations", new Object[] {"consumer", "attractions", "ATTR"});
}
catch (ClientStatusException cse)
{
System.out.println(cse);
}
catch (ServerStatusException sse)
{
System.out.println(sse);
}
// Close the connection.
amfConnection.close();
When I run it I get a:
ServerStatusException
data: ASObject(15401342){message=Unable to find source to invoke, rootCause=null, details=null, code=Server.Processing}
HttpResponseInfo: HttpResponseInfo
code: 200
message: OK
Can anyone spot what's wrong?
Thanks for reading!
I ended up using Charles Web Proxy. Sniffing AMF parameters and running my code with -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=8888
I compare both calls and modify to look alike.
The working code looks like this:
String url = "http://www.theGateWayurl.com";
// Generates the connection to the amf gateway.
AMFConnection amfConnection = new AMFConnection();
// Must register the class that this library will use to load the
// AMF object information.
// The library will read AMF object variables and use setters from
// the java bean stated in this line.
AMFConnection.registerAlias("", new LabelData().getClass().getName());
try {
// Do the connection.
amfConnection.connect(url);
// This page requires a certain headers to function.
// The Content-type is used to sniff with Charles Web Proxy.
amfConnection.addHttpRequestHeader("Content-type", "application/x-amf");
// The Referer is used by the webpage to allow gathering information.
amfConnection.addHttpRequestHeader("Referer", "http://orlandoinfo.com/ws/b2c/sitesearch/customtags/comSearch.swf");
// The rest of the HTTP POST sent by this library is wrapped
// inside a RemotingMessage.
// Prepare the msg to send.
RemotingMessage msg = new RemotingMessage();
// The method called in the server.
msg.setOperation("getLocations");
// Where the request came from. Similar to referer.
msg.setSource("ws.b2c.sitesearch.components.myService");
// The destination is a needed parameter.
msg.setDestination("ColdFusion");
// Create the body with the parameters needed to call the
// operation set with setOperation()
msg.setBody(new Object[] {"consumer", "attractions"});
// This is needed but not used.
msg.setMessageId("xxxxxxxxxx");
// Send the msg.
AcknowledgeMessage reply = (AcknowledgeMessage) amfConnection.call("null", msg);
// Parse the reply from the server.
ArrayCollection body = (ArrayCollection) reply.getBody();
for (Object obj : body) {
LabelData location = (LabelData) obj;
// Do something with the info.
}
} catch (ClientStatusException cse) {
// Do something with the exception.
} catch (ServerStatusException sse) {
// Do something with the exception.
} finally {
amfConnection.close();
}
The LabelData is just a java bean with with two vars: Data and Label.
I tried to comment every line for a better understanding.
Take into account what Stu mention in previous comments about crossdomain.xml to see if you have the rights to do this kind of things.