GWT Create JAVAscriptObject form string - gwt

I have a model such as bellow.
public class ColumnDtoWrapper extends JavaScriptObject{
protected ColumnDtoWrapper() {}
public final native JsArray<ColumnDto> getfields() /*-{
return this.fields;
}-*/;
public final native void gettable() /*-{
return this.table;
}-*/;
public final native JavaScriptObject getHasMany() /*-{
return this.hasmany;
}-*/;
}
I Make server call like
RequestBuilder build = new RequestBuilder(RequestBuilder.POST, URL);
try {
Request request = build.sendRequest(null, new RequestCallback(){
#Override
public void onResponseReceived(Request request, Response response) {
if(200== response.getStatusCode()){
}
}
#Override
public void onError(Request request, Throwable exception) {
Window.alert("error : " + exception.getLocalizedMessage());
}
});
} catch (Exception e) {
Window.alert("try err");
}
When i got success responce in JSON string.
I want to convert that string as ColumnsDtoWrapper.
somthing like ColumnDtoWrapper col = new ColumnDtoWrapper(responce.getText());
but it not works is there any good way to convert string to JavaScriptObject?

Use JsonUtils.safeEval:
ColumnDtoWrapper col = JsonUtils.safeEval(response.getText());

Related

Asynchronous GET on REST with okhttp3

I am trying to perform an asynchronous GET-request on my openHAB-project. I have done it before and reused parts of my code to create a new Android app, but it is not working.
In theory I want the state of the "GastSwitch"-item to be written into a String (gastSwitchState) to then be used as a trigger for opening a different activity. If the result of the request is "OFF" the app is supposed to keep running, but stay in the MainActivity.
When debugging it seems like the getGastSwitchState-method is jumped entirely after the enqeue-Method is called. Can someone explain to me, why my code seems to leave out half of the method?
I know that this way of doing it should work, but I can't find where I went wrong.
//connect with REST-API in openHAB :
// GET Status GastSwitch: if Switch = "ON" go to MeetingActivity
//Timer to GET the GastSwitch-status every 30 seconds:
TimerTask gastSwitchTimerTask = new TimerTask() {
public void run() {
try {
getGastSwitchState("myURLforOpenHABGastSwitchState", new Callback() {
#Override
public void getParameter(String string) {
if (gastSwitch.equals("ON")) {
Intent activityIntent = new Intent(getApplicationContext(), MeetingActivity.class);
startActivity(activityIntent);
}
}
});
} catch (IOException e) {
e.printStackTrace();
tvLog.setText(e.toString());
}
}
};
// Timer for GETting the GastSwitch-state every 30 seconds
long emergencyDelay = 1000 * 30 * 1;
Timer gastSwitchTimer = new Timer();
gastSwitchTimer.schedule(gastSwitchTimerTask, 0, emergencyDelay);
}
//Method for GETting the GastSwitch-state from REST-API:
void getGastSwitchState(String url, final Callback callback) throws IOException {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.method("GET", null)
.addHeader("AuthToken", "")
.build();
client.newCall(request)
.enqueue(new okhttp3.Callback() {
#Override
public void onResponse(#NotNull okhttp3.Call call, #NotNull Response response) throws IOException {
if (response.isSuccessful()) {
final String res = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
gastSwitch = res;
tvLog.setText(gastSwitch);
callback.getParameter(gastSwitch);
}
});
}
}
#Override
public void onFailure(#NotNull okhttp3.Call call, #NotNull IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
});

Issue with Google Contacts API

I'm running an issue with gwt-oauth and Google contacts API.
I use gwt-oauth to login and everything works fine.
While running the RPC for retrieving the contacts I get
WARNING: Authentication error: Unable to respond to any of these challenges: {}
java.lang.NullPointerException: No authentication header information
Here is the code in Client
Button button = new Button("Authenticate with Google");
button.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
final AuthRequest req = new AuthRequest(K.GOOGLE_AUTH_URL, K.GOOGLE_CLIENT_ID).withScopes(K.CONTACTS_SCOPE, K.AUTH_SCOPE);
AUTH.expiresIn(req);
AUTH.login(req, new Callback<String, Throwable>() {
#Override
public void onSuccess(final String token) {
greetingService.loginDetails(token, new AsyncCallback<LoginInfo>() {
#Override
public void onSuccess(LoginInfo result) {
greetingService.getContactList(token, new AsyncCallback<Boolean>() {
#Override
public void onSuccess(Boolean result) {
Window.alert("oh");
}
#Override
public void onFailure(Throwable caught) {
Window.alert("Error:\n" + caught.getMessage());
}
});
}
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onFailure(Throwable caught) {
Window.alert("Error:\n" + caught.getMessage());
}
});
}
});
And here the serverside for contacts:
try {
ContactsService s = new ContactsService(K.APPLICATION_NAME);
s.setProtocolVersion(ContactsService.Versions.V3);
s.setAuthSubToken(token);
s.setHeader("Authorization", "Bearer " + token);
for (ContactEntry entry : s.query(new Query(new URL(K.CONTACTS_SCOPE)), ContactFeed.class).getEntries())
System.out.println(entry.toString());
} catch (Exception e) {
e.printStackTrace();
}
return true;
This was working couple of weeks ago...
I assume is not a scope issue since loginDetails works properly...
Any idea?
Solved.
Scope for contacts in Auth was set to: https://www.google.com/m8/feeds/contacts/default/full/
Apparently this doesn't work anymore and I just set https://www.google.com/m8/feeds/ for auth
and the full url for querying in ContactService

formpanel.submit does not submit the file on GWT server

i want to send a file from client to server.
My code:
Client side:
private FormPanel getFormPanel() {
if (formPanel == null) {
formPanel = new FormPanel();
formPanel.setMethod(FormPanel.METHOD_POST);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setAction(GWT.getHostPageBaseURL() +"UploadFileServlet");
formPanel.setWidget(getFlexTable_1());
System.out.println(GWT.getHostPageBaseURL() +"UploadFileServlet");
}
return formPanel;
}
In getFlexTable_1()
flexTable.setWidget(1, 1, getFileUpload());
In getFileUpload()
private FileUpload getFileUpload() {
if (fileUpload == null) {
fileUpload = new FileUpload();
fileUpload.setName("upload");
}
return fileUpload;
}
private Button getAddButton() {
if (addButton == null) {
addButton = new Button("ADD");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
formPanel.submit();
}
});
}
return addButton;
}
On server side
public class CmisFileUpload extends HttpServlet implements Servlet{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
byte[] buffer = new byte[115200];//
String fileName = null;
String mimetype = null;
String majorVersion = null;
InputStream stream = null;
System.out.println("ServletWorking Fine");
}
Now when i Choose a file and click on ADD button i cant see the output on server side for this code System.out.println("ServletWorking Fine");
The outPut of System.out.println(GWT.getHostPageBaseURL() +"UploadFileServlet"); on client side is
http://127.0.0.1:8888/UploadFileServlet
and when i use this url directly on browser i get server side output for System.out.println("ServletWorking Fine");**
Edited
I created one more web application for file upload
public class Uploadfile implements EntryPoint {
FormPanel uploadForm = new FormPanel();
public void onModuleLoad() {
HorizontalPanel horizontalPanel = new HorizontalPanel();
uploadForm.setAction(GWT.getHostPageBaseURL() +"UploadFileServlet");
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
horizontalPanel.add(uploadForm);
// Create a panel to hold all of the form widgets.
VerticalPanel panel = new VerticalPanel();
uploadForm.setWidget(panel);
FlexTable flexTable = new FlexTable();
panel.add(flexTable);
// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
flexTable.setWidget(2, 3, upload);
// panel.add(upload);
// Add a 'submit' button.
Button uploadSubmitButton = new Button("Submit");
panel.add(uploadSubmitButton);
uploadSubmitButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
uploadForm.submit();
}
});
uploadForm.addFormHandler(new FormHandler() {
public void onSubmit(FormSubmitEvent event) {
}
public void onSubmitComplete(FormSubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
RootPanel.get().add(horizontalPanel);
}
}
Server
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
System.out.println("working fine" );
}
This code is working fine
According to me there is no difference between the codes.
Plz tell me why the formpanel.submit is not working properly.
Plz help.
Is hide() method is closing the window??? If Yes then
remove move code hide(); after formPanel.submit();
for hide() use FormHandler. for eg
uploadForm.addFormHandler(new FormHandler() {
public void onSubmitComplete(FormSubmitCompleteEvent event) {
hide();
}
public void onSubmit(FormSubmitEvent event) {
}
});
reason: The FormPanel must not be detached (i.e. removed from its parent until the submission is complete. Otherwise, notification of submission will fail.
Why you have mapped for GET method for file upload. The GET request method is serving for the url entered in browser. Remove the GET Request Map, it will work.
For the POST request map, you can use MultipartFile for RequestParam as below
protected void uploadFileAndReconcilePayout1(#RequestParam("documentUpload") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
//code for file working
}

RequestFactory and offline clients

I'm trying to create an application which is able to work even when network is down.
The idea is to store data returned from RequestFactory on the localStorage, and to use localStorage when network isn't available.
My problem - I'm not sure exactly how to differentiate between server errors(5XX, 4XX, ...) and network errors.
(I assume that on both cases my Receiver.onFailure() would be called, but I still don't know how to identify this situation)
Any help would be appreciated,
Thanks,
Gilad.
The response code when there is no internet connection is 0.
With RequestFactory to identify that the request was unsuccessful because of the network the response code has to be accessed. The RequestTransport seems like the best place.
Here is a rough implementation of an OfflineAwareRequestTransport.
public class OfflineAwareRequestTransport extends DefaultRequestTransport {
private final EventBus eventBus;
private boolean online = true;
public OfflineAwareRequestTransport(EventBus eventBus) {
this.eventBus = eventBus;
}
#Override
public void send(final String payload, final TransportReceiver receiver) {
// super.send(payload, proxy);
RequestBuilder builder = createRequestBuilder();
configureRequestBuilder(builder);
builder.setRequestData(payload);
builder.setCallback(createRequestCallback(receiver, payload));
try {
builder.send();
} catch (RequestException e) {
}
}
protected static final int SC_OFFLINE = 0;
protected RequestCallback createRequestCallback(final TransportReceiver receiver,
final String payload) {
return new RequestCallback() {
public void onError(Request request, Throwable exception) {
receiver.onTransportFailure(new ServerFailure(exception.getMessage()));
}
public void onResponseReceived(Request request, Response response) {
if (Response.SC_OK == response.getStatusCode()) {
String text = response.getText();
setOnline(true);
receiver.onTransportSuccess(text);
} else if (response.getStatusCode() == SC_OFFLINE) {
setOnline(false);
boolean processedOk = processPayload(payload);
receiver.onTransportFailure(new ServerFailure("You are offline!", OfflineReceiver.name,
"", !processedOk));
} else {
setOnline(true);
String message = "Server Error " + response.getStatusCode() + " " + response.getText();
receiver.onTransportFailure(new ServerFailure(message));
}
}
};
}

How to post data and redirect to another page using GWT?

When I press a button I post some data to server and there redirect to another page.
I used RequestBuilder but it is waiting the response, and of course get it. And nothing happens, same page stays. I see RequestBuidler shouldn't be used here... What should I use to post data and be able to redirect?
In Spring
#RequestMapping(method=RequestMethod.POST, value="/ddd")
public ModelAndView processOrder(#RequestBody String orderInString, HttpSession session) throws Exception{
...
return new ModelAndView(new RedirectView("abc"));
}
In GWT
public void postData(final String data, final String url) {
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
try {
builder.sendRequest(data, new RequestCallback() {
public void onError(Request request, Throwable exception) {
...
}
public void onResponseReceived(Request request,
Response response) {
if (200 == response.getStatusCode()) {
..
} else {
..
}
}
});
} catch (RequestException e) {
...
}
return;
}
FormPanel form = new FormPanel("_self");
form.setMethod(FormPanel.METHOD_GET);
Hidden params0 = new Hidden("param1", "value1");
Hidden params1 = new Hidden("param1", "value2");
Hidden params2 = new Hidden("param2", "value3");
FlowPanel panel = new FlowPanel();
panel.add(params0);
panel.add(params1);
panel.add(params2);
form.add(panel);
form.setAction(GWT.getModuleBaseURL() + "../MyServlet");
RootPanel.get().add(form);
form.submit();
Thats it. The code adds FormPanel and sends form.
Add more specifications, code, this is blur.
Since you are using Spring-mvc, you should be having something like this
private static final String newPage = "index2"; //this is resolved with view resolver
#RequestMapping(params = "action=button")
protected String getALPLicense(final RenderRequest request,
final RenderResponse response, final Model model) throws Exception {
try{
}catch{
}
return newPage; //this is your new redirected page
}