I have some Ajax methods which receives data from controller with HashMap object and everything worked fine.
This time,
I'm trying to retrieve the data with json type.
However, my server responses with error 406 (not acceptable).
I don't understand why the server cannot receive json type
I followed every step introduced in stackoverflow
(adding additional bean tag, changing content type , and so on..)
None of them worked
Here's my codes below.
#RequestMapping(value="/report/getMember", produces="application/json",
method=RequestMethod.GET)
public #ResponseBody JSONArray getMember(){
List<HashMap<String,String>> result_dep = reportDao.getDep();
List<MemberForReport> result_member = reportDao.getMemberForReport();
String[] dep_list = new String[result_dep.size()];
for(int i=0; i<result_dep.size(); i++){
dep_list[i] = result_dep.get(i).get("dep");
}
HashMap<String, ArrayList<String>> hash_list = new HashMap<String, ArrayList<String>>();
for(int i=0; i<dep_list.length; i++){
ArrayList<String> member_list = new ArrayList<String>();
for(int j=0; j<result_member.size(); j++){
if(dep_list[i].equals(result_member.get(j).getDep())){
member_list.add(result_member.get(j).getName());
}
}
hash_list.put(dep_list[i], member_list);
}
JSONArray arry = new JSONArray();
List keys = new ArrayList(hash_list.keySet());
for(int i=0; i<keys.size(); i++){
JSONArray arry_child = new JSONArray();
JSONObject json_folder = new JSONObject();
json_folder.put("title", keys.get(i));
json_folder.put("isFolder", true);
for(int j=0; j<hash_list.get(keys.get(i)).size(); j++){
JSONObject json_child = new JSONObject();
json_child.put("title", hash_list.get(keys.get(i)).get(j));
arry_child.put(json_child);
}
json_folder.put("children", arry_child);
arry.put(json_folder);
}
System.out.println("result \n"+arry.toString());
return arry;
}
my jquery code
$.ajax({
url: "/asec/document/report/getMember",
type: "get",
ContentType: "application/json",
success: function(data){
alert(data);
// alert ("dd");
},
error: function(request, status, error){
console.log(request.getAllResponseHeaders());
}
});
Related
Here's my code:
Crashes.TrackError(ex,
new Dictionary<string, string> {
{"RunQuery", "Exception"},
{"sql", s },
{"Device Model", DeviceInfo.Model },
{"Exception", ex.ToString()}
});
Everything works but I find that Appcenter limits the length of the parameters to 125 characters so it's useless for me as I can never see all of the sql or the ex string.
Has anyone found a way to get around this?
I ran into the same problem. My solution was to break my string into groups of 125 character strings and iterate through while logging. I chatted with AppCenter support. They have no way of extending this length currently.
Here is a scrubbed version of my code:
var tokenChunks = LoggingHelper.SplitBy(extremelyLongString, 120);
string title = "Long string here";
var props = new Dictionary<string, string>();
int item = 0;
foreach(string chunk in tokenChunks)
{
string chunkIndex = string.Format("item: {0}", item++);
props.Add(chunkIndex, chunk);
}
Analytics.TrackEvent(title, props);
Where the LoggingHelper class is:
public static class LoggingHelper
{
public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
if (String.IsNullOrEmpty(str)) throw new ArgumentException();
if (chunkLength < 1) throw new ArgumentException();
for (int i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
chunkLength = str.Length - i;
yield return str.Substring(i, chunkLength);
}
}
}
I should give credit to this post https://stackoverflow.com/a/8944374/117995 by #oleksii for the SplitBy method.
I have a Spring Boot web application and I need an example of how to download a file from the server.
Thanks,
R.
I have this running project of SpringBoot. Below is a part of code which outputs xlsx file.
WebController.java
#RequestMapping(value = {"/excel"}, method = RequestMethod.GET)
public void excel(HttpServletResponse response, #RequestParam("email") String email) {
try {
Query query = new Query();
query.addCriteria(Criteria.where("email").is(email));
if(email.equals(""))
query=new Query();
List<MQTT_Server_Detail> list = mongoTemplate.find(query, MQTT_Server_Detail.class, "owner");
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
Workbook workbook = new XSSFWorkbook();
workbook.createSheet("owner");
workbook.setSheetName(0, "Owner");
Sheet sheet = workbook.getSheetAt(0);
sheet.createRow(0);
sheet.getRow(0).createCell(0).setCellValue("Owner Email");
sheet.getRow(0).createCell(1).setCellValue("Topic");
sheet.getRow(0).createCell(2).setCellValue("Device Name");
sheet.getRow(0).createCell(3).setCellValue("Device ID");
Row row;
int num = 1;
for (MQTT_Server_Detail a : list) {
Devices devices = getDevice(a.getEmail());
for (int i = 0; i < devices.getDevicesID().size(); i++) {
row = sheet.createRow(num++);
row.createCell(0).setCellValue(a.getEmail());
row.createCell(1).setCellValue(a.getTopic());
row.createCell(2).setCellValue((String) devices.getDevicesName().get(i));
row.createCell(3).setCellValue((String) devices.getDevicesID().get(i));
}
}
sheet = workbook.createSheet("Users");
row = sheet.createRow(0);
row.createCell(0).setCellValue("Name");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("CardID");
row.createCell(3).setCellValue("Email");
row.createCell(4).setCellValue("Mobile");
row.createCell(5).setCellValue("Blocked");
row.createCell(6).setCellValue("Last in Date");
row.createCell(7).setCellValue("Last in Time");
row.createCell(8).setCellValue("Last out Date");
row.createCell(9).setCellValue("Last out Time");
row.createCell(10).setCellValue("Owner");
Criteria criteria[] = new Criteria[list.size()];
for (int i = 0; i < list.size(); i++) {
criteria[i] = Criteria.where("owner").is(list.get(i).getEmail());
}
List<Users_POJO> users_pojoList;
if (list.size() == 0)
users_pojoList = new ArrayList<>();
else
users_pojoList = mongoTemplate.find(new Query().addCriteria(new Criteria().orOperator(criteria)),
Users_POJO.class, "users");
for (int i = 0; i < users_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(users_pojoList.get(i).getName());
row.createCell(1).setCellValue(users_pojoList.get(i).getDevice());
row.createCell(2).setCellValue(users_pojoList.get(i).getCard_id());
row.createCell(3).setCellValue(users_pojoList.get(i).getEmail());
row.createCell(4).setCellValue(users_pojoList.get(i).getMobile());
row.createCell(5).setCellValue(users_pojoList.get(i).getBlocked());
row.createCell(6).setCellValue(users_pojoList.get(i).getLast_in_date());
row.createCell(7).setCellValue(users_pojoList.get(i).getLast_in_time());
row.createCell(8).setCellValue(users_pojoList.get(i).getLast_out_date());
row.createCell(9).setCellValue(users_pojoList.get(i).getLast_out_time());
row.createCell(10).setCellValue(users_pojoList.get(i).getOwner());
}
sheet = workbook.createSheet("Logs");
row = sheet.createRow(0);
row.createCell(0).setCellValue("CardID");
row.createCell(1).setCellValue("Device");
row.createCell(2).setCellValue("Date");
row.createCell(3).setCellValue("Time");
row.createCell(4).setCellValue("Count");
criteria = new Criteria[users_pojoList.size()];
for (int i = 0; i < users_pojoList.size(); i++) {
criteria[i] = Criteria.where("card_id").is(users_pojoList.get(i).getCard_id());
}
query = new Query();
query.addCriteria(new Criteria().orOperator(criteria));
List<Log_POJO> log_pojoList;
if (users_pojoList.size() == 0)
log_pojoList = new ArrayList<>();
else
log_pojoList = mongoTemplate.find(query, Log_POJO.class, "logs");
for (int i = 0; i < log_pojoList.size(); i++) {
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(log_pojoList.get(i).getCard_id());
row.createCell(1).setCellValue(log_pojoList.get(i).getDevice());
String date = log_pojoList.get(i).getDay() + "-" + log_pojoList.get(i).getMonth() + "-" + log_pojoList.get(i).getYear();
row.createCell(2).setCellValue(date);
String time = log_pojoList.get(i).getHour() + "-" + log_pojoList.get(i).getMin() + "-" + log_pojoList.get(i).getSec();
row.createCell(3).setCellValue(time);
row.createCell(4).setCellValue(log_pojoList.get(i).getSerial_no());
}
workbook.write(response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
}
}
In short, you have to do this:
response.addHeader("Content-disposition", "attachment; filename=Door.xlsx");
response.setContentType("application/vnd.ms-excel");
//get the outputstream of response and write data to it
Spring Boot download file from server
#Controller
#RequestMapping(value = "/")
public class HomeController {
#RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"webpage.html\"");
InputStream inputStream = new FileInputStream(new File("C:\\MyWebPage\\webpage.html"));
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};
}
}
i have a doubt that how to split json data into strings.My intention is iam creating several textboxes dynamically and posting them using ajax post,to avoid full postback,here check my ajax part
function profileAndSectin_Submit() {
//alert('test123');
document.getElementById("hiddenSection").value = i;
$('#profile_form').submit(
function() {
alert(i);
var profileName = $('#profileName').val();
var Section1 = $('#Section1').val();
var dynamicData = " ";
for ( var m = 2; m <= i; m++) {
var textbx = $('#Section' + m).val();//"Section"+m;
var dt="section"+m+":"+textbx;
//var txtbxval = document.getElementsByName(textbx).value;
var x = textbx ;
if (m <= m - 1) {
x + " ";
}
dynamicData = dynamicData +dt+",";
//dynamicData = dynamicData +":"+dt+",";
}
alert(dynamicData);
var Data = "profileName :"+profileName+","+"Section1 :"+Section1+"," + dynamicData;
alert(Data);
$.ajax({
type : "post",
url : "addProfile",
//data : {
//"profileName" : profileName,
//"Section1" : Section1,
//},
data :{"Count" : i,"Data" :Data},
success : function(msg) {
alert(i);
$('#divContent').load('addfields.jsp');
},
Error : function(msg) {
debugger;
}
});
return false;
});
};
and iam sending these values to one controller ,the main problem comes into picture here,how can i retrive these data,if iam using #RequestParam("Data") String data then iam getting the total data as a single string,like
{ProfileName:profileName,Section1:section1,Section2:section2...}
but i want each string like profileName ,Section2 and Section3 like that i want.
Controller.java
#Controller
public class SettingController implements HibernateConfig {
#RequestMapping(value = "/addProfile", method = RequestMethod.POST)
//public String home(HttpServletRequest request,#RequestParam("Count") int i,#RequestParam("profileName") String pname,#RequestParam("Section1") String Section1,Locale locale, Model model) throws IOException
public String home(HttpServletRequest request,#RequestParam("Count") int i,#RequestParam("Data") String data,Locale locale, Model model) throws IOException
{
System.out.println(i);
System.out.println(data);
}
so any idea guys?
Use a JSON API/marshaller in Java to transform the JSON string back into a Java object. There are dozens of such JSON APIs: Look at http://www.json.org/ for a list of Java JSON APIs.
In this particular case, a quick option would be to call in your controller data.split(","). You will obtain a String[] with separated values.
In your example the resulting Array will be: {"ProfileName:profileName", "Section1:section1", "Section2:section2", ...}.
Afterwards, you can iterate over it and process it as you want.
I am making a request to a service and getting a response. Service works fine and I am deserializing an object without a problem.
Below is an example of my code. The problem is the result object is null at the end. I do not know why am I losing a reference. What is the proper solution?
HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create("http://service.svc/Login");
hwrq.ContentType = "application/x-www-form-urlencoded; encoding='utf-8'";
hwrq.Accept = "text/xml";
hwrq.Method = "POST";
Users result = null; // object initializaiton
hwrq.BeginGetRequestStream(ar =>
{
var requestStream = hwrq.EndGetRequestStream(ar);
using (var sw = new StreamWriter(requestStream, System.Text.Encoding.UTF8))
{
sw.Write("Username Password");
sw.Close();
}
hwrq.BeginGetResponse(a =>
{
var response = hwrq.EndGetResponse(a);
var responseStream = response.GetResponseStream();
using (var sr = new StreamReader(responseStream))
{
returnedXML = sr.ReadToEnd();
XmlSerializer xds = new XmlSerializer(typeof(Users));
byte[] byteArray = Encoding.UTF8.GetBytes(returnedXML);
MemoryStream stream = new MemoryStream(byteArray);
result = (Users)xds.Deserialize(stream); // object is correct
}
responseStream.Close();
response.Close();
}, null);
}, null);
return result; // object is null!
Just like MarcinJuraszek suggested, the proper way is to make a callback and handle the results there.
I have create web services using Web Api in mvc3,in this i want get the data from json. Json Result like this
{"order": {
"locationid": "1",
"deviceidentifier": "XXXXXXXXXXXXXXXXXXXXXXX",
"ordercontactname": "XXXXXXXXXXXXXXXXXXXXXXX",
"ordercontactphone": "XXXXXXXXXXXXXXXXXXXXXXX",
"ordercontactemail": "XXXXXXXXXXXXXXXXXXXXXXX",
"shipaddress1": "17 Brookfield",
"shipaddress2": "Suite 17",
"shipcity": "Irvine",
"shipstate": "CA",
"shipzipcode": "92604",
"shipphonenumber": "9493742114",
"shipemail": "Info#mail.com",
"shipmethod": "pickup",
"billingfirstname":"Tester",
"billinglastname":"test",
"billingmiddleinitial":"S",
"billingaddress":"field",
"billingcity":"Sample",
"billingstate":"SM",
"billingzipcode":"523201",
"billingphonenumber": "1234567891",
"billingemail": "",
"paytype":"creditcard",
"amount"="10.50",
"acctno"="123456789987",
"exproute"="0114",
"coupon"="X2323",
"notes"="",
"items": [
{"itemid":"1","quantity":"1","price":"2.5","notes":"make it spicy"},
{"itemid":"4","quantity":"2","price":"4.5","notes":""},
{"itemid":"3","quantity":"1","price":"1.5","notes":""}
]
}}
for this i have create Poco class and i get Order data using poco class, but i can't get the items array data how can i get items data
Here is my code
public List<Message> PlaceOrder(PlaceOrder order)
{
// List<PlaceOrder> entities = (List<PlaceOrder>)JavaScriptConvert.DeserializeObject(json, typeof(List<PlaceOrder>));
int PayOrderID = 0;
List<Message> Result;
Result = new List<Message>();
try
{
Order objOrder = new Order();
PayHist objPayhis = new PayHist();
objOrder.LocationId = order.LocationId;
objOrder.DeviceIdentifier = order.DeviceIdentifier;
objOrder.OrderContactName = order.OrderContactName;
objOrder.OrderContactPhone = order.OrderContactPhone;
objOrder.OrderContactEmail = order.OrderContactEmail;
string guid = Guid.NewGuid().ToString();
objOrder.ShipMethod = order.ShipMethod;
objOrder.ShippingDate = Convert.ToDateTime(order.PickupDate);
objOrder.OrderGuid = guid;
entities.AddObject("Orders", objOrder);
entities.SaveChanges();
int orderId = objOrder.OrderId;
PayOrderID = orderId;
objPayhis.OrderId = orderId;
objPayhis.PayType = order.ShipMethod;
objPayhis.Amount = float.Parse(order.Amount);
entities.AddObject("PayHists", objPayhis);
entities.SaveChanges();
JavaScriptSerializer ser = new JavaScriptSerializer();
// Order foo = ser.Deserialize<Order>(json);
Message objMessage = new Message();
objMessage.Messagevalue = "Sucess";
Result.Add(objMessage);
return Result;
}
Please help me..
Try this (you need to fix your Json by replacing the "=" signs by ":" signs" before):
[WebInvoke(Method = "POST", UriTemplate = "")]
public HttpResponseMessage Add(JsonValue json) {
JsonValue order = json["order"];
JsonArray items = (JsonArray) order["items"];
JsonValue item1 = items[0];
var notes1 = item1["notes"];
return new HttpResponseMessage(HttpStatusCode.OK);
}