Assignment Operator in StringBuffer not working - stringbuffer

public class Test
{
static void operate(StringBuffer x, StringBuffer y)
{
x.append(y);
y=x;
}
public static void main(String args[])
{
StringBuffer x=new StringBuffer("Sun");
StringBuffer y=new StringBuffer("Java");
operate(x,y);
System.out.println(x+","+y);
}
}
his Prints : SunJava,Java
Can anyone please explain why it is printing like that instead of SunJava,SunJava ?

You pass a reference to the StringBuffer in y to your operate function. Then in operate, you change the reference, but not the object. After the call to operate, your main function still has a reference to the StringBuffer it originally allocated.

Related

JsonpRequestBuilder with typed response throws InCompatibleClassChangeError

I have an existing app that I'm adding a "Suggested Products" feature to and I'm having trouble with my JSONP response not being properly transformed to the typed JsArray. I'm hoping someone can give me an idea of what I'm doing wrong?
I have defined my type that will be returned from the server in its own class:
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName();
public final native String getImageURL();
}
I have a method that uses the JsonpRequestBuilder to fire off a request to get my JSON.
private void loadSuggestedProducts() {
JsonpRequestBuilder builder = new JsonpRequestBuilder();
builder.requestObject(buildSuggestedProductURL(), new AsyncCallback<JsArray<SuggestedProduct>>() {
public void onFailure(Throwable caught) {
//Handle errors
}
public void onSuccess(JsArray<SuggestedProduct> data) {
if ( data == null) {
//Handle empty data
return;
}
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<h4>Suggested Products:</h4>");
for (int i=0; i < data.length(); i++) {
SuggestedProduct product = data.get(i); //<- This line throws the exception
sb.appendHtmlConstant("<div class=\"card\">");
sb.appendHtmlConstant("<img class=\"card-img-top\" src=\"" + product.getImageURL() + "\" alt=\"" + product.getFormName() + "\">");
sb.appendHtmlConstant("<div class=\"card-body\">");
sb.appendHtmlConstant("<h5 class=\"card-title\">" + product.getFormName() + "</h5>");
sb.appendHtmlConstant("<a onclick=\"javascript:addItems();\" class=\"cmd-add\">Add <i aria-hidden=\"true\" class=\"fa fa-plus-circle\"></i></a>");
sb.appendHtmlConstant("</div></div>");
}
view.getSuggestedProducts().setInnerSafeHtml(sb.toSafeHtml());
}
});
}
When I try to use a SuggestedProduct from the response, I get an error:
java.lang.IncompatibleClassChangeError: Found interface
com.google.gwt.cor.client.JsArray, but class was expected
I've been following the guide in the GWT documentation. I don't see any difference between what I'm trying and what they say will work. When I debug, it looks as though the returned data is an array of SuggestedProducts, so I'm stumped as to how to proceed. Any help would be appreciated.
After closer inspection I realized my overlay type was missing method bodies for what fields to return from the JSON object they represented. The fix was to include the proper JSNI method definitions.
import com.google.gwt.core.client.JavaScriptObject;
public class SuggestedProduct extends JavaScriptObject {
protected SuggestedProduct() {}
public final native String getFormName() /*-{ return this.formname; }-*/;
public final native String getImageURL() /*-{ return this.imageurl; }-*/;
}

Singleton class with updated parameters in java

public class ThreadSafeSingleton implements Serializable {
#Override
public String toString() {
return "ThreadSafeSingleton [i=" + i + ", str=" + str + "]";
}
int i;
String str;
private static ThreadSafeSingleton instance;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
private ThreadSafeSingleton(){
}
public static synchronized ThreadSafeSingleton getInstance(int i,String str){
if(instance == null){
synchronized (ThreadSafeSingleton.class) {
if(instance == null){
instance = new ThreadSafeSingleton();
}
}
}
instance.setI(i);
instance.setStr(str);
return instance;
}
public Object readResolve(){
System.out.println("readResolve executed");
return getInstance(this.i,this.str);
}
public static void main(String[] args) throws IOException, Exception {
FileOutputStream fos = new FileOutputStream(
"B://Serilization//text1.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
ThreadSafeSingleton obj = new ThreadSafeSingleton();
obj.setI(1);
obj.setStr("katrina kaif");
oos.writeObject(obj);
System.out.println("serilization done");
FileInputStream fis = new FileInputStream("B://Serilization//text1.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
ThreadSafeSingleton copy=(ThreadSafeSingleton) ois.readObject();
System.out.println("copy "+copy);
System.out.println("deserilization done");
}
}
in the above code i have a singleton class containing int i and String str attributes and i have implemented Serializable interface my requirement is that when i serialized a class i will serialize the class with some attributes values on one JVM and when i deserialize on another JVM i should get the same instance of my singleton class but the attributes in the class should get updated with the values i provided during serialization
here on internet i checked the solution i got to use readResolve method there you can write a logic which will set the values of attributes i provided during serialization of my singleton class so if you will see the code of readResolve i have written a code like this "return getInstance(this.i,this.str);" here i have used "this" keyword which means a current object is being used therefore i have question
i have doubt that is this code creating new object here as "this" refers to the current object apart from the object i created in the getInstance(int i,String str) method can anybody please explain is this breaking singleton ?
You may want to read up on Java serialization: readObject() vs. readResolve(). When readResolve() is called, your object has already been deserialized from the stream and fully created. Your this pointer, in that case, will be the object that the deserialization process has constructed, complete with the i and str values from the stream. If you use this.i and this.str to construct the new Singleton, you're not creating a new object with the new JVM's specific parameters.

How to solve waiting for RPC response in GWT?

I know that the RPC is asynchronous but how Can in other way (other than waiting for response) to solve this problem:
public static String htsl(String sentence)
{
final DataBaseAsync db = GWT.create(DataBase.class);
String cookie = staticContent.getCookie("ll");
String shortcut = cookie.split("/")[1];
final String[] lala = new String[1];
database.getTranslated(sentence, shortcut, new AsyncCallback<String>() {
#Override
public void onSuccess(String result) {
lala[0]=result;
//this result I want to return in static function htsl... ?
}
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
});
//here I have blank result, because RPC is slower than te return..
And i have always blank result
return lala[0];
}
I know that is not good, but.. If it is no working solution for this, how to wait for response?
Make htsl asynchronous (non-blocking, i.e. with a callack for the response rather than a return value)
Do it like so:
public static String htsl(String sentence, AsyncCallback<String> myCallback) {
final DataBaseAsync db = GWT.create(DataBase.class);
String cookie = staticContent.getCookie("ll");
String shortcut = cookie.split("/")[1];
final String[] lala = new String[1];
database.getTranslated(sentence, shortcut, myCallback);
}
Then you let some other class implement AsyncCallback, pass it as the myCallback argument to the htsl method and Bob's your uncle.

How to call java method from javascript method that located within another jsni method

public class A{
private void javaMethod(int a,int b){}
private native void init()/*-{
function OnMouseMove(e) {
//blow calling doesn't work
this.#p::javaMethod(Ljava/...teger;Ljava.../Integer;)(intVal,intVal);
}
}-*/;
}
As described above,how to make that invoking work?
Answered on the Google Group: https://groups.google.com/d/msg/google-web-toolkit/qE2-L4u_t4s/YqjOu-bUfsAJ
Copied here for reference and convenience:
First, int is not java.lang.Integer, so your method signature in JSNI is wrong; it should read javaMethod(II).
(I suppose the #p:: while javaMethod is defined in class A is over-simplification in your question, but is OK in your code)
You'll also probably have a problem with this, that might not be what you think it is. A common pattern is to assign the current object (this, at the time) to a variable that you'll reference from your closure:
var that = this;
…
function OnMouseMove(e) {
that.#p.A::javaMethod(II)(intVal, intVal);
}
You're doing two things wrong:
You're not defining the class name after #p, (assuming #p is actually just a shortened version of the real package's name);
You're attempting to pass java.lang.Integer in place of int. You should be saying (II) as the types, as described here.
Your code should look more like this:
package com.my.package;
public class ClassA {
private static void javaMethod(int a, int b) { ... }
public static native void init() /*-{
$wnd.javaMethod = function(a, b) {
return #com.my.package.ClassA::javaMethod(II)(a,b);
}
function OnMouseMove(e) {
$wnd.javaMethod(a,b);
}
}-*/;
}

Use Java constant in GWT Javascript Overlay Type (JSO)?

I would like to define the GWT JSO property name as a constant in the JSO, in order to avoid typos and benefit from Eclipse code completion, like so:
public final class MyJSO extends JavaScriptObject
{
/** here is the constant */
private static final String MY_CONST = "myPropName";
protected MyJSO() {
super();
}
public native void setMyProp(final boolean pFlag)
/*-{
this.#fully.qualified.MyJSO::MY_CONST = pFlag;
}-*/;
public native boolean isMyProp()
/*-{
if (this.hasOwnProperty(#fully.qualified.MyJSO::MY_CONST)) {
return this.#fully.qualified.MyJSO::MY_CONST;
} else {
return false;
}
}-*/;
}
The GWT compiler should be able to replace the String from the constant at compile time, so there is no problem with the object living as Javascript later on.
But this is so totally not working, I'm thinking I may be wrong. :-) Can anyone explain why? Do you have better ideas how to achieve this?
Thanks!
The correct syntax to refer to a static variable is:
#fully.qualified.MyJSO::MY_CONST
No qualifier (this., in your example) is needed since the variable is static.
If you want to set/get a property on the JavaScript object with the constant name do so as follows:
public native void setMyProp(final boolean pFlag) /*-{
this[#fully.qualified.MyJSO::MY_CONST] = pFlag;
}-*/;
public native boolean isMyProp() /*-{
if (this[#fully.qualified.MyJSO::MY_CONST] != null) {
return this[#fully.qualified.MyJSO::MY_CONST];
} else {
return false;
}
}-*/;