unable to refresh a jtable more than one time - java

In my jFrame,I created a table that contains the patients' list and a button that allows to refresh the table on action. When I click the refresh button for the firt time, the list is displayed in the table. Howerver, when I press it for a second time it doesn't work any more and the table isn't able to be refreshed.
Any idea about the problem please?
this is the code of the refresh button:
public class Interface extends javax.swing.JFrame{
private void RefreshActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)worklisttable.getModel();
int rowCount = model.getRowCount();
for (int i = rowCount - 1; i >= 0; i--) {
model.removeRow(i);
}
model.fireTableDataChanged();
GetMwl_3.main(args);
}
public static void main(String args[]) {
......
}
}
GetMwl_3.java : allows to retrieve the patient list from the server
public class GetMwl_3 {
private String[] args;
/**
* #param args
*/
public static void main(String[] args/*,String aet, String host, Integer port*/) {
new GetMwl_3(/*aet,host,port*/);
}
private static final int[] RETURN_KEYS = {
Tag.AccessionNumber,
Tag.ReferringPhysicianName,
Tag.PatientName,
Tag.PatientID,
Tag.PatientBirthDate,
Tag.PatientSex,
Tag.PatientWeight,
Tag.MedicalAlerts,
Tag.Allergies,
Tag.PregnancyStatus,
Tag.StudyInstanceUID,
Tag.RequestingPhysician,
Tag.RequestingService,
Tag.RequestedProcedureDescription,
Tag.AdmissionID,
Tag.SpecialNeeds,
Tag.CurrentPatientLocation,
Tag.PatientState,
Tag.RequestedProcedureID,
Tag.RequestedProcedurePriority,
Tag.PatientTransportArrangements,
Tag.PlacerOrderNumberImagingServiceRequest,
Tag.FillerOrderNumberImagingServiceRequest,
Tag.ConfidentialityConstraintOnPatientDataDescription,
};
private static final int[] SPS_RETURN_KEYS = {
Tag.Modality,
Tag.RequestedContrastAgent,
Tag.ScheduledStationAETitle,
Tag.ScheduledProcedureStepStartDate,
Tag.ScheduledProcedureStepStartTime,
Tag.ScheduledPerformingPhysicianName,
Tag.ScheduledProcedureStepDescription,
Tag.ScheduledProcedureStepID,
Tag.ScheduledStationName,
Tag.ScheduledProcedureStepLocation,
Tag.PreMedication,
Tag.ScheduledProcedureStepStatus
};
private static final String[] LE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian };
private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };
private Device device;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private final NetworkConnection remoteConn = new NetworkConnection();
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private final DicomObject keys = new BasicDicomObject();
private final DicomObject spsKeys = new BasicDicomObject();
private Association assoc;
private int priority = 0;
private int cancelAfter = Integer.MAX_VALUE;//ÐœÐ°ÐºÑ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑтво Ñтрок
private boolean fuzzySemanticPersonNameMatching;
private Component emptyLabel;
public GetMwl_3(/*String aet, String host, Integer port*/) {
String name = "DCMMWL";
device = new Device(name);
NewThreadExecutor executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAETitle(name);
for (int i = 0; i < RETURN_KEYS.length; i++) {
keys.putNull(RETURN_KEYS[i], null);
}
keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
new BasicDicomObject());
keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
spsKeys.putNull(SPS_RETURN_KEYS[i], null);
}
spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
new BasicDicomObject());
/////////
Properties pacs = new Properties();
InputStream file = null;
File thefile = new File("C:\\properties\\save.properties");
if (thefile.exists()){
try {
file = new FileInputStream("C:\\properties\\save.properties");
// load a properties file
pacs.load(file);
// get the property value and print it out
remoteAE.setAETitle( pacs.getProperty("aethl7"));
remoteConn.setHostname(pacs.getProperty("hosthl7"));
remoteConn.setPort(Integer.parseInt(pacs.getProperty("porthl7")));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,"20131030");
setTransferSyntax(LE_TS);
long t1 = System.currentTimeMillis();
try {
assoc = ae.connect(remoteAE, executor);
} catch (Exception e) {
// System.err.println("ERROR: Failed to establish association:");
//e.printStackTrace(System.err);
//jLabel7.setText("ERROR: Failed to establish association");
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients ne peut pas être retirée");
//System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
//jLabel6.setText("Connected to " + remoteAE + " in "
// + ((t2 - t1) / 1000F) + "s");
try {
List<DicomObject> result = query();
long t3 = System.currentTimeMillis();
System.out.println("Received " + result.size()
+ " matching entries in " + ((t3 - t2) / 1000F) + "s");
for(DicomObject dcm : result) {
worklist.main(args,
dcm.getString(Tag.PatientID),
dcm.getString(Tag.AccessionNumber),
dcm.getString(Tag.PatientName),
dcm.getString(Tag.PatientBirthDate),
dcm.getString(Tag.PatientSex),
dcm.getString(Tag.ReferringPhysicianName)
);
}
javax.swing.JOptionPane.showMessageDialog(null,"Liste des patients retirée avec succée");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assoc.release(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Released connection to " + remoteAE);
}
}
public void setTransferSyntax(String[] ts) {
TransferCapability tc = new TransferCapability(
UID.ModalityWorklistInformationModelFIND, ts,
TransferCapability.SCU);
if (fuzzySemanticPersonNameMatching)
tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
ae.setTransferCapability(new TransferCapability[]{tc});
}
public void addSpsMatchingKey(int tag, String value) {
spsKeys.putString(tag, null, value);
}
public List<DicomObject> query() throws IOException, InterruptedException {
TransferCapability tc = assoc.getTransferCapabilityAsSCU(
UID.ModalityWorklistInformationModelFIND);
if (tc == null) {
throw new NoPresentationContextException(
"Modality Worklist not supported by "
+ remoteAE.getAETitle());
}
DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
priority, keys, tc.getTransferSyntax()[0], cancelAfter);
List<DicomObject> result = new ArrayList<DicomObject>();
while (rsp.next()) {
DicomObject cmd = rsp.getCommand();
if (CommandUtils.isPending(cmd)) {
DicomObject data = rsp.getDataset();
result.add(data);
}
}
return result;
}
}
worklist.java :
public class worklist extends Interface{
public worklist(){
}
public static void main(String[] args,
String PatientID,
String accessingNumber,
String PatientName,
String BirthDate,
String sex,
String referringPhysician
) {
DefaultTableModel modelw=(DefaultTableModel)worklisttable.getModel();
modelw.setColumnIdentifiers(new String[]{"ID Patient"," Nom Patient","Date de Naissance","Sexe"});
DefaultTableCellRenderer centerRenderer= new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment(JLabel.CENTER);
worklisttable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
for (int j = 0 ; j< worklisttable.getColumnCount(); j++)
{
worklisttable.getColumnModel().getColumn(j).setCellRenderer(centerRenderer);
}
row=new Object[4];
row[0]=PatientID;
row[1]=PatientName;
row[2]=BirthDate;
row[3]=sex;
modelw.addRow(row);
}
}

Related

Why does the mean method does not work correctly?

I have the following class imp with inner class ScoringSummaryImplementation, when I tested the mean() method alone it works correctly, but when I test it as I show in the main method the answer goes incorrectly, I need to know the reason:
public class imp implements Normalizer {
public static List<BigDecimal> dataToBeNormalized = new ArrayList<>();
#Override
public ScoringSummary zscore(Path csvPath, Path destPath, String colToStandardize) {
ScoringSummary scoringObejct = new ScoringSummaryImplementation();
if (!Files.exists(csvPath)) {
throw new IllegalArgumentException("source file not found");
}
try {
readDataToBeNormalized(csvPath, destPath, colToStandardize);
} catch (IOException ex) {
Logger.getLogger(imp.class.getName()).log(Level.SEVERE, null, ex);
} catch (CsvValidationException ex) {
Logger.getLogger(imp.class.getName()).log(Level.SEVERE, null, ex);
}
//Z-score
for (int i = 0; i < dataToBeNormalized.size(); i++) {
BigDecimal sub = (dataToBeNormalized.get(i).subtract(scoringObejct.mean()));
try {
BigDecimal divide = sub.divide(scoringObejct.standardDeviation(), 2, RoundingMode.HALF_EVEN);
dataToBeNormalized.set(i, divide);
} catch (ArithmeticException e) {
}
}
return scoringObejct;
}
private void readDataToBeNormalized(Path csvPath, Path destPath, String colToStandardize) throws FileNotFoundException, IOException, CsvValidationException {
int indexOfTheCol = -1;
CSVReader reader = new CSVReader(new FileReader(csvPath.toString()));
String[] header = reader.readNext();
for (int i = 0; i < header.length; i++) {
if (header[i].equalsIgnoreCase(colToStandardize)) {
indexOfTheCol = i;
}
}
if (indexOfTheCol == -1) {
throw new IllegalArgumentException("column " + colToStandardize + " not found");
}
String[] values;
while ((values = reader.readNext()) != null) {
dataToBeNormalized.add(new BigDecimal(values[indexOfTheCol]));
}
}
//Inner class to implement ScoringSummary
public static class ScoringSummaryImplementation implements ScoringSummary {
#Override
public BigDecimal mean() {
BigDecimal sum = new BigDecimal("0");
BigDecimal sizeOfTheList = new BigDecimal(dataToBeNormalized.size());
for (int i = 0; i < dataToBeNormalized.size(); i++) {
sum = sum.add(dataToBeNormalized.get(i));
}
sum.divide(sizeOfTheList, 2, RoundingMode.HALF_EVEN);
return sum.divide(sizeOfTheList, 2, RoundingMode.HALF_EVEN);
}
}
}
// test in the main:
public class Test {
public static void main(String [] args){
Path p = Paths.get("C:\\Users\\DELL\\Documents\\GitHub\\J2EE\\demo\\src\\main\\java\\com\\mycompany\\demo\\d.csv");
Path p2 = Paths.get("C:\\Users\\DELL\\Documents\\GitHub\\J2EE\\demo\\src\\main\\java\\com\\mycompany\\demo\\des.csv");
Normalizer n1 = new imp ();
ScoringSummary n2 = n1.zscore(p, p2, "age");
BigDecimal mean = n2.mean();
System.out.println(mean);
}
}
Here is output:
0.82
Here is age column:
|age |
|5434|
|42423|
|54534|
|3333|

Could not render red5 recorded media stream

I have problem of playing back the recorded media file from red5 published stream, following is my code. I could see a file called out.flv is created, but this out.flv can not be played back.
public class Red5ClientTest {
private static Timer timer;
private static RTMPClient client;
private static String sourceStreamName;
private static int videoTs;
private static int audioTs;
private static FLVWriter writer;
private static int bytesRead =0;
public static void main(String[] args) throws IOException {
String sourceHost = "localhost";
int sourcePort = 1935;
String sourceApp = "oflaDemo";
sourceStreamName = "myStream";
timer = new Timer();
client = new RTMPClient();
String path = "c:\\temp\\out.flv";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
writer = new FLVWriter(file,true);
client.setStreamEventDispatcher(new StreamEventDispatcher());
client.setStreamEventHandler(new INetStreamEventHandler() {
public void onStreamEvent(Notify notify) {
System.out.printf("onStreamEvent: %s\n", notify);
ObjectMap<?, ?> map = (ObjectMap<?, ?>) notify.getCall().getArguments()[0];
String code = (String) map.get("code");
System.out.printf("<:%s\n", code);
if (StatusCodes.NS_PLAY_STREAMNOTFOUND.equals(code)) {
System.out.println("Requested stream was not found");
client.disconnect();
}
else if (StatusCodes.NS_PLAY_UNPUBLISHNOTIFY.equals(code)
|| StatusCodes.NS_PLAY_COMPLETE.equals(code)) {
System.out.println("Source has stopped publishing or play is complete");
client.disconnect();
}
}
});
client.setConnectionClosedHandler(new Runnable() {
public void run() {
if (writer != null) {
writer.close();
}
System.out.println("Source connection has been closed, proxy will be stopped");
System.exit(0);
}
});
client.setExceptionHandler(new ClientExceptionHandler() {
#Override
public void handleException(Throwable throwable) {
throwable.printStackTrace();
System.exit(1);
}
});
// connect the consumer
Map<String, Object> defParams = client.makeDefaultConnectionParams(sourceHost, sourcePort,
sourceApp);
// add pageurl and swfurl
defParams.put("pageUrl", "");
defParams.put("swfUrl", "app:/Red5-StreamRelay.swf");
// indicate for the handshake to generate swf verification data
client.setSwfVerification(true);
// connect the client
client.connect(sourceHost, sourcePort, defParams, new IPendingServiceCallback() {
public void resultReceived(IPendingServiceCall call) {
System.out.println("connectCallback");
ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
String code = (String) map.get("code");
if ("NetConnection.Connect.Rejected".equals(code)) {
System.out.printf("Rejected: %s\n", map.get("description"));
client.disconnect();
//proxy.stop();
}
else if ("NetConnection.Connect.Success".equals(code)) {
// 1. Wait for onBWDone
timer.schedule(new BandwidthStatusTask(), 2000L);
Object result = call.getResult();
System.out.println("Red5ClientTest.main()");
}
else {
System.out.printf("Unhandled response code: %s\n", code);
}
}
});
// keep sleeping main thread while the proxy runs
// kill the timer
//timer.cancel();
System.out.println("Stream relay exit");
}
/**
* Handles result from subscribe call.
*/
private static final class SubscribeStreamCallBack implements IPendingServiceCallback {
public void resultReceived(IPendingServiceCall call) {
System.out.println("resultReceived: " + call);
Object result = call.getResult();
System.out.println("results came {}" + result);
}
}
private static final class StreamEventDispatcher implements IEventDispatcher {
public void dispatchEvent(IEvent event) {
System.out.println("ClientStream.dispachEvent()" + event.toString());
try {
//RTMPMessage build = RTMPMessage.build((IRTMPEvent) event);
IRTMPEvent rtmpEvent = (IRTMPEvent) event;
ITag tag = new Tag();
tag.setDataType(rtmpEvent.getDataType());
if (rtmpEvent instanceof VideoData) {
videoTs += rtmpEvent.getTimestamp();
tag.setTimestamp(videoTs);
}
else if (rtmpEvent instanceof AudioData) {
audioTs += rtmpEvent.getTimestamp();
tag.setTimestamp(audioTs);
}
IoBuffer data = ((IStreamData) rtmpEvent).getData().asReadOnlyBuffer();
tag.setBodySize(data.limit());
tag.setBody(data);
try {
writer.writeTag(tag);
} catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("writting....");
}
catch (Exception e) {//IOException
e.printStackTrace();
}
}
}
private static final class BandwidthStatusTask extends TimerTask {
#Override
public void run() {
// check for onBWDone
System.out.println("Bandwidth check done: " + client.isBandwidthCheckDone());
// cancel this task
this.cancel();
// create a task to wait for subscribed
timer.schedule(new PlayStatusTask(), 1000L);
// 2. send FCSubscribe
client.subscribe(new SubscribeStreamCallBack(), new Object[] { sourceStreamName });
}
}
private static final class PlayStatusTask extends TimerTask {
#Override
public void run() {
// checking subscribed
System.out.println("Subscribed: " + client.isSubscribed());
// cancel this task
this.cancel();
// 3. create stream
client.createStream(new CreateStreamCallback());
}
}
/**
* Creates a "stream" via playback, this is the source stream.
*/
private static final class CreateStreamCallback implements IPendingServiceCallback {
public void resultReceived(IPendingServiceCall call) {
System.out.println("resultReceived: " + call);
int streamId = ((Number) call.getResult()).intValue();
System.out.println("stream id: " + streamId);
// send our buffer size request
if (sourceStreamName.endsWith(".flv") || sourceStreamName.endsWith(".f4v")
|| sourceStreamName.endsWith(".mp4")) {
client.play(streamId, sourceStreamName, 0, -1);
}
else {
client.play(streamId, sourceStreamName, -1, 0);
}
}
}
}
what could I be doing possibly wrong here?
Finally got it
public class TeqniRTMPClient {
private static final Logger logger = LoggerFactory.getLogger(MyRtmpClient.class);
public static void main(String args[]) throws IOException {
TeqniRTMPClient client = new TeqniRTMPClient("localhost", 1935, "oflaDemo", "myStream");
client.recordStream();
}
private RTMPClient client;
private ITagWriter writer;
private String sourceHost;
private int sourcePort;
private String sourceApp;
private String sourceStreamName;
private int lastTimestamp;
private int startTimestamp = -1;
public TeqniRTMPClient(String sourceHost, int sourcePort, String sourceApp,
String sourceStreamName) {
super();
this.sourceHost = sourceHost;
this.sourcePort = sourcePort;
this.sourceApp = sourceApp;
this.sourceStreamName = sourceStreamName;
}
public void recordStream() throws IOException {
client = new RTMPClient();
String path = "c:\\temp\\out.flv";
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
FLVService flvService = new FLVService();
flvService.setGenerateMetadata(true);
try {
IStreamableFile flv = flvService.getStreamableFile(file);
writer = flv.getWriter();
}
catch (Exception e) {
throw new RuntimeException(e);
}
client.setStreamEventDispatcher(new StreamEventDispatcher());
client.setStreamEventHandler(new INetStreamEventHandler() {
public void onStreamEvent(Notify notify) {
System.out.printf("onStreamEvent: %s\n", notify);
ObjectMap<?, ?> map = (ObjectMap<?, ?>) notify.getCall().getArguments()[0];
String code = (String) map.get("code");
System.out.printf("<:%s\n", code);
if (StatusCodes.NS_PLAY_STREAMNOTFOUND.equals(code)) {
System.out.println("Requested stream was not found");
client.disconnect();
}
else if (StatusCodes.NS_PLAY_UNPUBLISHNOTIFY.equals(code)
|| StatusCodes.NS_PLAY_COMPLETE.equals(code)) {
System.out.println("Source has stopped publishing or play is complete");
client.disconnect();
}
}
});
client.setExceptionHandler(new ClientExceptionHandler() {
#Override
public void handleException(Throwable throwable) {
throwable.printStackTrace();
System.exit(1);
}
});
client.setConnectionClosedHandler(new Runnable() {
public void run() {
if (writer != null) {
writer.close();
}
System.out.println("Source connection has been closed, proxy will be stopped");
System.exit(0);
}
});
// connect the consumer
Map<String, Object> defParams = client.makeDefaultConnectionParams(sourceHost, sourcePort,
sourceApp);
// add pageurl and swfurl
defParams.put("pageUrl", "");
defParams.put("swfUrl", "app:/Red5-StreamRelay.swf");
// indicate for the handshake to generate swf verification data
client.setSwfVerification(true);
// connect the client
client.connect(sourceHost, sourcePort, defParams, new IPendingServiceCallback() {
public void resultReceived(IPendingServiceCall call) {
System.out.println("connectCallback");
ObjectMap<?, ?> map = (ObjectMap<?, ?>) call.getResult();
String code = (String) map.get("code");
if ("NetConnection.Connect.Rejected".equals(code)) {
System.out.printf("Rejected: %s\n", map.get("description"));
client.disconnect();
}
else if ("NetConnection.Connect.Success".equals(code)) {
// 1. Wait for onBWDone
client.createStream(new CreateStreamCallback());
Object result = call.getResult();
System.out.println("Red5ClientTest.main()");
}
else {
System.out.printf("Unhandled response code: %s\n", code);
}
}
});
}
class CreateStreamCallback implements IPendingServiceCallback {
public void resultReceived(IPendingServiceCall call) {
System.out.println("resultReceived: " + call);
int streamId = ((Number) call.getResult()).intValue();
System.out.println("stream id: " + streamId);
// send our buffer size request
if (sourceStreamName.endsWith(".flv") || sourceStreamName.endsWith(".f4v")
|| sourceStreamName.endsWith(".mp4")) {
client.play(streamId, sourceStreamName, 0, -1);
}
else {
client.play(streamId, sourceStreamName, -1, 0);
}
}
}
class StreamEventDispatcher implements IEventDispatcher {
private int videoTs;
private int audioTs;
public void dispatchEvent(IEvent event) {
System.out.println("ClientStream.dispachEvent()" + event.toString());
try {
IRTMPEvent rtmpEvent = (IRTMPEvent) event;
logger.debug("rtmp event: " + rtmpEvent.getHeader() + ", "
+ rtmpEvent.getClass().getSimpleName());
if (!(rtmpEvent instanceof IStreamData)) {
logger.debug("skipping non stream data");
return;
}
if (rtmpEvent.getHeader().getSize() == 0) {
logger.debug("skipping event where size == 0");
return;
}
byte dataType = rtmpEvent.getDataType();
ITag tag = new Tag();
tag.setDataType(dataType);
if (rtmpEvent instanceof VideoData) {
VideoData video = (VideoData) rtmpEvent;
FrameType frameType = video.getFrameType();
videoTs += rtmpEvent.getTimestamp();
tag.setTimestamp(videoTs);
}
else if (rtmpEvent instanceof AudioData) {
audioTs += rtmpEvent.getTimestamp();
tag.setTimestamp(audioTs);
}
IoBuffer data = ((IStreamData) rtmpEvent).getData().asReadOnlyBuffer();
tag.setBodySize(data.limit());
tag.setBody(data);
try {
writer.writeTag(tag);
}
catch (Exception e) {
throw new RuntimeException(e);
}
System.out.println("writting....");
}
catch (Exception e) {//IOException
e.printStackTrace();
}
}
}
}

How to locate or work with different locator in selemium webdrier frameowrk?

I am beginner in selenium webdriver, I am trying to work with different locator by reading excel sheet but in these it take only one data put it in one field by finding locator "id", and when it come to the second text field for this we are using locator by "Xpath" but its not taking. So, my question is how can I work with different locator also by don't using switch case if possible.
Below are my code:
public class MainClass {
private static final String BROWSER_PATH = "D:\\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";
// other constants
private WebDriver driver;
private Properties properties;
/*private WebElement we;*/
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() throws BiffException, IOException {
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) throws BiffException, IOException {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH);
testScenarios.setSheetName("Login");
testScenarios.columnData();
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("FRMNameKK=" + framWork + ",Operation=" + operation +
",Value=" + value);
handleObjects(operation,value,framWork);
}
}
private void handleObjects(String operation,String value,String framWork) throws BiffException, IOException
{
System.out.println("HandleObject--> "+framWork);
ExcelHandler objectRepository = new ExcelHandler(OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows in hadleObject=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(objectRepository.getCell("FrameworkName"), k);
String ObjectName = objectRepository.readCell(objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkNameV=" + frameWorkName +
",ObjectName=" + ObjectName + ",Locator=" + Locator);
if(framWork.equalsIgnoreCase(frameWorkName))
{
operateWebDriver(operation,Locator,value,ObjectName);
}
}
}
private void operateWebDriver(String operation,String Locator,String value, String objectName)
{
System.out.println("Operation execution in progress");
WebElement temp=getElement(Locator,objectName);
if (operation.equalsIgnoreCase("SendKey"))
{
temp.sendKeys(value);
}
if (operation.equalsIgnoreCase("Click"))
{
temp.click();
}
}
public WebElement getElement(String locator,String objectName)
{
WebElement temp = null;
if(locator.equalsIgnoreCase("id"))
{
temp = driver.findElement(By.id(objectName));
}else if(locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
}
if(locator.equalsIgnoreCase("link"))
{
}
return temp;
}
}
You need the Reflection. See example in 2 methods below:
import java.lang.reflect.Method;
...
#Test
public void TestAmazon() {
driver = new ChromeDriver();
driver.navigate().to("http://www.amazon.com");
String locatorType = "id";
String locatorExpression = "twotabsearchtextbox";
By locator = createLocator(locatorType, locatorExpression);
WebElement textbox = driver.findElement(locator);
textbox.sendKeys("Star Wars: The Digital Movie Collection");
textbox.sendKeys(Keys.ENTER);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
locatorType = "className";
locatorExpression = "nav-logo-link";
locator = createLocator(locatorType, locatorExpression);
driver.findElement(locator).click();
}
private By createLocator(String locatorType, final String locatorExpression) {
By locator = null;
Class<By> byClass = By.class;
Class[] argTypes = new Class[] { String.class };
try {
Method m = byClass.getDeclaredMethod(locatorType, argTypes);
try {
locator = (By)m.invoke(null,locatorExpression);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return locator;
}

Java: Android: SQLite: Doing Multiple Inserts Using a For Loop

Please review the following piece of code:
try {
db.beginTransaction();
db.execSQL(DBConstants.PRAG_FOR_KEYS_ON);
db.execSQL(DBConstants._BLDG_CREATE);
db.execSQL(DBConstants._BLDG_INDEX);
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT+x);
}
db.execSQL(DBConstants.PRAG_FOR_KEYS_OFF);
db.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
}finally{
db.endTransaction();
}
Each of the insert constants (representing a row of new data) are numbered thus:
public static final String _BLDG_INSERT0 = "<SQL insert statement>"
...all the way up to 28 ("_BLDG_INSERT28").
Is there ANY way i can execute these SQL statements in a for loop? If i can, how do i concactenate the number on to the name of the constant AND have it recognized by the java interpreter in the correct way?
Thanks!
It's not clear from the question whether you are able to change the constants. If you can, it would be better if you could put the statements in an array.
String[] _BLDG_INSERT = {"<SQL insert statement>", // 0
"<SQL insert statement>", // 1
...
"<SQL insert statement>" // 28
};
And then you can just access them like this.
for(int x = 0; x < 28; x = x+1){
db.execSQL(DBConstants._BLDG_INSERT[x]);
}
Or better still:
for(String s : DBConstants._BLDG_INSERT) {
db.execSQL(s);
}
public ArrayList<String> getAllRecord()
{
ArrayList<String> total = new ArrayList<String>();
Cursor cursor1 = null;
try
{
cursor1 = getDBobject().rawQuery(
"select * from "
+ Your table name + ";", null);
if (cursor1.moveToFirst())
{
do
{
String cid = cursor1.getString(1);
total.add(cid);
}
while (cursor1.moveToNext());
}
}
catch (Exception e)
{
System.out.println("" + TAG + " :" + e);
}
finally
{
if (cursor1 != null && !cursor1.isClosed())
{
cursor1.close();
}
}
return total;
}
This will return you all the datas according to your insertion order
Try something like this:
public class testeReflection {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException{
MyClass myClass = new MyClass();
Class aClass = MyClass.class;
for(int i = 0; i < 5; i++){
try {
Field field = aClass.getField("VAR" + i);
String s = (String)field.get(myClass);
System.out.println("myClass[" + i + "] = " + s);
} catch (NoSuchFieldException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
Logger.getLogger(testeReflection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static class MyClass{
public static final String VAR0 = "VARIAVEL 01";
public static final String VAR1 = "VARIAVEL 02";
public static final String VAR2 = "VARIAVEL 03";
public static final String VAR3 = "VARIAVEL 04";
public static final String VAR4 = "VARIAVEL 05";
}
}

Java and Hyper-V

I am trying to learn something about JAVA and the best way to do this is creating something I would actually use and know what the purpose of it is.
I am trying to communicate with HyperV (WMI Library).
For example I found the following, my question is: how to use it? I am using Netbeans to create the GUI.
http://www.paulneve.com/wlab/javadoc/org/paulneve/wlab/virtualisation/VirtualisationAccessHyperVImpl.html
Also, how to load jInterop into my project so I can use it?
Thank you.
You can use JInterop for managing all operations of HyperV.
Download JInterop from here.
Add all JInterop jar files to your project build path.
Following is an example of getting all VMs of Hyper server:
public class ManageHyperV {
static final int RETURN_IMMEDIATE = 0x10;
static final int FORWARD_ONLY = 0x20;
private static final int STOP = 0;
private static final int START = 1;
static IJIDispatch msvmServices = null;
private static IJIDispatch createCOMServer(String namespace) { //root//virtualization
JIComServer comServer;
try {
JISystem.getLogger().setLevel(Level.WARNING);
JISystem.setAutoRegisteration(true);
JISession session = JISession.createSession(domainName,userName,password);
session.useSessionSecurity(false);
comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"),hostIP,session);
IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));
//parameters to connect to WbemScripting.SWbemLocator
Object[] params = new Object[] {
new JIString(hostIP),//strServer
new JIString(namespace),//strNamespace
// new JIString("ROOT\\CIMV2"),
JIVariant.OPTIONAL_PARAM(),//strUser
JIVariant.OPTIONAL_PARAM(),//strPassword
JIVariant.OPTIONAL_PARAM(),//strLocale
JIVariant.OPTIONAL_PARAM(),//strAuthority
new Integer(0),//iSecurityFlags
JIVariant.OPTIONAL_PARAM()//objwbemNamedValueSet
};
JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
IJIDispatch wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
return wbemServices;
} catch (JIException jie) {
System.out.println(jie.getMessage());
jie.printStackTrace();
} catch (JIRuntimeException jire) {
jire.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static void getVMList() throws JIException {
String temp = "select * from Msvm_ComputerSystem";
String[] arrQuery = new String[]{temp};
for (int k=0;k<arrQuery.length;k++) {
Object[] params = new Object[] {
new JIString(arrQuery[k]),
JIVariant.OPTIONAL_PARAM(),
new JIVariant(new Integer(RETURN_IMMEDIATE + FORWARD_ONLY))
};
JIVariant[] servicesSet = msvmServices.callMethodA("ExecQuery", params);
iterateEnum(servicesSet);
}
}
private static void iterateEnum(JIVariant[] servicesSet) {
try {
IJIDispatch wbemObjectSet = (IJIDispatch) narrowObject(servicesSet[0].getObjectAsComObject());
JIVariant newEnumvariant = wbemObjectSet.get("_NewEnum");
IJIComObject enumComObject = newEnumvariant.getObjectAsComObject();
IJIEnumVariant enumVariant = (IJIEnumVariant) narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));
List<Object[]> respArr = getEnumIterations(enumVariant);
for (Object[] elements : respArr) {
JIArray aJIArray = (JIArray) elements[0];
JIVariant[] array = (JIVariant[]) aJIArray.getArrayInstance();
for (JIVariant variant : array) {
IJIDispatch wbemObjectDispatch = (IJIDispatch) narrowObject(variant.getObjectAsComObject());
JIVariant[] v = wbemObjectDispatch.callMethodA("GetObjectText_", new Object[] {});
System.out.println("----------------------------------------------------------------------");
System.out.println(v[0].getObjectAsString().getString());
System.out.println("----------------------------------------------------------------------");
}
}
} catch (JIRuntimeException e) {
e.printStackTrace();
} catch (JIException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
msvmServices = createCOMServer("root\\virtualization");
getVMList();
}
}
private static List<Object[]> getEnumIterations(IJIEnumVariant enumVariant) {
List<Object[]> list = new ArrayList<Object[]>();
int i=0;
for (i=0;i<100;i++) {
try {
list.add(enumVariant.next(1));
}catch (JIRuntimeException jre) {
break;
}
catch (JIException jie) {
break;
}
catch (Exception e) {
break;
}
}
return list;
}
Also, provide administrator username and password.
It should work.
Thanks.

Categories

Resources