Getting Json data using ajax in Google app engine java - java

I'm unable to get data back from ajax request from java servlet using Json object..here is the code below we are using channel api in google app engine .we need to implement chat application.
displayFriendList = function() {
var txt = document.createElement("div");
txt.innerHTML = "<p> Logged in as <b>" + userid
+ "</b><p><hr />";
document.getElementById("friendlistdiv").appendChild(
txt);
var dataString ='userId='+userid;
$.ajax({
type : "POST",
url : "/OnlineUserServlet",
data : dataString,
success : function(html) {
alert(html.frndsList[0].friend);
}
});
};
Java Servlet Code:
while(friendList.hasNext()){
friend = friendList.next() ;
if(!friend.equals(user)){
Map<String, String> state = new HashMap<String, String>();
state.put("friend", friend);
state.put("type","updateFriendList");
state.put("message",user);
state1.add(state);
message = new JSONObject(state);
channelService.sendMessage(
new ChannelMessage(friend,message.toString()));
}
i++;
}
Map<String, String> statejason = new HashMap<String, String>();
statejason.put("friendsList", state1.toString());
//System.out.print("hello"+message.toString());
response.setContentType("text/plain");
response.getWriter().print(statejason.toString());
}

Your response type should be application/json.

Related

Java serverlet parse JSON data

I want to post JSON object from JavaScript to java serverlet.
I used the following javaScript code :
var a = {};
function SaveInfo(c)
{
document.getElementById("saveButton").className = "savebutton";
document.getElementById("cancelButton").className = "cancebutton";
var z= $(c).parent().parent().attr('id');
a[z] = c.value;
}
$("#saveButton").click(function(e){
if( document.getElementById("saveButton").className=="savebutton")
$.ajax({
url: "../../update",
type: 'POST',
dataType: 'json',
data: JSON.stringify(a),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
consol.log(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
});
and following java code :
public void doPost(HttpServletRequest req, HttpServletResponse res){
JSONObject jObj;
jObj = new JSONObject(req.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys();
while(it.hasNext())
{
String key = (String)it.next(); // get key
Object o = jObj.get(key); // get value
// store in session
}
}
JSON is successfully received.
Problem is there is no constructor for :
jObj = new JSONObject(req.getParameter("mydata"));
I want to read both values and keys passed via javascript.
For your purpose you can simply use a form, simply parse it like:
Map<String, String[]> map = request.getParameterMap();
for(Entry<String, String[]> e : map.entrySet()){
response.getWriter().write(e.getKey() + ":" + e.getValue()[0] + "\n");
}
Use json when you want to send an object or a complex data array etc.
Hope that completes your work.
Try the following:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(req.getParameter("mydata").toString());

GWT- POST object/json and go to another page

I referred this link : How to post data and redirect to another page using GWT?
I can use formpanel but I am stuck somewhere ,please help .
This is my code :
HashMap<String, String> map = new HashMap<String, String>();
map.add(...some information....); //want to send this map in POST
I want to send the map using POST and also I want to go to another page.
I can use this code (answered in How to post data and redirect to another page using GWT?):
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() + "../test");
RootPanel.get().add(form);
form.submit();
But how do I send already created map along with POST ?
At server side :
#RequestMapping(value = "/test",method = RequestMethod.POST)
#ResponseBody
public String test(#RequestBody final HashMap<String, String> map,HttpSession session)
{
//use the map
return another-page.jsp
}
Probably better to send data via RPC or AJAX and redirect to another page by Location.assign() or Location.replace(). If you expect the server to provide dynamic URL to redirect you can send it as a response for the RPC or AJAX request. In current example AJAX request is used:
// map is your existing map object
JSONObject data = new JSONObject();
for (String key : map.keySet()) {
data.put(key, new JSONString(map.get(key)));
}
RequestBuilder request = new RequestBuilder(RequestBuilder.GET, "<URL>");
request.setRequestData(data.toString());
request.setCallback(new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
String url = response.getText();
// url to redirect
Window.Location.assign(url);
}
#Override
public void onError(Request request, Throwable exception) {
// handle error
}
});
request.send();
Or you can serialize map to String and pass it as hidden field of a POST request.
Client code:
String buffer = Streamer.get().toString(map);
FlowPanel panel = new FlowPanel();
panel.add(new Hidden("map", buffer));
FormPanel form = new FormPanel("_self");
form.setMethod(FormPanel.METHOD_POST);
form.setAction(<URL>);
form.add(panel);
RootPanel.get().add(form);
form.submit();
Server code:
#RequestMapping(value = <URL>,method = RequestMethod.POST)
#ResponseBody
public String test(#RequestBody String mapString,HttpSession session)
{
Map<String, String> map = (Map<String, String>) Streamer.get().fromString(mapString);
// use the map
return another-page.jsp
}

Bonita Web API - 401 Unauthorized Error

I am trying to use Bonita Web API. I My code is below. As you can see I call the loginservice before calling any other API service. It logs in OK 200. But when I make the subsequent call to get the list of processes I get a 401 error. You get a JSESSIONID from the first call and you are suppose to pass it to the subsequent calls to authenticate you.
var baseAddress = new Uri(<base address>);
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
HttpResponseMessage result = client.PostAsync("/bonita/loginservice", new StringContent("login=<username>,password=<password>,redirect=false")).Result;
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage result2 = client.GetAsync("/bonita/API/bpm/process").Result;
result2.EnsureSuccessStatusCode();
}
This works for .Net 2.0 C# but has some interesting things to check.
WebClient wc = new WebClient();
wc.Proxy = WebRequest.GetSystemWebProxy();
//wc.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
string strLogin = wc.DownloadString("http://localhost:8080/bonita/loginservice?username=walter.bates&password=bpm&redirect=false");
wc.Headers[HttpRequestHeader.Cookie] = wc.ResponseHeaders[HttpResponseHeader.SetCookie].ToString();
string strCookie = wc.ResponseHeaders[HttpResponseHeader.SetCookie].ToString();
string strProcesses = wc.DownloadString("http://localhost:8080/bonita/API/bpm/process?p=0");
First of all you should know how to determine that the executed operation is successful ( login, getProcesses and whatever) When you try to login you will always get the header (for example "JSESSIONID=50E509D37AC28E2D725CBD45A8112FA7; Path=/bonita; HttpOnly") and OK 200 even if your login attempt in Bonita is unsuccesful.
For the successful login on the previous example
1) You must Pass mandatory form data: username, password and redirect You must also be sure to pass redirect in lower case ."False" will not work, "false" will work. So for .Net suppose you have a property-> Boolean redirect. You must make it lowercase with redirect.ToString().ToLower() cause either way the value will be "False" and you don't want that.
Let's say you try to login only with username and password without passing redirect. the result is that you will get both OK 200 and the header but you will also get a response which is wrong (the response must be empty), so on the next request (i.e getProcesses) you'll get (401) Unauthorized. Guess the results you will have if you pass redirect=False instead of redirect=false. Exactly the same.
2)You must get: strLogin="" // the body of the response must be empty strCookie="JSESSIONID=4F67F134840A2C72DBB968D53772FB22; Path=/bonita; HttpOnly"
For the successful getProcesses on the previous example you pass the header you got from login
wc.Headers[HttpRequestHeader.Cookie] = wc.ResponseHeaders[HttpResponseHeader.SetCookie].ToString();
and then you call the process and get a string in json format for example
"[{\"id\":\"6996906669894804403\",\"icon\":\"\",\"displayDescription\":\"\",\"deploymentDate\":\"2014-11-19 17:57:40.893\",\"description\":\"\",\"activationState\":\"ENABLED\",\"name\":\"Travel request\",\"deployedBy\":\"22\",\"displayName\":\"Travel request\",\"actorinitiatorid\":\"4\",\"last_update_date\":\"2014-11-19 17:57:41.753\",\"configurationState\":\"RESOLVED\",\"version\":\"1.0\"}]"
(or [] which means an empty json)
If the cookie is not passed correctly you will get again 401 error.
Solution for .Net 4.5.1
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace BonitaRestApi
{
class BonitaApi
{
private CookieCollection collection;
string strCookietoPass;
string sessionID;
static void Main(string[] args)
{
BonitaApi obj = new BonitaApi();
Task login = new Task(obj.Login);
login.Start();
login.Wait();
Console.ReadLine();
Task GetProcesses = new Task(obj.GetProcesses);
GetProcesses.Start();
GetProcesses.Wait();
Console.ReadLine();
Task logout = new Task(obj.Logout);
logout.Start();
logout.Wait();
Console.ReadLine();
}
public async void Login()
{
const string url = "http://localhost:8080/bonita/";
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
var uri = new Uri(url);
client.BaseAddress = uri;
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("username", "helen.kelly"),
new KeyValuePair<string, string>("password", "bpm"),
new KeyValuePair<string, string>("redirect", "false"),
new KeyValuePair<string, string>("redirectUrl", ""),
});
HttpResponseMessage response = await client.PostAsync("loginservice", content);
if (response.IsSuccessStatusCode)
{
var responseBodyAsText = await response.Content.ReadAsStringAsync();
if (!String.IsNullOrEmpty(responseBodyAsText))
{
Console.WriteLine("Unsuccessful Login.Bonita bundle may not have been started, or the URL is invalid.");
return;
}
collection= cookies.GetCookies(uri);
strCookietoPass = response.Headers.GetValues("Set-Cookie").FirstOrDefault();
sessionID = collection["JSESSIONID"].ToString();
Console.WriteLine(string.Format("Successful Login Retrieved session ID {0}", sessionID));
// Do useful work
}
else
{
Console.WriteLine("Login Error" + (int)response.StatusCode + "," + response.ReasonPhrase);
}
}
}
public async void Logout()
{
const string url = "http://localhost:8080/bonita/";
var cookies = new CookieContainer();
var handler = new HttpClientHandler();
handler.CookieContainer = cookies;
using (var client = new HttpClient(handler))
{
var uri = new Uri(url);
client.BaseAddress = uri;
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("redirect", "false")
});
HttpResponseMessage response = await client.PostAsync("logoutservice", content);
if (response.IsSuccessStatusCode)
{
var responseBodyText = await response.Content.ReadAsStringAsync();
if (!String.IsNullOrEmpty(responseBodyText))
{
Console.WriteLine("Unsuccessful Logout.Bonita bundle may not have been started, or the URL is invalid.");
return;
}
Console.WriteLine("Successfully Logged out.");
}
else
{
Console.WriteLine("Logout Error" + (int)response.StatusCode + "," + response.ReasonPhrase);
}
}
}
public async void GetProcesses()
{
var handler = new HttpClientHandler();
Cookie ok = new Cookie("Set-Cookie:",strCookietoPass);
handler.CookieContainer.Add(collection);
using (var client = new HttpClient(handler))
{
var builder = new UriBuilder("http://localhost/bonita/API/bpm/process");
builder.Port = 8080;
var query = HttpUtility.ParseQueryString(builder.Query);
query["p"] = "0";
query["c"] = "10";
builder.Query = query.ToString();
Uri uri= new Uri(builder.ToString());
client.BaseAddress = uri;
HttpResponseMessage response = await client.GetAsync(uri.ToString());
if (response.IsSuccessStatusCode)
{
var responseBodyText = await response.Content.ReadAsStringAsync();
if (String.IsNullOrEmpty(responseBodyText))
{
Console.WriteLine("Unsuccessful GetProcesses.Bonita bundle may not have been started, or the URL is invalid.");
return;
}
Console.WriteLine("Successfully GetProcesses:" + responseBodyText);
}
else
{
Console.WriteLine("GetProcesses Error" + (int)response.StatusCode + "," + response.ReasonPhrase);
}
}
}
}
}
I had the same problem (401 errors) for every single non-GET request.
I finally got through this by looking to the CSRF documentation:
http://documentation.bonitasoft.com/7.4?page=csrf-security
(See the "Is there an impact on REST API calls?" section)
After succesfull login, you have to put a special header in your request:
key: X-Bonita-API-Token
value: the one you got after your login (check the relevant cookie)

get json array from servlet using ajax

I have to json array in my servlet.
I want to fetch json array value and print in to jsp page using ajax.
below is code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
jsp
I got error msg here.
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
error : function() {
alert("Error");
},
success : function(data) {
alert(data);
}
});
See, if you want to pass that from servlet to jsp you need not to make a request (ajax), since servlet and jsp both exists at server side.You just set that json array as a request attribute or session attribute and get it in jsp and display(with loop).NO need of ajax there.
If You need to fetch the data with synchronous call:
In servlet
PrintWriter out = response.getWriter();
out.println(htags);
I won't clutter SO with another full example,see this SO post:How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?
Try this
servlet code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String jsons = "["+htags+","+trends+"]"; //Put both objects in an array of 2 elements
out.print(jsons);
and on you jsp page
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
contentType:"application/json",
error : function() {
alert("Error");
},
success : function(data) {
var data1=data[0],
var data2=data[2],
alert(data1[0]);
}
});
Servlet can use this to send json array or json object to client.
JSONArray jsonArray = [{:}, {:}];
response.getWriter.write(jsonArray.toString());
In JSP page, this method call the request JSON to Servlet and catch the json array or json object with annonymous function(JSON.parse is used to convert string to json object or json array) method.
$("button").click(function(){
$.get("ServletToJSP",function(data,status){
alert("Data: " + JSON.parse(data) + "\nStatus: " + status);
});
});
in servlet:
String uri = request.getRequestURI();
if (uri.equalsIgnoreCase(uri)) {
response.setContentType("application/json");
/* get the json array */
response.getWriter().write(array.toJSONString());
}
jquery:
$('#buttonid').on('click', function() {
var url="your url";
$.ajax({
type : 'POST',
url : url,
data : null,
error : function(xhr, status, error) {
alert("error");
},
success : function(data) {
alert("success");
$.each(data, function(key, val) {
console.log(val);
}
});
});

Servlet+jQuery/Ajax - Unexpted token o

I'm new to developing web applications with Java. I'm trying to establish an AJAX call. This is some arbitrary code that I've created.
Servlet
Map<String, String> testJson = new HashMap<String, String>();
String Key = "someKey";
String Value = "someValue";
testJson.put(Key, Value);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(testJson));
}
jQuery
$(document).on("click","#register-user", function(){
$.ajax({
type: 'GET',
url: 'Register',
success: function(data){
alert($.parseJSON(data));
}
});
return false;
});
The callback function is working without any Json so the AJAX is fine. But when I try to send back a Java object that is encoded with Json I get an "Uncaught exception. Unexpected token o". What am I doing wrong?
Try this
Gson gson = new GsonBuilder().create();
String json = gson.toJson(testJson);
or try a little something like this
Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
String json = gson.toJson(map, typeOfMap);
More examples of the above on this link
and then return the Stringed JSON

Categories