Access response data of ajax's success call back function - java

I returned a list<object> from my controller,it successfully captured in ajax's success(), as it is list so it can have n-number of objects, I want to create tabular data dynamically and populated the same by iterating data, but I am not able to access the elements inside data object, as console data shows, the actual elements are wrapped inside an outer object and my for loop outer one. please see the screenshot attached
Please refer to this link for image reference: Console log
Ajax call of the controller:
function getSelectedTableRecords(tableId) {
if (tableId != null && tableId != '') {
$.ajax({
type: "POST",
url: baseUrl + "search",
data: {
tableId: tableId
},
success: function (data) {
for (var i = 0; i < data.length; i++) {
var item = data[i];
$('#applicationList > tbody').append(
'<tr>'
+ '<td><h4>' + item.userId + '</h4></td>'
+ '<td><h4>' + item.firstName + '</h4></td>'
+ '<td><h4>' + item.lastName + '</h4></td>'
+ '<td><h4>' + item.rollNo + '</h4></td>'
+ '<td><h4>' + item.contact + '</h4></td>'
+ '<td><h4>' + item.email + '</h4></td>'
+ '<td><h4>' + item.gender + '</h4></td>'
+ '</tr>');
insideData(data);
}
},
fail: function (data) {
alert('Failed to fetch records.');
}
});
} else {
// ...
}
}
My Controller code:
#RequestMapping(value = "/search", method = RequestMethod.POST)
#ResponseBody
public List<Object> fetchTableData(#RequestParam("tableId") String tableId) {
List<Object> userList = new ArrayList<>();
try {
System.out.println(" table id id " + tableId);
if (tableId != null) {
List<UserInfo> l = userInfoDao.findById(tableId);
userList.add(l);
}
return userList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
As per screenshot, I only got one row with all undefined values, what I want to do, in the image I have 7 elements, so I want to iterate and I want seven rows and their corresponding columns populated with values. Please suggest me the solution.

Well, as far as I see from your log, the structure is an array of array. An element might be accessible using:
success: function (data) {
for (var i = 0; i < data[0].length; i++) { // access the first item data[0] of outer array
var item = data[0][i]; // and get the nth object
$('#applicationList > tbody').append(
// code skipped
);
insideData(data);
}
},
Why does it happen?
Because you return List<Object> which has one element List<UserInfo>. This brief sequence of operation adds a list to a list and returns it:
List<Object> userList = new ArrayList<>(); // Creates a List
List<UserInfo> l = userInfoDao.findById(tableId); // Creates another of users
userList.add(l); // Adds List to List
return userList; // Returns the List to List
Since the return type is List<Object>, you might not notice that the returned type is actually List<List<UserInfo>>.
How to fix it?
There are two ways, yet I recommend you the second one:
I suppose that you wanted to add all the elements to the outer List and keep the flat structure. For this, you have to use method List::addAll which passes all the elements from the List to another one. You have used List::add which adds an element to the list as is - in your case the added element was a new entire List and not its elements.
A better way is to return the result directly. If nothing is found, return an empty List:
#RequestMapping(value = "/search", method = RequestMethod.GET)
#ResponseBody
public List<UserInfo> fetchTableData(#RequestParam("tableId") String tableId) {
try {
List<UserInfo> userList = new ArrayList<>();
System.out.println(" table id id " + tableId);
if (tableId != null) {
userList = userInfoDao.findById(tableId);
}
return userList;
} catch (Exception e) {
// log it, don't print the stacktrace...
return Collections.emptyList()
}
}
What more?
I noticed you use the POST method, however since you receive data from the server, you should use GET method regardless you pass a parameter which identifies the entity to be returned. From W3Schools:
GET is used to request data from a specified resource.
POST is used to send data to a server to create/update a resource.

Related

java mail - how to retrieve the last replied mail of a sender

I'm trying to retrieve the latest mail received in my mail box from one sender. I have an issue when a sender reply on one of his emails, for example:
screenshot of my exemple
I want to get the last message received on 04/28 instead of getting the two messages.
In my code, I simply did this to get my messages:
defaultFolder = store.getDefaultFolder().getFolder("inbox");
Message [] msg = defaultFolder.getMessages();
Any ideas of how we can get only the latest email of the same sender ?
Thank you!
To get the latest recieved email from the folder you can Sort items by using the Items.Sort method, here is a VBA sample (the Outlook object model is common for all kind of applications):
Sub SortByDueDate()
Dim myNameSpace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myItem As Outlook.TaskItem
Dim myItems As Outlook.Items
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myFolder.Items
myItems.Sort "[ReceivedTime]", False
For Each myItem In myItems
MsgBox myItem.Subject & "-- " & myItem.DueDate
Next myItem
End Sub
So, the first item will be the latest received. As soon as you got the latest item you can iterate over all items in the same conversation. The MailItem.GetConversation method obtains a Conversation object that represents the conversation to which this item belongs. So, you may get all items from the conversation. Read more about that in the Obtain and Enumerate Selected Conversations article. For example:
void DemoConversation()
{
object selectedItem =
Application.ActiveExplorer().Selection[1];
// This example uses only
// MailItem. Other item types such as
// MeetingItem and PostItem can participate
// in the conversation.
if (selectedItem is Outlook.MailItem)
{
// Cast selectedItem to MailItem.
Outlook.MailItem mailItem =
selectedItem as Outlook.MailItem;
// Determine the store of the mail item.
Outlook.Folder folder = mailItem.Parent
as Outlook.Folder;
Outlook.Store store = folder.Store;
if (store.IsConversationEnabled == true)
{
// Obtain a Conversation object.
Outlook.Conversation conv =
mailItem.GetConversation();
// Check for null Conversation.
if (conv != null)
{
// Obtain Table that contains rows
// for each item in the conversation.
Outlook.Table table = conv.GetTable();
Debug.WriteLine("Conversation Items Count: " +
table.GetRowCount().ToString());
Debug.WriteLine("Conversation Items from Table:");
while (!table.EndOfTable)
{
Outlook.Row nextRow = table.GetNextRow();
Debug.WriteLine(nextRow["Subject"]
+ " Modified: "
+ nextRow["LastModificationTime"]);
}
Debug.WriteLine("Conversation Items from Root:");
// Obtain root items and enumerate the conversation.
Outlook.SimpleItems simpleItems
= conv.GetRootItems();
foreach (object item in simpleItems)
{
// In this example, only enumerate MailItem type.
// Other types such as PostItem or MeetingItem
// can appear in the conversation.
if (item is Outlook.MailItem)
{
Outlook.MailItem mail = item
as Outlook.MailItem;
Outlook.Folder inFolder =
mail.Parent as Outlook.Folder;
string msg = mail.Subject
+ " in folder " + inFolder.Name;
Debug.WriteLine(msg);
}
// Call EnumerateConversation
// to access child nodes of root items.
EnumerateConversation(item, conv);
}
}
}
}
}
void EnumerateConversation(object item,
Outlook.Conversation conversation)
{
Outlook.SimpleItems items =
conversation.GetChildren(item);
if (items.Count > 0)
{
foreach (object myItem in items)
{
// In this example, only enumerate MailItem type.
// Other types such as PostItem or MeetingItem
// can appear in the conversation.
if (myItem is Outlook.MailItem)
{
Outlook.MailItem mailItem =
myItem as Outlook.MailItem;
Outlook.Folder inFolder =
mailItem.Parent as Outlook.Folder;
string msg = mailItem.Subject
+ " in folder " + inFolder.Name;
Debug.WriteLine(msg);
}
// Continue recursion.
EnumerateConversation(myItem, conversation);
}
}
}

NotesException: A required argument has not been provided

My XPage gathers information which I use to populate a document in a different Domino database. I use a link button (so I can open another XPage after submission). The onClick code is as follows:
var rtn = true
var util = new utilities()
var hostURL = configBean.getValue("HostURL");
var userAttachment;
//set up info needed for checking duplicates
var attachName=getComponent("attachmentIdentifier").getValue();
var serialNbr = getComponent("serialNumber").getValue();
userAttachment = user+"~"+attachName;
var userSerial = user+"~"+serialNbr;
//Done setting info needed
//check for duplicates
rtn = utilBean.checkAttachmentName(userAttachment, userSerial)
//done
if(rtn==true){
var doc:Document = document1;
dBar.info("ALL IS GOOD");
var noteID:String=document1.getNoteID();
dBar.info("Calling saveNewAttachment using NoteID " + noteID )
rtn=utilBean.saveNewAttachment(session,noteID ); //<<< I get error here
dBar.info("rtn = " + rtn)
return "xsp-success";
view.postScript("window.open('"+sessionScope.nextURL+"')")
}else if (rtn==false){
errMsgArray = utilBean.getErrorMessages();
for(err in errMsgArray){
//for (i=0; i < errMsgArray.size(); i++){
dBar.info("err: "+ err.toString());
if (err== "nameUsed"){
//send message to XPXage
facesContext.addMessage(attachmentIdentifier.getClientId(facesContext) , msg(langBean.getValue("duplicateName")));
}
if(err=="serialUsed"){
//send message to XPXage
facesContext.addMessage(serialNumber.getClientId(facesContext) , msg(langBean.getValue("duplicateSerial")));
}
}
return "xsp-failure";
}
And the java code that delivers the error is this
public boolean saveNewAttachment(Session ses, String noteID)
throws NotesException {
debugMsg("Entering saveNewAttachment and NOTEID = "+noteID);
// this is used when the user saves an attachment to to the
// user profiles db
boolean rtn = false;
Document doc;
ConfigBean configBean = (ConfigBean)
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(),
"configBean");
String dbName = (String) configBean.getValue("WebsiteDbPath");
debugMsg("A");
Database thisDB = ses.getDatabase(ses.getServerName(), dbName, false);
String value;
try {
debugMsg("noteID: "+noteID);
The next line throws the NotesException error
doc = thisDB.getDocumentByID("noteID");
debugMsg("C");
} catch (Exception e) {
debugMsg("utilitiesBean.saveAttachment: " + e.toString());
e.printStackTrace();
System.out.println("utilitiesBean.saveAttachment: " + e.toString());
throw new RuntimeException("utilitiesBean.saveAttachment: "
+ e.toString());
}
return rtn;
}
I might be going about this wrong. I want to save the document which the data is bound to the User Profile database but if I submit it I need to redirect it to a different page. That is why I am using a link, however, I am having a hard time trying to get the document saved.
Has document1 been saved before this code is called? If not, it's not in the backend database to retrieve via getDocumentByID().
I'm assuming this line has been copied into here incorrectly, because "noteID" is not a NoteID or a variable holding a NoteID, it's a string.
doc = thisDB.getDocumentByID("noteID");

How to get value from jquery each loop when controller returns list

I have list and return from controller and i'm trying to show in a mvc view using jquery each loop function.I can get to list and send to view but when jquery loop start i cannot get index and value.I checked Console and Sources,values are there.
This is my controller codes
public JsonResult electric()
{
int id = Convert.ToInt32(Session["id"]);
string cs = "data source=LNPC;initial catalog=db;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework";
SqlConnection connection = new SqlConnection(cs);
SqlCommand command = new SqlCommand("electrcic_bills", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<analiz> TestList = new List<analiz>();
analiz electric;
while (reader.Read())
{
electric= new analiz();
electric.jan= Convert.ToDouble(reader["jan"].ToString());
electric.feb= Convert.ToDouble(reader["feb"].ToString());
electric.march= Convert.ToDouble(reader["march"].ToString());
electric.april = Convert.ToDouble(reader["april"].ToString());
TestList.Add(electric);
}
return Json(new { List = TestList }, JsonRequestBehavior.AllowGet);
}
Jquery codes
$("#electric").click(function () {
$("canvas#myCharts").remove();
$("#canvas1").append('<canvas id="myCharts" width="200" height="200"></canvas>');
$.ajax({
type: "GET",
url: "/MainController/electric",
dataType: "json",
success: function (List) {
var data = List.List;
$.each(data, function (index, value) {
alert(data);
});
},
});
});
With this method i cannot get value but when i write electric.push(List.List[0].jan._bills_electric) like this i can get value manualy perfctly.
This my Source codes from browser
Local List:List: Array(1)
0:
jan_bills: null
jan_bills_electric: 135
dec_bills: null
dec_bills_electric: 60
You are using List word in your return Json() statement. This may be ambiguous for Java.
Try using another name with camel case typography to solve the problem.
In your Javascript, try to use
var data = List["List"];
instead of
var data = List.List;
Okey i found my answer and where l am wrong.
First- there is nothing wrong in my controller
Second- in each loop function,my array not only array,it is array in OBJECT.I've found this link and try each loop in a each loop and i got my items from jquery loop.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});

Multithreading issues for database insertion

I have a piece of JAVA code that is accessed by multiple threads.
synchronized (this.getClass())
{
System.out.println("stsrt");
certRequest.setRequestNbr(
generateRequestNumber(
certInsuranceRequestAddRq.getAccountInfo().getAccountNumberId()));
System.out.println("outside funcvtion"+certRequest.getRequestNbr());
reqId = Utils.getUniqueId();
certRequest.setRequestId(reqId);
System.out.println(reqId);
ItemIdInfo itemIdInfo = new ItemIdInfo();
itemIdInfo.setInsurerId(certRequest.getRequestId());
certRequest.setItemIdInfo(itemIdInfo);
dao.insert(certRequest);
addAccountRel();
System.out.println("end");
}
the function generateRequestNumber() generates a request number based on the data fetched from two database tables.
public String generateRequestNumber(String accNumber) throws Exception
{
String requestNumber = null;
if (accNumber != null)
{
String SQL_QUERY = "select CERTREQUEST.requestNbr from CertRequest as CERTREQUEST, "
+ "CertActObjRel as certActObjRel where certActObjRel.certificateObjkeyId=CERTREQUEST.requestId "
+ " and certActObjRel.certObjTypeCd=:certObjTypeCd "
+ " and certActObjRel.certAccountId=:accNumber ";
String[] parameterNames = { "certObjTypeCd", "accNumber" };
Object[] parameterVaues = new Object[]
{
Constants.REQUEST_RELATION_CODE, accNumber
};
List<?> resultSet = dao.executeNamedQuery(SQL_QUERY,
parameterNames, parameterVaues);
// List<?> resultSet = dao.retrieveTableData(SQL_QUERY);
if (resultSet != null && resultSet.size() > 0) {
requestNumber = (String) resultSet.get(0);
}
int maxRequestNumber = -1;
if (requestNumber != null && requestNumber.length() > 0) {
maxRequestNumber = maxValue(resultSet.toArray());
requestNumber = Integer.toString(maxRequestNumber + 1);
} else {
requestNumber = Integer.toString(1);
}
System.out.println("inside function request number"+requestNumber);
return requestNumber;
}
return null;
}
The tables CertRequest and CertActObjRel used in generateRequestNumber() are updated by the functions "dao.insert(certRequest);" and "addAccountRel();" used in my initial code respectively. Also the System.out.println() statements used in my initial code have following output.
stsrt
inside function request number73
outside funcvtion73
A1664886-5F84-45A9-AB5F-C69768B83EAD
end
stsrt
inside function request number73
outside funcvtion73
44DAD872-6A1D-4524-8A32-15741FAC0CA9
end
If you notice both the threads run in a synchronized manner, but when the request number is generated , it's the same. My assumption is the database updation for CertRequest and CertActObjRel is done when both the threads finish their execution.
Could anyone help me to fix this?

Why are there multiple calls to my function when it has been called only once during iteration?

I am working on an Android application which uses Xerces for Iteration. I have a custom method which is called to store a filtered set of data values in it after being iterated through via a while loop. Part of the specific while loop is as follows:
while((n = iterator.nextNode())!= null) {
... //other code
object.customMethod(tagName, n.getNodeValue()); //occurs only once per iteration
Log.i("TAG", tagName + ": " + n.getNodeValue())
...//other code
}
The customMethod received a key and value pair and saves them as Strings using Android's SharedPreferences system. At the moment of being called, the method actually has the key=>value pair, but it appears the method is being called more than once during the same iteration loop. I came to know this after printing out the logcat sample showing the output after each call within customMethod due to having blanks/nulls saved in the preferences when I fetched them later. Why is this happening? A sample output is as shown:
TAG inserted: 500.00 //log call right after insertion within customMethod()
TAG vc:limit: 500.00 //log call after returning from customMethod()
TAG inserted:
TAG inserted:
TAG inserted: //other calls, which I want to know how and why they are occurring
All the above occurred during a single iteration of the while loop. Anyone know why this is happening? Something else, it seems the code right after the insertion only runs once, but only the code within the customMethod() gets called several times during the iteration. The custom method is as shown below:
public boolean customMethod(String key, String val) {
boolean inserted = prefs.edit().putString(key, val).commit(); //prefs is global
Log.i("TAG", (inserted == true ? "inserted: " + val : "not inserted"));
return inserted;
}
Edit: The full while loop as requested:
private void setSelectedID(int pos)
{
...
String id = IDs[pos];
...
NodeList descElements = MainActivity.root.getElementsByTagName(VCard.DIRECTORY); //DIRECTORY is a String constant
Element desc = (Element) descElements.item(0);
NodeIterator iterator = ((DocumentTraversal)MainActivity.doc).createNodeIterator(desc, NodeFilter.SHOW_ALL, null, true);
Node n;
VCard object = new VCard(this);
while((n = iterator.nextNode())!= null)
{
if(n.getNodeType() == Node.CDATA_SECTION_NODE || n.getNodeType() == Node.TEXT_NODE)
{
String tagName = n.getParentNode().getNodeName();
if(object.containsKey(tagName))
{
Element e = (Element) n.getParentNode();
if(e.hasAttribute("id") && e.getAttribute("id").equals(id))
{
object.customMethod(tagName, n.getNodeValue());
Log.i("TAG", tagName + ": " + n.getNodeValue())
}
}
}
}
}

Categories