I keep getting null pointer exception when I try to put into messages
( I have removed all unnecessary code)
I dont get the error when I initialize messages inside add function
How can I resolve this?
class Chat {
HashMap< Integer, String> messages;
void Chat() {
this.messages = new HashMap<>();
}
public void add(int id, String newMessage) {
if (!newMessage.isEmpty()) {
System.out.println(newMessage + " "
+ Integer.parseInt(String.valueOf(id)));
this.messages.put(Integer.parseInt(String.valueOf(id)),
newMessage);
System.out.println(messages.values() + "Added to hashset");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Chat obj = new Chat();
int size = Integer.parseInt(sc.nextLine());
for (int i = 0; i < size; i++) {
String str = sc.nextLine();
if (!str.isEmpty()) {
obj.add(i + 1, str);
}
}
}
}
I am trying to mock the getMeasureAggregator() of ResultSetRow object - I don't seem to succeed. I am very new in writing mockito unit test.
I want the BuilSQL.formatMeasuer() goes to case 2: so what I have decided to do was mocking row.getMeasureAggregator.
Here is my BuildSQL class:
public class SQLBuilder {
public static String buildSQL(JsonObject requestData, JsonObject queryInfo) throws AcquisitionException {
JsonArray jArray = queryInfo.get("columns").getAsJsonArray();
Set<String> columns = new HashSet<>(jArray.size());
for (int i = 0; i < jArray.size(); i++) {
columns.add(jArray.get(i).getAsString());
}
List<ResultSetRow> selectedRows = new ArrayList<>();
List<ResultSetRow> retrievedRows = null;
retrievedRows = MetaDataProvider.executeMetadataRequest(queryInfo, requestData); // this method returns a collection of RetrievedResultSetRow
for (ResultSetRow retrievedRow: retrievedRows) {
if (//some condition evaluates to true) {
selectedRows.add(retrievedRow);
}
}
String sql = "";
String select = "SELECT ";
for (int i = 0; i < selectedRows.size(); i++) {
ResultSetRow row = selectedRows.get(i);
select += formatMeasure(row.getMeatureName(), row.getMeasureAggregator());
}
select = select.substring(0, select.length() - 1);
return sql;
}
private static String formatMeasure(String measureName, int measureAggregator) {
switch(measureAggregator) {
case 1:
return "sum(\"" + measureName + "\")" + " AS \"" + measureName + "\",";
case 2:
return "COUNT(\"" + measureName + "\")" + " AS \"" + measureName + "\",";
return measureName;
}
}
here is my ResultSetRow class:
public class ResultSetRow {
private final int iRow;
private final int measureAggregator;
public ResultSetRow(JsonObject dimensionMetadata) {
this.iRow = dimensionMetadata.get("ROW").getAsInt();
this.measureAggregator = dimensionMetadata.get("MEASURE_AGGR").getAsInt();
}
public int getMeasureAggregator() {
return measureAggregator;
}
}
here is how I am mocking
#RunWith(PowerMockRunner.class)
#PrepareForTest({ HanaClientRequestUtils.class, RetrievedResultSetRow.class })
public class HanaSQLBuilderTest {
private ResultSetRow resultSetRow;
private requestData;
private queryInfo
#Test
public void formatMeatureExecuteCase2() throws Exception{
resultSetRow = Mockito.mock(ResultSetRow.class);
PowerMockito.when(resultSetRow.getMeasureAggregator()).thenReturn(2);
String querySQL = HanaSQLBuilder.buildSQL(requestData, queryInfo);
System.out.println(querySQL);
}
}
}
I am not sure why row.getMeasureAggregator() does not return 2?
Additionally to my comments above (I am coding by hand, forgive me some mistakes).
You can try with adding a retrievedRows as a parameter in Your buildSQL method:
public static String buildSQL(
JsonObject requestData,
JsonObject queryInfo,
List<ResultSetRow> retrievedRows) throws AcquisitionException {
// ... rest of Your code adopted to new parameter
}
And then provide Your retrievedRows filled with mocks
#Test
public void formatMeatureExecuteCase2() throws Exception{
resultSetRow = Mockito.mock(ResultSetRow.class);
PowerMockito.when(resultSetRow.getMeasureAggregator()).thenReturn(2);
List<ResultSetRow> retrievedRowsMock = new ArrayList<>(1);
retrievedRowsMock.add(resultSetRow);
String querySQL = HanaSQLBuilder.buildSQL(requestData, queryInfo, retrievedRowsMock);
System.out.println(querySQL);
}
}
I hope it will guide You to solution.
Hi everyone i've produced an agent based model. The agents can move randomly and use the A* algorithm to move to places to places. There are two main collections 1) arrival Queue (arraylist) and the 2) main agents (arraylist). All the agents are initially placed into the arrival queue, agents are placed into the simulation at certain time intervals e.g. 100 agents per 400 simulation steps).
The issue im getting is every time I increase the population of agents from 3000+ the simulation begins to lag. Also im using the Java 2D libraries for visualizing the 2D array of agents. Bellow ive added a screenshot of the the visualVM of my application is shows the methods which are being called the most (CPU time).
ScreenShot Here
Model code:
package Model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import Model.Grid;
import Agent.*;
public class Model extends AbstractModel implements Runnable{
private Grid grid;
private Constants modelConstants;
private RandomGenerator randGenerator;
private GridMapLayout Maplayout;
private RoomController roomController;
private AgentFactory agentFacory;
private Statistics stats;
private ArrayList<AbstractAgent> agents;
private Queue<Patient> patientArrivalQueue;
private List<Patient> dischargedPatients;
private Queue<Doctor> doctorsQueue;
private Queue<Nurse> nursesQueue;
private int patientPopulation;
private int doctorPopulation;
private int receptionNurses;
private int aNeNurses;
private int ward1Nurses;
private int ward2Nurses;
private int ward3Nurses;
private boolean running;
private int currentSimCycle;
private int simArrivalCounter;
public CTimer timer = new CTimer();
public Model() {
super();
this.grid = new Grid(150, 150); //if no given size grid uses default size
this.modelConstants = new Constants();
this.randGenerator = new RandomGenerator(modelConstants.getSEED());
this.Maplayout = new GridMapLayout(this);
this.roomController = new RoomController(this);
this.agentFacory = new AgentFactory(this);
this.stats = new Statistics(this);
this.currentSimCycle = 0;
this.simArrivalCounter = 0;
this.agents = new ArrayList<AbstractAgent>();
this.patientArrivalQueue = new LinkedList<Patient>();
this.dischargedPatients = new LinkedList<Patient>();
this.doctorsQueue = new LinkedList<Doctor>();
this.nursesQueue = new LinkedList<Nurse>();
loadModelConstants();
loadMapLayout();
roomController.readyRoomCollections();
createAllAgents();
loadDoctorsInRooms();
loadNursesInRooms();
loadNextPatientArrival();
// randomlyPopulateGrid();
stats.updateStatistics();
stats.setDataValid(false);
// Room entrance = roomController.getAllRooms().get("Entrance");
// Room reception = roomController.getAllRooms().get("Reception");
// Room aNe = roomController.getAllRooms().get("A&E");
// Room ward1 = roomController.getAllRooms().get("Ward 1");
// Room ward2 = roomController.getAllRooms().get("Ward 2");
// Room ward3 = roomController.getAllRooms().get("Ward 3");
// Room canteen = roomController.getAllRooms().get("Canteen");
// Room toilet = roomController.getAllRooms().get("Toilet");
//
// System.out.println(toilet);
// System.out.println(entrance.getDoorLocations().size());
// System.out.println("Reception: " + reception.getRoomLocations().size());
// System.out.println("A&E: " + aNe.getRoomLocations().size());
// System.out.println("Ward 1: " + ward1.getRoomLocations().size());
// System.out.println("Ward 2: " + ward2.getRoomLocations().size());
// System.out.println("Ward 3: " + ward3.getRoomLocations().size());
// System.out.println("Canteen: " + canteen.getRoomLocations().size());
// System.out.println("Toilet: " + toilet.getRoomLocations().size());
}
public void loadModelConstants() {
this.patientPopulation = modelConstants.getPatientPopulation();
this.doctorPopulation = modelConstants.getDoctorPopulation();
this.receptionNurses = modelConstants.getReceptionNursePopulation();
this.aNeNurses = modelConstants.getaNeNursePopulation();
this.ward1Nurses = modelConstants.getWard1NursePopulation();
this.ward2Nurses = modelConstants.getWard2NursePopulation();
this.ward3Nurses = modelConstants.getWard3NursePopulation();
// System.out.println(this.patientPopulation);
// System.out.println(this.doctorPopuation);
// System.out.println(this.nursePopulation);
System.out.println("Loaded Model Constants");
}
public void loadMapLayout() {
Maplayout.loadMapImage();
Maplayout.loadRGBfileAndRooms();
Maplayout.readPixels();
Maplayout.addMapLayout();
// layout.printCells();
System.out.println("Loaded Map Layout");
}
public void createAllAgents() {
ArrayList<Patient> tempPatient = new ArrayList<Patient>();
ArrayList<Doctor> tempDoctor = new ArrayList<Doctor>();
ArrayList<Nurse> tempNurse = new ArrayList<Nurse>();
int totalNurses = + (modelConstants.getReceptionNursePopulation()
+ modelConstants.getaNeNursePopulation()
+ modelConstants.getWard1NursePopulation()
+ modelConstants.getWard2NursePopulation()
+ modelConstants.getWard3NursePopulation()
);
int noOfAgentLeftToCreate = modelConstants.getPatientPopulation() + modelConstants.getDoctorPopulation()
+ totalNurses;
while(tempPatient.size() != this.patientPopulation) {
Patient newPatient = (Patient) this.agentFacory.createAgent("PATIENT", noOfAgentLeftToCreate);
tempPatient.add(newPatient);
noOfAgentLeftToCreate--;
}
while(tempDoctor.size() != this.doctorPopulation) {
Doctor newDoctor = (Doctor)this.agentFacory.createAgent("DOCTOR", noOfAgentLeftToCreate);
tempDoctor.add(newDoctor);
noOfAgentLeftToCreate--;
}
while(tempNurse.size() != totalNurses) {
Nurse newNurse = (Nurse)this.agentFacory.createAgent("NURSE", noOfAgentLeftToCreate);
tempNurse.add(newNurse);
noOfAgentLeftToCreate--;
}
this.patientArrivalQueue.addAll(tempPatient); //Add total patients to arrive queue
this.doctorsQueue.addAll(tempDoctor); //Add all doctors to the doctors agent collection
this.nursesQueue.addAll(tempNurse); //Add all nurses to the nurse agent collection
System.out.println("All agents created");
}
public void loadDoctorsInRooms() {
for(Map.Entry<String, Room> pair : roomController.getDoctorRooms().entrySet()) {
String key = pair.getKey();
Room value = pair.getValue();
if(value.isRoomEmpty()) {
Doctor newDoctor = doctorsQueue.remove();
Location randFreeRoomLoc = value.getRandomFreeRoomLocation();
grid.moveAgentToNewLocation(newDoctor, newDoctor.getLocation(), randFreeRoomLoc);
newDoctor.setLocation(randFreeRoomLoc);
newDoctor.setAllocatedRoom(value);
newDoctor.getAgentController().setCurrentRoom(value);
newDoctor.getAgentController().setTargetRoom(value);
//Tell the room that this agent is now a occupant of the room
value.getCurrentOccupantsMap().put(newDoctor.getAgentID(), newDoctor);
agents.add(newDoctor);
}
}
Room aNeRoom = roomController.getAllRooms().get("A&E");
if(aNeRoom.isRoomEmpty()) {
Doctor aNeDoc = doctorsQueue.remove();
Location randFreeRoomLoc = aNeRoom.getRandomFreeRoomLocation();
grid.moveAgentToNewLocation(aNeDoc, aNeDoc.getLocation(), randFreeRoomLoc);
aNeDoc.setLocation(randFreeRoomLoc);
aNeDoc.setAllocatedRoom(aNeRoom);
aNeDoc.getAgentController().setCurrentRoom(aNeRoom);
aNeDoc.getAgentController().setTargetRoom(aNeRoom);
//Tell the room that this agent is now a occupant of the room
aNeRoom.getCurrentOccupantsMap().put(aNeDoc.getAgentID(), aNeDoc);
agents.add(aNeDoc);
}
System.out.println("All Doctors are placed");
}
public void loadNursesInRooms() {
HashMap<String, Room> nurseRooms = new HashMap<String, Room>();
nurseRooms.putAll( roomController.getAllRooms());
nurseRooms.remove("Toilet");
nurseRooms.remove("Canteen");
nurseRooms.remove("Staff");
nurseRooms.remove("Corridor");
nurseRooms.remove("ISOL Entrance");
nurseRooms.remove("Entrance");
nurseRooms.remove("Exit");
for(Map.Entry<String, Room> drPair : roomController.getDoctorRooms().entrySet()) {
String drKey = drPair.getKey();
Room drValue = drPair.getValue();
for(Map.Entry<String, Room> isolPair : roomController.getIsolRooms().entrySet()) {
String isolKey = isolPair.getKey();
Room isolValue = isolPair.getValue();
if(nurseRooms.containsKey(drKey)) {
nurseRooms.remove(drKey);
}
if(nurseRooms.containsKey(isolKey)) {
nurseRooms.remove(isolKey);
}
}
}
for(Map.Entry<String, Room> pair : nurseRooms.entrySet()) {
String key = pair.getKey();
Room value = pair.getValue();
int noOfNurseToCreate = 0;
if(key.contentEquals("Reception")) {
noOfNurseToCreate = modelConstants.getReceptionNursePopulation();
}
else if(key.contentEquals("A&E")) {
noOfNurseToCreate = modelConstants.getaNeNursePopulation();
}
else if(key.contentEquals("Ward 1")) {
noOfNurseToCreate = modelConstants.getWard1NursePopulation();
}
else if(key.contentEquals("Ward 2")) {
noOfNurseToCreate = modelConstants.getWard2NursePopulation();
}
else if(key.contentEquals("Ward 3")) {
noOfNurseToCreate = modelConstants.getWard3NursePopulation();
}
for(int i=0; i != noOfNurseToCreate; i++) {
Nurse newNurse = nursesQueue.remove();
Location roomLocation = value.getRandomFreeRoomLocation();
grid.moveAgentToNewLocation(newNurse, newNurse.getLocation(), roomLocation);
newNurse.setLocation(roomLocation);
newNurse.setAllocatedRoom(value);
newNurse.getAgentController().setCurrentRoom(value);
newNurse.getAgentController().setTargetRoom(value);
//Tell the room controller that this agent is now an occupant of the room
value.getCurrentOccupantsMap().put(newNurse.getAgentID(), newNurse);
agents.add(newNurse);
}
}
System.out.println("All Nurses are placed");
}
public void loadNextPatientArrival() {
if(this.simArrivalCounter == 0) {
int removeThemPatients = 0;
//If there are more patients in the arrival queue then the specified simPatientarrival rate then
//remove the specified amount of patients per simPatient arrival rate
if(patientArrivalQueue.size() >= modelConstants.getPatientArrivalRate()) {
removeThemPatients = modelConstants.getPatientArrivalRate();
}
//Number of patient to place on the grid is less then the patient arrival rate, just place the rest into the entrance
else {
removeThemPatients = patientArrivalQueue.size();
}
Room reception = roomController.getAllRooms().get("Reception");
Room aNe = roomController.getAllRooms().get("A&E");
for(int i=removeThemPatients; i !=0; i--) {
Patient nextPatient = patientArrivalQueue.remove();
// if(nextPatient.getPatientType().contains("Normal") & nextPatient.getLocation() != null) {
if(grid.checkEmptyAt(nextPatient.getLocation())) {
grid.placeAgent(nextPatient, nextPatient.getLocation());
agents.add(nextPatient);
}
else {
patientArrivalQueue.add(nextPatient);
}
// }
}
//IMPORTANT need to reset the simArrivalCounter back to the specified count
this.simArrivalCounter = this.modelConstants.getSimArrivalCounter();
// System.out.println("More patients have arrived");
}
}
public void removeDischargedPatients() {
//Just iterate through the exit room door locations and remove
//the the discharged patients waiting there into the patient discharge list
Room exit = roomController.getAllRooms().get("Exit");
for(Location loc : exit.getDoorLocations()) {
if(!grid.checkEmptyAt(loc)) {
Patient dischargedPatient = (Patient) grid.getAgentAtLocation(loc);
grid.clearLocationAt(loc);
agents.remove(dischargedPatient);
dischargedPatients.add(dischargedPatient);
}
}
}
public void randomlyPopulateGrid() {
Room reception = roomController.getAllRooms().get("Reception");
while(!this.patientArrivalQueue.isEmpty()) {
Location freeLoc = reception.getRandomFreeRoomLocation();
Patient nextPatient = this.patientArrivalQueue.remove();
grid.moveAgentToNewLocation(nextPatient, nextPatient.getLocation(), freeLoc);
nextPatient.setLocation(freeLoc);
nextPatient.getAgentController().setCurrentRoom(reception);
nextPatient.getAgentController().setTargetRoom(reception);
agents.add(nextPatient);
}
System.out.println("Populate Grid");
}
public void simulateCycles(int maxCycles) {
for(int i=0; i != maxCycles; i++) {
loadNextPatientArrival();
removeDischargedPatients();
updateAgents();
stats.updateStatistics();
stats.setDataValid(false);
this.currentSimCycle++;
this.simArrivalCounter--;
}
notifyViews();
}
public void updateAgents() {
// Iterator<AbstractAgent> it = agents.iterator();
// while(it.hasNext()) {
// AbstractAgent nextAgent = it.next();
// nextAgent.act();
// }
for(AbstractAgent agent : agents) {
agent.act();
}
}
#Override
public void startSimulation() {
new Thread(this).start();
System.out.println("Running Simulation");
}
#Override
public void stopSimulation() {
running = false;
System.out.println("Simulation has stoped");
}
#Override
public void resetSimulation() {
System.out.println("Model Constant set to default");
}
public void run() {
running = true;
// int loop = 0;
while(running) {
// System.out.println("loop: "+ loop);
// loop++;
simulateCycles(1);
try {
Thread.sleep(5);
}
catch (Exception e) {
}
}
}
public Grid getGrid() {
return grid;
}
public List<AbstractAgent> getAgentsCollection() {
return agents;
}
public GridMapLayout getGridMayLayout() {
return Maplayout;
}
public RoomController getRoomController() {
return roomController;
}
public Constants getModelConstants() {
return modelConstants;
}
public RandomGenerator getRandGenerator() {
return randGenerator;
}
public int getCurrentSimCycle() {
return currentSimCycle;
}
public Statistics getStats() {
return stats;
}
}
This is a characteristic of time-stepped agent-based modeling. Since each of n agents can in principle interact with any of the other agents, there are n choose 2 interactions to be evaluated at each time step, which grows as O(n2). Your basic choices are: 1) keep the number of agents small; 2) increase the size of your time steps (which usually introduces modeling errors due to the coarser approximation of what's happening); 3) "localize" the scope of interactions (which may or may not be realistic for what you're modeling); or 4) rewrite your model to use discrete event scheduling rather than time stepping.
I am beginner in Selenium, there are two separate .xls file file one for GmailTestSuite.xls and other for objectrepository.xls.
I have created MainClass, in it I have written a code which read both .xls file, also I've open the driver in it and perform operation. But problem is that it continuously open new driver but don't perform any operation.
Please suggest and let me know where I'm going wrong.
public class MainClass {
static Properties properties= null;
public static void main(String[] args) throws IOException, BiffException{
// TODO Auto-generated method stub
ReadPropertyFile readConfigFile= new ReadPropertyFile();
properties= readConfigFile.loadPropertiess();
ExcelHandler testSuite= new ExcelHandler("D:\\GmailTestSuite.xls", "Suite");
testSuite.columnData();
int rowCount= testSuite.rowCount();
System.out.println("Total Rows="+rowCount);
for(int i=1;i<rowCount;i++)
{
String executable= testSuite.readCell(testSuite.getCell("Executable"), i);
System.out.println("Executable="+executable);
if(executable.equalsIgnoreCase("y")){
// exe. the process
String scenarioName= testSuite.readCell(testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name="+scenarioName);
ExcelHandler testScenarios= new ExcelHandler("D:\\GmailTestSuite.xls", scenarioName);
int rowWorkBook1= testScenarios.rowCount();
for(int j=1; j<rowWorkBook1;j++){
String framWork= testScenarios.readCell(testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(testScenarios.getCell("Operation"), j); //SendKey
String value= testScenarios.readCell(testScenarios.getCell("Value"), j);
System.out.println("FRMName="+framWork+",Operation="+operation+",Value="+value);
ExcelHandler objectRepository= new ExcelHandler("D:\\objectrepository.xls", "OR");
objectRepository.columnData();
int rowCount1= testSuite.rowCount();
System.out.println("Total Rows="+rowCount1);
for(int k=1;k<rowCount;k++){
String frameWorkName= objectRepository.readCell(objectRepository.getCell("Executable"), k);
String ObjectName= objectRepository.readCell(testScenarios.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(testScenarios.getCell("Locator"), k); //SendKey
System.out.println("FrameWorkName="+frameWorkName+",ObjectName="+ObjectName+",Locator="+Locator);
//ExcelHandler executeOperation = new ExcelHandler(ObjectName, operation, value);
File file= new File("D:\\softs\\FF installed\\FF18\\firefox.exe");
FirefoxBinary fb = new FirefoxBinary(file);
WebDriver driver = new FirefoxDriver(fb,new FirefoxProfile());
driver.get("https://www.gmail.com");
WebElement we = driver.findElement(By.id("Email"));
if(operation.equalsIgnoreCase("SendKey"))
{
we.sendKeys("abc#gmail.com");
we.sendKeys("si#2013");
}
if(operation.equalsIgnoreCase("Click"))
we.click();
}
}
}
}
}
A couple of guide lines for better formed code:
Break your code into methods that only do one thing each. That way it's easier to manage and nicely compartmentalized, plus you don't enter into indentation hell with such embedded loop and if structures as the one you have over here.
Use class variables for things like the WebDriver instance, so you can initialize it once and keep calling on it later.
Don't hard code text into the application, use constants. Then you only need to define the text once and can refer to it multiple times. Makes the code much easier to maintain and change, when you don't have to search and replace through entire class, after some details (like a file path) change.
Also, I'm guessing you meant to do the following:
loop the rows in objectRepository in the k-loop, instead of looping the rows in the testSuite again.
get cells from objectRepository rather than from testScenarios when reading the cells from objectRepository
Example:
public class MainClass {
private static final String BROWSER_PATH = "D:\\softs\\FF installed\\FF18\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
private static final By EMAIL_INPUT = By.id("Email");
// other constants
private WebDriver driver;
private Properties properties;
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws IOException, BiffException {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
}
private void handleScenario(String scenarioName) {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH, scenarioName);
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(testScenarios.getCell("Value"), j);
System.out.println("FRMName=" + framWork + ",Operation=" + operation +
",Value=" + value);
handleObjects(operation);
}
}
private void handleObjects(String operation) {
ExcelHandler objectRepository = new ExcelHandler(OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(objectRepository.getCell("Executable"), k);
String ObjectName = objectRepository.readCell(objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkName=" + frameWorkName +
",ObjectName=" + ObjectName + ",Locator=" + Locator);
operateWebDriver(operation);
}
}
private void operateWebDriver(String operation) {
WebElement we = driver.findElement(EMAIL_INPUT);
if (operation.equalsIgnoreCase("SendKey")) {
we.sendKeys("abc#gmail.com");
we.sendKeys("si#2013");
} else if (operation.equalsIgnoreCase("Click")) {
we.click();
}
}
}
If ExcelHandler is your own implementation, you really should move the getCell(String s) method inside the readCell() method to change the call pattern of handler.readCell(handler.getCell("foo"), i) into handler.readCell("foo", i). If it's a library you're using, you can always make a helper method:
private static String readCell(ExcelHandler handler, String cellName, int row) {
return handler.readCell(handler.getCell(cellName), row);
}
EDIT
Since you're having problems with getting WebDriver to work, simplify things and take everything else out of the equation for now. In order to do that let's ignore all the reading data from .xls files. This is where having different methods for different things makes your design shine, since you can just comment one method call instead of having to comment out 50 lines of code from your one mega method.
Changed the above code a bit (just commented call to the other methods out and omitted them from the snippet, moved the line opening the correct page into constructor and rewrote the operateWebDriver() method a bit):
public class MainClass {
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
private static final By EMAIL_INPUT = By.id("Email");
private static final By PASSWORD_INPUT = By.id("Passwd");
private static final By SIGN_IN_BUTTON = By.id("signIn");
private static final String EMAIL = "test#abc.com";
private static final String PASSWORD = "test123";
private WebDriver driver;
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws IOException, BiffException {
MainClass main = new MainClass();
//main.handleTestSuite();
main.operateWebDriver("Click", EMAIL_INPUT);
main.operateWebDriver("SendKey", EMAIL_INPUT, EMAIL);
main.operateWebDriver("Click", PASSWORD_INPUT);
main.operateWebDriver("SendKey", PASSWORD_INPUT, PASSWORD);
main.operateWebDriver("Click", SIGN_IN_BUTTON);
}
private void operateWebDriver(String operation, By element) {
operateWebDriver(operation, element, null);
}
private void operateWebDriver(String operation, By element, String keys) {
WebElement we = driver.findElement(element);
if (operation.equalsIgnoreCase("SendKey")) {
we.sendKeys(keys);
} else if (operation.equalsIgnoreCase("Click")) {
we.click();
}
}
}
Then once you get WebDriver working, you can start reading the data from the files and using it to operate WebDriver.
#user2092132- You require to make changes on two places in your code
1: Insert new line after line- System.out.println("Total Rows="+rowCount);
WebDriver driver = null;
2:Change line from: WebDriver driver = new FirefoxDriver(fb,new FirefoxProfile());
To: driver = new FirefoxDriver(fb,new FirefoxProfile());
Above two changes should resolve initiating new instacne of FF each time.
Programme class which contains a code and module(s)
import java.util.ArrayList;
public class Programme {
private ArrayList<String> modules = new ArrayList<String>();
private String ProgrammeCode;
public Programme(String ProgrammeName) {
this.ProgrammeCode = ProgrammeName;
if (modules.size() > 0) {
modules.clear(); //clear if something in modules
}
}
public Programme(String programmeCode, ArrayList<String> moduleList) {
this.ProgrammeCode = programmeCode;
modules = moduleList;
}
public void addModule(String name) {
if (name != null && !name.equals("")) {
modules.add(name);
}
}
public String getProgrammeCode() {
return ProgrammeCode;
}
public ArrayList<String> getModules() {
return modules;
}
public int getModuleCount() {
return modules.size();
}
}
This is in the class that reads csv files and stores them into type Programme, but i have a problem adding the strings into modules.
public ArrayList<Programme> loadProgrammes() {
ArrayList<String> modules = new ArrayList<String>(); //.... modules are being read from
//a csv file and have done multiple tests and its working correctly
modules.add(".....");
//PROBLEM HERE
programmes.add(new Programme(programmeStrings.get(i).get(0), modules));
//this displays as i want it to e.g. when added:3:[MA4102, CS4092, CS4162]
System.out.print("when added:" + programmes.get(i).getModuleCount() + ":" + modules);
//where as this doesn't work e.g. //Finished list:3 //LM023 0 []
//LM051 0 [] //LM110 0 []
System.out.println("\nFinished list:" + programmes.size());
for (int t = 0; t < programmes.size(); t++) {
System.out.println(programmes.get(t).getProgrammeCode() + " " + programmes.get(t).getModuleCount() + " "
+ programmes.get(t).getModules());
}
return programmes;
}
I'm not sure what is going wrong. Why isn't it adding the modules to the programme object