Gridsim: Extend functionality in network flow - java

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.

Related

How can I query for the configured maximum IBM MQ queue depth in Java?

How can I use the IBM MQ Java APIs to query for the maximum queue depth attribute of a queue?
You can use MQ PCF to retrieve attribute values of a queue.
i.e.
request = new PCFMessage(CMQCFC.MQCMD_INQUIRE_Q);
/**
* You can explicitly set a queue name like "TEST.Q1" or
* use a wild card like "TEST.*"
*/
request.addParameter(CMQC.MQCA_Q_NAME, "*");
// Add parameter to request only local queues
request.addParameter(CMQC.MQIA_Q_TYPE, CMQC.MQQT_LOCAL);
// Add parameter to request all of the attributes of the queue
request.addParameter(CMQCFC.MQIACF_Q_ATTRS, new int [] { CMQC.MQCA_Q_NAME,
CMQC.MQIA_CURRENT_Q_DEPTH,
CMQC.MQIA_MAX_Q_DEPTH
});
responses = agent.send(request);
for (int i = 0; i < responses.length; i++)
{
if ( ((responses[i]).getCompCode() == CMQC.MQCC_OK) &&
((responses[i]).getParameterValue(CMQC.MQCA_Q_NAME) != null) )
{
String name = responses[i].getStringParameterValue(CMQC.MQCA_Q_NAME);
if (name != null)
name = name.trim();
int depth = responses[i].getIntParameterValue(CMQC.MQIA_CURRENT_Q_DEPTH);
int maxDepth = responses[i].getIntParameterValue(CMQC.MQIA_MAX_Q_DEPTH);
}
}
I thought I posted MQListQueueAttributes01.java to StackOverflow but I cannot find it. It is on my blog.
It is a complete and fully functioning Java/MQ/PCF program to retrieve all attributes values of a queue. If you click on "PCF" category on my blog, you will find a variety of complete sample Java/MQ/PCF programs.
One way of doing it is by using the inquire method on the MQQueue object:
import com.ibm.mq.MQException;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import static com.ibm.mq.constants.CMQC.MQIA_MAX_Q_DEPTH;
import static com.ibm.mq.constants.CMQC.MQOO_INQUIRE;
public class SampleJavaCode {
public static void main(String[] args) throws MQException {
MQQueueManager mqQueueManager = ...;
MQQueue mqQueue = mqQueueManager.accessQueue("ORDER", MQOO_INQUIRE);
int[] selectors = new int[]{MQIA_MAX_Q_DEPTH};
int[] intAttrs = new int[1];
byte[] charAttrs = new byte[0];
mqQueue.inquire(selectors, intAttrs, charAttrs);
System.out.println("Max Queue depth = " + intAttrs[0]);
}
}

Reading a text file with boolean values into an array list as objects

I am trying to read a file of string int and boolean values into an array list as object blocks. The string values go into the array list just fine, its the boolean values I'm having trouble with. Every time I encounter the variable 'active'there is a mismatch exception. Please help! The text file for if the block is a wizard goes in this order
name (string)
location (string)
active (boolean) ... the one I'm having issues with
skill level (int)
friendliness (int)
I included the driver class as well as the Witch class which contains the
variable 'active' originally.
Driver class that adds objects to the array list based on what the scanner
reads from the file
package project2;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class Project2 {
public static void main(String[] args) {
Scanner inputFileScanner1 = null;
//file name
String listFile = "list.txt";
// Check to see if file exists
try {
inputFileScanner1 = new Scanner(new File(listFile));
} catch (FileNotFoundException e) {
System.out.println("Error opening file.");
System.exit(1);
}
//create Individuals arraylist and Location arraylist
ArrayList < Individual > Individual = new ArrayList < > ();
ArrayList < String > Location = new ArrayList < > ();
//declare variables to read file contents into the arraylist
String wizName, witchName, individualName, location, position,
profession = null, line = null;
int wizLevel, witchSkillLevel, friendliness;
boolean active;
//while there is a next line, if the line equals Wizard, the next four lines
// are wizard name, location, position and level
while (inputFileScanner1.hasNext()) {
line = inputFileScanner1.nextLine();
if (line.trim().equals("Wizard")) {
wizName = inputFileScanner1.nextLine().trim();
location = inputFileScanner1.nextLine().trim();
position = inputFileScanner1.nextLine().trim();
wizLevel = inputFileScanner1.nextInt();
//create wizard object
Individual wizard = new Wizard(wizName, location, position, profession, wizLevel);
//fill arraylist with wizard objects
Individual.add(wizard);
Location.add(location);
} //if the next line is Witch, the next five lines are
// witch name, location, yes/no active, skill level, and friendliness
//in that order
else if (line.trim().equals("Witch")) {
witchName = inputFileScanner1.nextLine().trim();
location = inputFileScanner1.nextLine().trim();
active = inputFileScanner1.nextBoolean();
witchSkillLevel = inputFileScanner1.nextInt();
friendliness = inputFileScanner1.nextInt();
//create witch object
Individual witch = new Witch(witchName, location, profession, witchSkillLevel, friendliness, active);
//fill the arraylist with witch objects
Individual.add(witch);
Location.add(location);
} else {
profession = line.trim();
individualName = inputFileScanner1.nextLine().trim();
location = inputFileScanner1.nextLine().trim();
Individual i = new Individual(profession, individualName, location);
Individual.add(i);
Location.add(location);
}
java.util.Collections.sort(Individual);
java.util.Collections.sort(Location);
}
System.out.println("List of friends and possible allies: " + Location);
inputFileScanner1.close();
}
}
//Witch class which holds values that are in the text file. active is the boolean value Im having trouble with
package project2;
public class Witch extends Individual implements Magical {
private int skill;
private int friendly;
//Constructor with witch parameters
public Witch(String name, String location, String profession,
int skill, int friendly, boolean active) {
}
//default constructor
public Witch() {
this("", "", "", 0, 0, false);
}
//overridden abstract method from magical interface
#Override
public void assess() {
System.out.print(this.friendly + " " + this.skill + " " + super.toString());
}
}
<!-- end snippet -->
Text file :
enter image description here
When you pull in your boolean variable do something like this.
if(inputFileScanner1.nextLine().trim().equals("yes"))
{
active = true;
}
else
{
active = false;
}
Okay, the problem is that the file contains the strings yes and no, that are not directly parsable as booleans (should be true or false).
If you can change the original data file somehow, I would suggest to use the two true and false keywords, otherwise, the #Sendrick Jefferson solution will do the job (at your own risk: every typo, as for instance "ye", will be translated into false).

need advice regarding design and performance issue

I have data retrieved from a server at very high rate, the datas sent are in form of a message that resembles the following format:
$FMSn,par1,par2...,...,...,...,..,...,....,par20 //where n is number ranges from 1 to 12
this message I need to process to parse some data.
but less frequently the server sends other message in different format, that message is not important and could be discarded and the difference between it and the previously described messages in format is that
the previous message starts with $FMS while the other message not.
to distinguish between these messages to know which one is that should be processed, i created a class FMSParser as shown below and i checked if the message header is
$FMS
or not.
my question is, should i create a new object of FMSParser class in the loop in which the messages from the server are received or create one object in the whole
program and in the loop in which the data are recived i just call isValid method and getParam(). in other words in code:
should i choose solution 1 or 2?
solution 1:
loop for messages receiving:
msg = receive message();
fmsParser = new FMSParser(msg);
if (fmsParser.isValid) {
params = fmsParser.getParam();
}
solution 2:
fmsParser = new FMSParser();
loop for messages receiving:
msg = receive message();
if (fmsParser.isValid(msg)) {
params = fmsParser.getParam();
}
code:
private class FMSParser {
private final static String HEADER = "$FMS"
private String[] mSplittedMsg;
FMSParser() {}
public boolean isValidMsg(String msg) {
boolean isValid = false;
this.mSplittedMsg = msg.split(",");
for (int i = 0; i < 12; i++) {
if (splittedMsg[0].equals(HEADER+i)) {
valid = true;
break;
}
}
return valid;
}
public String [] getParam() {
return this.mSplittedMsg;
}
}
If you construct a new FMSParser each time through the loop, it will require memory allocation and garbage collection.
I would choose option 3 which makes the FMSParser immutable, meaning it is thread-safe.
FMSParser fmsParser = new FMSParser();
while (messageIterator.hasNext()) {
String msg = messageIterator.next();
if (fmsParser.isValid(msg)) {
params = fmsParser.getParam(msg);
}
}
Eg:
public class FMSParser {
public boolean isValid(String msg) {
return msg.startsWith("$FMS");
}
public String[] getParams(String msg) {
return msg.split(",");
}
}

LensKit: LensKit demo is not reading my data file

When I run the LensKit demo program I get this error:
[main] ERROR org.grouplens.lenskit.data.dao.DelimitedTextRatingCursor - C:\Users\sean\Desktop\ml-100k\u - Copy.data:4: invalid input, skipping line
I reworked the ML 100k data set so that it only holds this line although I dont see how this would effect it:
196 242 3 881250949
186 302 3 891717742
22 377 1 878887116
244
Here is the code I am using too:
public class HelloLenskit implements Runnable {
public static void main(String[] args) {
HelloLenskit hello = new HelloLenskit(args);
try {
hello.run();
} catch (RuntimeException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
private String delimiter = "\t";
private File inputFile = new File("C:\\Users\\sean\\Desktop\\ml-100k\\u - Copy.data");
private List<Long> users;
public HelloLenskit(String[] args) {
int nextArg = 0;
boolean done = false;
while (!done && nextArg < args.length) {
String arg = args[nextArg];
if (arg.equals("-e")) {
delimiter = args[nextArg + 1];
nextArg += 2;
} else if (arg.startsWith("-")) {
throw new RuntimeException("unknown option: " + arg);
} else {
inputFile = new File(arg);
nextArg += 1;
done = true;
}
}
users = new ArrayList<Long>(args.length - nextArg);
for (; nextArg < args.length; nextArg++) {
users.add(Long.parseLong(args[nextArg]));
}
}
public void run() {
// We first need to configure the data access.
// We will use a simple delimited file; you can use something else like
// a database (see JDBCRatingDAO).
EventDAO base = new SimpleFileRatingDAO(inputFile, "\t");
// Reading directly from CSV files is slow, so we'll cache it in memory.
// You can use SoftFactory here to allow ratings to be expunged and re-read
// as memory limits demand. If you're using a database, just use it directly.
EventDAO dao = new EventCollectionDAO(Cursors.makeList(base.streamEvents()));
// Second step is to create the LensKit configuration...
LenskitConfiguration config = new LenskitConfiguration();
// ... configure the data source
config.bind(EventDAO.class).to(dao);
// ... and configure the item scorer. The bind and set methods
// are what you use to do that. Here, we want an item-item scorer.
config.bind(ItemScorer.class)
.to(ItemItemScorer.class);
// let's use personalized mean rating as the baseline/fallback predictor.
// 2-step process:
// First, use the user mean rating as the baseline scorer
config.bind(BaselineScorer.class, ItemScorer.class)
.to(UserMeanItemScorer.class);
// Second, use the item mean rating as the base for user means
config.bind(UserMeanBaseline.class, ItemScorer.class)
.to(ItemMeanRatingItemScorer.class);
// and normalize ratings by baseline prior to computing similarities
config.bind(UserVectorNormalizer.class)
.to(BaselineSubtractingUserVectorNormalizer.class);
// There are more parameters, roles, and components that can be set. See the
// JavaDoc for each recommender algorithm for more information.
// Now that we have a factory, build a recommender from the configuration
// and data source. This will compute the similarity matrix and return a recommender
// that uses it.
Recommender rec = null;
try {
rec = LenskitRecommender.build(config);
} catch (RecommenderBuildException e) {
throw new RuntimeException("recommender build failed", e);
}
// we want to recommend items
ItemRecommender irec = rec.getItemRecommender();
assert irec != null; // not null because we configured one
// for users
for (long user: users) {
// get 10 recommendation for the user
List<ScoredId> recs = irec.recommend(user, 10);
System.out.format("Recommendations for %d:\n", user);
for (ScoredId item: recs) {
System.out.format("\t%d\n", item.getId());
}
}
}
}
I am really lost on this one and would appreciate any help. Thanks for your time.
The last line of your input file only contains one field. Each input file line needs to contain 3 or 4 fields.

Main method not found

When I try to excute the java class below (AuctionExample1.java), I got the following error :
"selection does not contain the main type"
Here is the java class :
package org.cloudbus.cloudsim.examples.auction;
/**
* A simple example showing how to create a bidder datacenter and a bidder broker
* and start the auction.
* No VM is specified at all because no one wins he auction.
*
* Created on 2011/9/9
*/
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletSchedulerTimeShared;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.UtilizationModel;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicySimple;
import org.cloudbus.cloudsim.VmSchedulerTimeShared;
import org.cloudbus.cloudsim.auction.auctioneer.Auctioneer;
import org.cloudbus.cloudsim.auction.bid.DatacenterBid;
import org.cloudbus.cloudsim.auction.bid.DatacenterBrokerBid;
import org.cloudbus.cloudsim.auction.bidder.BidderDatacenter;
import org.cloudbus.cloudsim.auction.bidder.BidderDatacenterBroker;
import org.cloudbus.cloudsim.auction.vm.DatacenterAbstractVm;
import org.cloudbus.cloudsim.auction.vm.VmCharacteristics;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.provisioners.BwProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
public class AuctionExample1 {
/** The cloudlet list. */
private static List<Cloudlet> cloudletList;
/** The vmlist. */
private static List<Vm> vmlist;
/**
* Creates main() to run this example.
*
* #param args the args
*/
public static void main(String[] args) {
Log.printLine("Starting AuctionExample1...");
try {
// First step: Initialize the CloudSim package. It should be called
// before creating any entities.
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
// Initialize the CloudSim library
CloudSim.init(num_user, calendar, trace_flag);
Auctioneer.initAuctioneer();
// Second step: Create Datacenters
// Datacenters are the resource providers in CloudSim. We need at
// list one of them to run a CloudSim simulation
BidderDatacenter datacenter0 = createDatacenter("Datacenter_0");
// Third step: Create Broker
BidderDatacenterBroker broker = createBroker();
int brokerId = broker.getId();
// Fourth step: Create one virtual machine
vmlist = new ArrayList<Vm>();
// VM description
int vmid = 0;
int mips = 1000; /*Youness: VM need to be allocated a share of
processing power on Datacenter's hosts.*/
long size = 10000; // image size (MB) (Youness: virtual machine's image size)
int ram = 512; // vm memory (MB)
long bw = 1000;
int pesNumber = 1; // number of cpus
String vmm = "Xen"; // VMM name
// create VM
Vm vm = new Vm(vmid, brokerId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
// add the VM to the vmList
vmlist.add(vm);
// Fifth step: Create one Cloudlet
cloudletList = new ArrayList<Cloudlet>();
// Cloudlet properties
int id = 0;
long length = 400000; //MI cloudletLength
long fileSize = 300; //cloudletFileSize
long outputSize = 300; //cloudletOutputSize
UtilizationModel utilizationModel = new UtilizationModelFull();
Cloudlet cloudlet = new Cloudlet(id, length, pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
cloudlet.setUserId(brokerId);
cloudlet.setVmId(vmid);//Youness: Bind cloudLet to a VM. If you do not do this, application assigns the first created VM for this cloudlet
// add the cloudlet to the list
cloudletList.add(cloudlet);
// submit cloudlet list to the broker
broker.submitCloudletList(cloudletList);
DatacenterBrokerBid brokerBid = new DatacenterBrokerBid(broker.getId(), 0.0035);
brokerBid.addVM(vm, 1);
broker.submitBid(brokerBid);
// Sixth step: Starts the simulation
CloudSim.startSimulation();
CloudSim.stopSimulation();
//Final step: Print results when simulation is over
List<Cloudlet> newList = broker.getCloudletReceivedList();
printCloudletList(newList);
// Print the debt of each user to each datacenter
datacenter0.printDebts();
Log.printLine("AuctionExample1 finished!");
} catch (Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
/**
* Creates the datacenter.
*
* #param name the name
*
* #return the datacenter
*/
private static BidderDatacenter createDatacenter(String name) {
// Here are the steps needed to create a PowerDatacenter:
// 1. We need to create a list to store
// our machine
List<Host> hostList = new ArrayList<Host>();
// 2. A Machine contains one or more PEs or CPUs/Cores.
// In this example, it will have only one core.
List<Pe> peList = new ArrayList<Pe>();
int mips = 1000;
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerSimple(mips))); // need to store Pe id and MIPS Rating
// 4. Create Host with its id and list of PEs and add them to the list
// of machines
int hostId = 0;
int ram = 2048; // host memory (MB)
long storage = 1000000; // host storage
int bw = 10000;
Host host = new Host(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerSimple(bw),
storage,
peList,
new VmSchedulerTimeShared(peList)
);
hostList.add(host); // This is our machine
// 5. Create a DatacenterCharacteristics object that stores the
// properties of a data center: architecture, OS, list of
// Machines, allocation policy: time- or space-shared, time zone
// and its price (G$/Pe time unit).
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this
// resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); // we are not adding SAN
// devices by now
DatacenterCharacteristics characteristics = new DatacenterCharacteristics(
arch, os, vmm, hostList, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
// 6. Finally, we need to create a PowerDatacenter object.
BidderDatacenter datacenter = null;
try {
datacenter = new BidderDatacenter(name, characteristics, new VmAllocationPolicySimple(hostList), storageList, 0);
} catch (Exception e) {
e.printStackTrace();
}
//TODO check if VM fits the host
VmCharacteristics vmCharacteristics = new VmCharacteristics(
arch, os, vmm, time_zone, cost, costPerMem,
costPerStorage, costPerBw);
DatacenterAbstractVm vm = new DatacenterAbstractVm(1000, 1, 512, 1000, 1000, vmCharacteristics);
DatacenterBid bid = new DatacenterBid(datacenter.getId());
bid.addVM(vm, 1);
datacenter.submitBid(bid);
return datacenter;
}
// We strongly encourage users to develop their own broker policies, to
// submit vms and cloudlets according
// to the specific rules of the simulated scenario
/**
* Creates the broker.
*
* #return the datacenter broker
*/
private static BidderDatacenterBroker createBroker() {
BidderDatacenterBroker broker = null;
try {
broker = new BidderDatacenterBroker("Broker");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return broker;
}
/**
* Prints the Cloudlet objects.
*
* #param list list of Cloudlets
*/
private static void printCloudletList(List<Cloudlet> list) {
int size = list.size();
Cloudlet cloudlet;
String indent = " ";
Log.printLine();
Log.printLine("========== OUTPUT ==========");
Log.printLine("Cloudlet ID" + indent + "STATUS" + indent
+ "Data center ID" + indent + "VM ID" + indent + "Time" + indent
+ "Start Time" + indent + "Finish Time");
DecimalFormat dft = new DecimalFormat("###.##");
for (int i = 0; i < size; i++) {
cloudlet = list.get(i);
Log.print(indent + cloudlet.getCloudletId() + indent + indent);
if (cloudlet.getCloudletStatus() == Cloudlet.SUCCESS) {
Log.print("SUCCESS");
Log.printLine(indent + indent + cloudlet.getResourceId()
+ indent + indent + indent + cloudlet.getVmId()
+ indent + indent
+ dft.format(cloudlet.getActualCPUTime()) + indent
+ indent + dft.format(cloudlet.getExecStartTime())
+ indent + indent
+ dft.format(cloudlet.getFinishTime()));
}
}
}
}
I want to add a note, that the structure of this project is not constituted into packages. Here is an outline description of the project hierarchy :
/CloudAuction
/CloudAuction/src
/CloudAuction/src/main
/CloudAuction/src/test
/CloudAuction/src/test/java
/CloudAuction/src/test/java/org.cloudbus.cloudsim.examples.auction
/CloudAuction/src/test/java/org.cloudbus.cloudsim.examples.auction/AuctionExample1.java
/CloudAuction/src/test/java/org.cloudbus.cloudsim.examples.auction/AuctionExample2.java
/CloudAuction/src/test/java/org.cloudbus.cloudsim.examples.auction/AuctionExample3.java
/CloudAuction/src/test/java/org.cloudbus.cloudsim.examples.auction/AuctionExample4.java
/CloudAuction/src/test/java/org.cloudbus.cloudsim.examples.auction/BidderBrokerFactory.java
/CloudAuction/src/test/java/org.cloudbus.cloudsim.examples.auction/BidderDatacenterFactory.java
/CloudAuction/target
/CloudAuction/pom.xml
Can anyone help me to find a solution to this problem, please ?
under the src folder you must have the package name represented as folders. In your code you have : org.cloudbus.cloudsim.examples.auction as package name but you don't have the same folders in you src, the folder need to be like this :
src/org/cloudbus/cloudsim/examples/auction/YourClass.java

Categories