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);
}
}
}
Related
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.
I'm using Milo and its example server and client. I'm adding nodes to the server but I can't figure out how to add EuInformation, i.e., unit and description. I thought about using the ExtensionObject but since EuInformation does not implement Serializable I don't know how to pass it to the ExtensionObject. I'd also like to know how I can get the namespace ID and URI on client side. So far I just set them statically as I have access to the classes.
I've implemeted the AddNodes on server side. I can add nodes, read nodes and write to nodes.
Here's what I'm doing on client side:
// Should somehow get the namespace ID and namespace dynamically.
// Maybe by iterating through all nodes??
ExpandedNodeId parentNodeId = new ExpandedNodeId(
new nodeId(2,DatatypeNamespace.NODE_IDENTIFIER),
datatypeNamespace.NAMESPACE_URI, 0);
NodeId referenceTypeId = Identifiers.String;
// Define the new node.
ExpandedNodeId requestedNewNodeId = new ExpandedNodeId(new NodeId(2, "NewNode"),
DatatypeNamespace.NAMESPACE_URI, 0);
QualifiedName browseName = new QualifiedName(2, "NewNode");
// How to get this to the server??
EUInformation euinfo = new EUInformation(null,-1,LocalizedText.english("MyUnit"),
LocalizedText.english("My Description"));
ExpandedNodeId typeDef = new ExpandedNodeId(Identifiers.BaseVariableType,
DatatypeNamespace.NAMESPACE_URI, 0);
AddNodesItem newItem = new AddNodesItem(parentNodeId, referenceTypeId,
requestedNewNodeId,rowseName,NodeClass.VariableType, null, typeDef);
List<AddNodesItem> items = new ArrayList<AddNodesItem>();
items.add(newItem);
client.addNodes(items).get();
EDIT
With the help of Kevin Herron's answer I worked something out: I adjusted the write() in my namespace class. I can now modify the display name and description of the node with the values of the EUInformation. Here's my write() method:
#Override
public void write(WriteContext context, List<WriteValue> writeValues) {
List<StatusCode> results = Lists.newArrayListWithCapacity(writeValues.size());
for (WriteValue writeValue : writeValues) {
ServerNode node = server.getNodeMap().get(writeValue.getNodeId());
if (node != null) {
// Get the type of the variant thats about to be written to the node
NodeId variantType = writeValue.getValue().getValue().getDataType().get();
if (variantType.equals(Identifiers.Structure)) {
ExtensionObject o = (ExtensionObject) writeValue.getValue().getValue().getValue();
if (o.getEncodingTypeId().equals(Identifiers.EUInformation_Encoding_DefaultBinary)) {
EUInformation euInformation = (EUInformation) o.decode();
node.setDescription(euInformation.getDescription());
node.setDisplayName(euInformation.getDisplayName());
System.out.println("Wrote EUInformation " + euInformation);
results.add(StatusCode.GOOD);
context.complete(results);
return;
}
}
try {
node.writeAttribute(new AttributeContext(context), writeValue.getAttributeId(),
writeValue.getValue(), writeValue.getIndexRange());
results.add(StatusCode.GOOD);
System.out.println(String.format("Wrote value %s to %s attribute of %s",
writeValue.getValue().getValue(),
AttributeId.from(writeValue.getAttributeId()).map(Object::toString).orElse("unknown"),
node.getNodeId()));
} catch (UaException e) {
System.out.println(String.format("Unable to write %s", writeValue.getValue()));
results.add(e.getStatusCode());
}
} else {
results.add(new StatusCode(StatusCodes.Bad_NodeIdUnknown));
}
}
context.complete(results);
}
Ok, so you would add a new VaribleNode with a TypeDefinition of Property (Identifiers.PropertyType).
Then you would write to its Value attribute so it contains the EUInformation object:
EUInformation euInformation = ...
Variant v = new Variant(ExtensionObject.encode(euInformation));
...write the value to the node you created...
Okay, I've looked at quite a few stack overflow questions and quite a few blogs, and still cannot find the answer to this. No, it doesn't look like it is missing braces, has extra semicolons, or any other typo that I am aware of. Why is the 'else' showing an error?
// check if myid property is set and create it if not
String subtopicMyId = subtopicNode.hasProperty("myid") ? subtopicNode.getProperty("myid").getString() : "";
if (subtopicMyId.equals("")) {
// generate new myid and check it against the list of existing IDs until a unique one is generated
do {
// generate new myid
Object topicmyidobj = new Object();
subtopicMyId = topicmyidobj.toString().split("#")[1].toUpperCase();
} while ( subtopicMyId.equals("") || existingMyIds.contains(subtopicMyId) );
// set myid on this node
subtopicNode.setProperty("myid", subtopicMyId);
subtopicNode.setProperty("parentid", topicMyId);
subtopicNode.save();
// add new myid to list of existsing IDs so that it doesn't get reused
existingMyIds.add(subtopicMyId);
} else {
// if subtopic has myid already
// compare the parentid to the parent myid
String subtopicParentId = subtopicNode.getProperty("parentid").getString();
if (!subtopicParentId.equals(topicMyId)) {
// they don't match
String subtopicNodePath = subtopicNode.getPath();
String topicNodePath = topicNode.getPath();
// find path to topic node that has matching myid to this subtopic's parentid
// loop through parent nodes
NodeIterator reorgTopicsIter = compNode.getNodes();
while (reorgTopicsIter.hasNext()) {
// loop through parent objects to find a matching myid for parentid
Node reorgTopicNode = (Node)reorgTopicsIter.next();
// get the myid property from this node, if it exists, and compare the parentid to it
String reorgTopicMyId = reorgTopicNode.hasProperty("myid") ? reorgTopicNode.getProperty("myid").getString() : "";
if (!reorgTopicMyId.equals("")) {
// parent myid exists and is not blank
if (reorgTopicMyId.equals(subtopicParentId)) {
// parentid does match parent myid
String reorgTopicNodePath = reorgTopicNode.getPath();
// determine how many parent objects there are
int reorgTopicSubtopics = 0;
NodeIterator reorgSubtopicsIter = reorgTopicNode.getNodes();
while (reorgSubtopicsIter.hasNext()) {
Node reorgSubtopicNode = (Node)reorgSubtopicsIter.next();
reorgTopicSubtopics++;
}
// set source to this child object
String source = subtopicNode.getPath();
// set destination to matching parent object with new child object appended
String destination = reorgTopicNodePath + "/subtopic-" + (reorgTopicSubtopics + 1);
// create session for move and perform move
Session session = resourceResolver.adaptTo(Session.class);
session.move(source, destination);
session.save();
} else {
// parentid does not match parent myid.
// nothing we need to do here;
// it just moves on to check next parent myid.
}
} else {
// parent myid does not exist or is blank
}
} else {
// no more parent objects to loop through, so we need to check if a match was found
// if no match was found, then parent was deleted or no longer exists, so we need to remove this child
}
} else {
// parentid does match parent myid
}
}
Here is the error in the console:
An error occurred at line: 145 in the jsp file: /apps/covidien/components/content/utilities/faq-node-process/faq-node-process.jsp
Syntax error on token "else", delete this token
142: subtopicNode.save();
143: // add new myid to list of existsing IDs so that it doesn't get reused
144: existingMyIds.add(subtopicMyId);
145: } else {
146: // if subtopic has myid already
147: // compare the parentid to the parent myid
148: String subtopicParentId = subtopicNode.getProperty("parentid").getString();
the number of if and else statement is not same. you have 4 if blocks but 5 else block.
five else with four if, not match.
At least number of if should more than else.
else can't be used after while. There's nothing in that else block anyway, so it should just be deleted.
There's a lot of redundant code here. My rewrite:
// check if myid property is set and create it if not
String subtopicMyId = subtopicNode.getProperty("myid").getString();
if (subtopicMyId == null) {
// generate new myid and check it against the list of existing IDs until a unique one is generated
do {
// generate new myid
Object topicmyidobj = new Object();
subtopicMyId = topicmyidobj.toString().split("#")[1].toUpperCase();
} while ( subtopicMyId.equals("") || existingMyIds.contains(subtopicMyId) );
// set myid on this node
subtopicNode.setProperty("myid", subtopicMyId);
subtopicNode.setProperty("parentid", topicMyId);
subtopicNode.save();
// add new myid to list of existsing IDs so that it doesn't get reused
existingMyIds.add(subtopicMyId);
} else {
// if subtopic has myid already
// compare the parentid to the parent myid
String subtopicParentId = subtopicNode.getProperty("parentid").getString();
if (!subtopicParentId.equals(topicMyId)) {
// they don't match
String subtopicNodePath = subtopicNode.getPath();
String topicNodePath = topicNode.getPath();
// find path to topic node that has matching myid to this subtopic's parentid
// loop through parent nodes
NodeIterator reorgTopicsIter = compNode.getNodes();
while (reorgTopicsIter.hasNext()) {
// loop through parent objects to find a matching myid for parentid
Node reorgTopicNode = (Node)reorgTopicsIter.next();
// get the myid property from this node, if it exists, and compare the parentid to it
String reorgTopicMyId = reorgTopicNode.getProperty("myid").getString();
if (reorgTopicMyId != null && reorgTopicMyId.equals(subtopicParentId)) {
// parentid does match parent myid
String reorgTopicNodePath = reorgTopicNode.getPath();
// determine how many parent objects there are
int reorgTopicSubtopics = 0;
NodeIterator reorgSubtopicsIter = reorgTopicNode.getNodes();
while (reorgSubtopicsIter.hasNext()) {
Node reorgSubtopicNode = (Node)reorgSubtopicsIter.next();
reorgTopicSubtopics++;
}
// set source to this child object
String source = subtopicNode.getPath();
// set destination to matching parent object with new child object appended
String destination = reorgTopicNodePath + "/subtopic-" + (reorgTopicSubtopics + 1);
// create session for move and perform move
Session session = resourceResolver.adaptTo(Session.class);
session.move(source, destination);
session.save();
} else {
// parentid does not match parent myid.
// nothing we need to do here;
// it just moves on to check next parent myid.
}
}
} else {
// parentid does match parent myid
}
}
I'm working on gridsim project in Java eclipse. I have found a network flow program, which works only for one-to-one connection between the sender and receiver. If the same user (sender) wish to send a message to any other receiver, the program does not work. Similarly, if a receiver wish to send message to two sender users, it does not work. Here, I'm including all the java files for this work. In order to run the program, we need to include external .jar file path in the project. The gridsim.jar and simjava2.jar files can be downloaded from http://sourceforge.net/projects/gridsim/
The following are the programs. The main program is FlowNetEx01.java
package network.flow.example01;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import java.util.*;
// Test Driver class for this example
public class FlowNetEx01
{
// Creates main() to run this example
public static void main(String[] args)
{
System.out.println("Starting network example ...");
try
{
int num_user = 4; // number of grid users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace GridSim events
System.out.println("Initializing GridSim package");
// It is essential to set the network type before calling GridSim.init()
GridSim.initNetworkType(GridSimTags.NET_FLOW_LEVEL);
GridSim.init(num_user, calendar, trace_flag);
// In this example, the topology is:
// user(s) --10Mb/s-- r1 --1.5Mb/s-- r2 --10Mb/s-- GridResource(s)
Router r1 = new FlowRouter("router1", trace_flag); // router 1
Router r2 = new FlowRouter("router2", trace_flag); // router 2
String sender1 = "user1";
String receipient1 = "test1";
String sender2 = "user2";
String receipient2 = "test2";
// these entities are the senders
FlowNetUser user1 = new FlowNetUser(sender1, receipient2, 5.0);
FlowNetUser user2 = new FlowNetUser(sender2, receipient1, 20.0);
// these entities are the receipients
FlowTest test1 = new FlowTest(receipient1, sender2);
FlowTest test2 = new FlowTest(receipient2, sender1);
// The schedulers are redundent and will be stripped out soon
FIFOScheduler userSched1 = new FIFOScheduler("NetUserSched_0");
r1.attachHost(user1, userSched1);
FIFOScheduler userSched2 = new FIFOScheduler("NetUserSched_1");
r1.attachHost(user2, userSched2);
FIFOScheduler testSched1 = new FIFOScheduler("FlowTestSched_0");
r2.attachHost(test1, testSched1);
FIFOScheduler testSched2 = new FIFOScheduler("FlowTestSched_1");
r2.attachHost(test2, testSched2);
//////////////////////////////////////////
// Second step: Creates a physical link
double baud_rate = 1572864; // bits/sec (baud) [1.5Mb/s]
double propDelay = 300; // propagation delay in millisecond
int mtu = Integer.MAX_VALUE;; // max. transmission unit in byte
Link link = new FlowLink("r1_r2_link", baud_rate, propDelay, mtu);
FIFOScheduler r1Sched = new FIFOScheduler("r1_Sched");
FIFOScheduler r2Sched = new FIFOScheduler("r2_Sched");
r1.attachRouter(r2, link, r1Sched, r2Sched);
//////////////////////////////////////////
// Final step: Starts the simulation
GridSim.startGridSimulation();
System.out.println("\nFinish network example ...");
}
catch (Exception e)
{
e.printStackTrace();
System.err.print(e.toString());
System.out.println("Unwanted errors happen");
}
}
} // end class
Program-2:
package network.flow.example01;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import eduni.simjava.*;
import java.util.*;
public class FlowNetUser extends GridSim
{
private int myID_; // my entity ID
private String name_; // my entity name
private String destName_; // destination name
private int destID_; // destination id
private double wait_; // Delay until I begin sending
public static final int SEND_MSG = 1;
public static final int ACK_MSG = 2;
public FlowNetUser(String name, String destName, Link link, double wait) throws Exception
{
super(name, link);
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
this.destName_ = destName;
// get the waiting time before sending
this.wait_ = wait;
}
public FlowNetUser(String name, String destName, double wait) throws Exception
{
// 10,485,760 baud = 10Mb/s
super(name, new FlowLink(name+"_link",10485760,450,Integer.MAX_VALUE));
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
destName_ = destName;
// get the waiting time before sending
this.wait_ = wait;
}
public void body()
{
int packetSize = 524288000; // packet size in bytes [5MB]
//int packetSize = 52428800; // packet size in bytes [50MB]
//int packetSize = 524288000; // packet size in bytes [500MB]
//int packetSize = 5242880000; // packet size in bytes [5000MB]
int size = 3; // number of packets sent
int i = 0;
// get the destination entity ID
this.destID_ = GridSim.getEntityId(destName_);
//super.sim_pause(this.wait_);
this.gridSimHold(this.wait_);
// sends messages over the other side of the link
for (i = 0; i < size; i++)
{
String msg = "Message_" + i;
IO_data data = new IO_data(msg, packetSize, destID_);
System.out.println(name_ + ".body(): Sending " + msg +
", at time = " + GridSim.clock() );
// sends through Output buffer of this entity
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.FLOW_SUBMIT, data);
//super.sim_pause();
super.sim_pause(10.0);
//this.gridSimHold((Math.random()*10)+1.0);
}
// get the ack back
Object obj = null;
for (i = 0; i < size; i++)
{
// waiting for incoming event in the Input buffer
obj = super.receiveEventObject();
System.out.println(name_ + ".body(): Receives Ack for " + obj);
}
// Wait for other FlowNetUser instances to finish
this.gridSimHold(1000.0);
super.send(destID_, GridSimTags.SCHEDULE_NOW,
GridSimTags.END_OF_SIMULATION);
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
}
} // end class
Program-3:
package network.flow.example01;
import java.util.*;
import gridsim.*;
import gridsim.net.*;
import gridsim.net.flow.*;
import gridsim.util.SimReport;
import eduni.simjava.*;
public class FlowTest extends GridSim
{
private int myID_; // my entity ID
private String name_; // my entity name
private String destName_; // destination name
private int destID_; // destination id
private SimReport report_; // logs every activity
public FlowTest(String name, String destName, Link link) throws Exception
{
super(name, link);
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
this.destName_ = destName;
// logs every activity. It will automatically create name.csv file
report_ = new SimReport(name);
report_.write("Creates " + name);
}
public FlowTest(String name, String destName) throws Exception
{
// 10,485,760 baud = 10Mb/s
super(name, new FlowLink(name+"_link",10485760,250,Integer.MAX_VALUE));
// get this entity name from Sim_entity
this.name_ = super.get_name();
// get this entity ID from Sim_entity
this.myID_ = super.get_id();
// get the destination entity name
this.destName_ = destName;
// logs every activity. It will automatically create name.csv file
report_ = new SimReport(name);
report_.write("Creates " + name);
}
public void body()
{
// get the destination entity ID
this.destID_ = GridSim.getEntityId(destName_);
int packetSize = 1500; // packet size in bytes
Sim_event ev = new Sim_event(); // an event
// a loop waiting for incoming events
while ( Sim_system.running() )
{
// get the next event from the Input buffer
super.sim_get_next(ev);
// if an event denotes end of simulation
if (ev.get_tag() == GridSimTags.END_OF_SIMULATION)
{
System.out.println();
write(super.get_name() + ".body(): exiting ...");
break;
}
// if an event denotes another event type
else if (ev.get_tag() == GridSimTags.FLOW_SUBMIT)
{
System.out.println();
write(super.get_name() + ".body(): receive " +
ev.get_data() + ", at time = " + GridSim.clock());
// No need for an ack, it is handled in FlowBuffer now on our behalf
// sends back an ack
IO_data data = new IO_data(ev.get_data(), packetSize, destID_);
write(name_ + ".body(): Sending back " +
ev.get_data() + ", at time = " + GridSim.clock() );
// sends through Output buffer of this entity
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.FLOW_ACK, data);
}
else if (ev.get_tag() == GridSimTags.INFOPKT_SUBMIT)
{
processPingRequest(ev);
}
}
// shut down I/O ports
shutdownUserEntity();
terminateIOEntities();
// don't forget to close the file
if (report_ != null) {
report_.finalWrite();
}
System.out.println(this.name_ + ":%%%% Exiting body() at time " +
GridSim.clock() );
}
private void processPingRequest(Sim_event ev)
{
InfoPacket pkt = (InfoPacket) ev.get_data();
pkt.setTag(GridSimTags.INFOPKT_RETURN);
pkt.setDestID( pkt.getSrcID() );
// sends back to the sender
super.send(super.output, GridSimTags.SCHEDULE_NOW,
GridSimTags.INFOPKT_RETURN,
new IO_data(pkt,pkt.getSize(),pkt.getSrcID()) );
}
private void write(String msg)
{
System.out.println(msg);
if (report_ != null) {
report_.write(msg);
}
}
} // end class
After running these programs, someone can tell us how to extend the required functionality as I mentioned in the beginning.
Personal experience ... GridSim5.2 potentially buggy.
The examples are dated written for version < 4.0, demonstrating not very complex scenarios.
Using version 5.2. According to the API docs every simulation should have at least one TopRegionalRC. This appends a UniqueID to the filename and records the location of the file in two hashmaps one for filename and the other for fileattr. Now the event filename used for the lookup remains unchanged - the lookup fails - compares to the fileattrmap.name_. Consequently, the waiting for ack block is never executed when performing a addmaster operation.
Fix: Since the UniqueId is returned by the initial request to the CTLG this can be appended to the filename for the subsequent event requiring the lookup. Alternatively, add the filename to fileattrmap and the filename+uniqueid to fileattrmap, then test for both in the lookup.
Also, GridSimTags uses -1 to signal END_OF_SIMULATION, but this conflicts with Advanced Reservation (AR) block of tags. That also use negative numbers. GridSimTags has an optional routine to check for duplicates but its use is optional and does not apply to DataGridTags. I created a reversemap for ease of debugging adding validation to ensure no duplicates occur and deprecated the GridSimTags method.
I am now wrestling with the DataGrid user tasks that do not seem to create events, I am also concerned that the delay operations are not effective.
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())
}
}
}
}
}