Suppose we have a Java Swings application, which has been used to run Selenium WebDriver tests using Maven project
The Swings application has 3 components:
'Run Tests' button : To start the execution of tests by calling a Windows batch file containing 'mvn test site' command
'Stop Tests' button : I need help to implement the functionality of this button
Text Area: To show the console output of a batch file called through 'Run Tests' button
My scenario is that I start the execution of Selenium WebDriver tests by clicking 'Run Tests' button and its output will be displayed in the Text area attached to the application. Now, suppose in-between the execution of tests I want to click on 'Stop Tests' button and tests execution should stop, just like 'Terminate' button works on Eclipse.
Here is the code I am using
startExecutionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
//startExecutionButton.setEnabled(false);
startExecutionButton.setText("Tests Running...");
startExecutionButton.setBackground(Color.GRAY);
String applicationURL = applicationUrlTextField.getText().trim();
String username = usernameTextField.getText().trim();
String password = passwordTextField.getText().trim();
String spreadsheetPath = spradsheetLocationTextField.getText().trim();
String testsType= testsTypeComboBox.getSelectedItem().toString();
String country = countryComboBox.getSelectedItem().toString();
// Create and overwrite properties file
List<String> lines = (List) Arrays.asList("applicationURL="+applicationURL, "username="+username,"password="+password,"sheetName="+testsType+"-"+country,"searchString=GHS_CLASS_"+country,"maxWaitTimeToPOLLElement=5","maxWaitTimeToFindElement=40","host=localhost","browserName=firefox","Time_Limit_To_Generate_Chemical=15");
Path configPath = Paths.get(getFileLocation("config.properties"));
try {
if(!configPath.toString().equals("")){
Files.deleteIfExists(configPath);
}
Files.write(configPath, lines, Charset.forName("UTF-8"));
} catch (IOException e1) {
e1.printStackTrace();
}
// Overwrite the spreadsheet
Path spreadsheet = Paths.get(getFileLocation("GenerateChemicalTest.xlsx"));
try {
if(!spreadsheet.toString().equals("")){
Files.deleteIfExists(spreadsheet);
}
Files.copy(new File(spreadsheetPath).toPath(), spreadsheet);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
printLog();
} catch (HeadlessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
private void printLog() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
// Open command prompt and start tests execution
// Process p;
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\\mavenTest.bat");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
//System.out.println(probuilder.environment().toString());
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
thread.start();
}
Click here for 'Swings application UI'
mavenTest.bat code
cd C:\Hazox\AutoTestHazox
C:
mvn test site
Related
I have created a java gui which takes values from the user send it to python file for processing and then displays the output from the python file onto the java gui. This is working perfectly on eclipse but when i exported it into a jar file the output is not displayed. I've seen a bunch of other questions like this but they do not give a solution that would help me.
This is how i connect my python script to java.
public void connection(String name)
{
ProcessBuilder pb= new ProcessBuilder("python","recomold.py","--movie_name",name);
///System.out.println("running file");
Process process = null;
try {
process = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int err = 0;
try {
err = process.waitFor();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// System.out.println("any errors?"+(err==0 ? "no" : "yes"));
/* try {
System.out.println("python output "+ output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
try {
matches.setText(output(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try{
br= new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
//descp.setText("<html><br/><html>");
//sb.append("\n");
}
}
finally
{
br.close();
}
return sb.toString();
}
I'm designing JMeter scenario which implies executing a certain .jar file via OS Process Sampler element. My Java code has while loop which basically checks a certain mailbox for a letter with a certain subject. Loop waits until finds one (emails are always delivered with roughly 3 minutes delay), parses it and writes some data to .txt file.
If I run this .jar directly from cmd then the code works as expected. But if I run it via JMeter OS Process Sampler then it never creates a file for me. I do see that email is delivered to inbox, so expect it to be parsed and .txt created.
At first I suspected that JMeter finishes Java scenario without waiting for while loop to execute. Then I put OS Process Sampler in a separate Thread and added a huge delay for this thread in order to wait and make 100% sure that email is delivered and Java only need to parse it but it does not help.
View Results Tree never shows any errors.
Here is my OS Process Sampler: https://www.screencast.com/t/LomYGShJHAkS
This is what I execute via cmd and it works as expected: java -jar mailosaurJavaRun.jar email533.druzey1a#mailosaur.in
And here is my code (it does not looks good but it works):
public class Run {
public static void main(String[] args) {
MailosaurHelper ms = new MailosaurHelper();
String arg1 = ms.getFirstLinkInEmail(args[0]);
BufferedWriter output = null;
try {
File file = new File("url.txt");
output = new BufferedWriter(new FileWriter(file));
output.write(arg1);
} catch ( IOException e ) {
e.printStackTrace();
} finally {
if ( output != null ) {
try {
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class MailosaurHelper {
protected final String API_KEY = "b3e4d2b193b5eb2";
protected final String MAILBOX_ID = "d1uzey1a";
public MailboxApi getEmailBox() {
return new MailboxApi(MAILBOX_ID, API_KEY);
}
public String getFirstLinkInEmail(String email) {
MailosaurHelper ms = new MailosaurHelper();
String link = "";
if (link.equals("") || link.isEmpty()) {
try {
Thread.sleep(3000);
link = ms.getAllEmailsByReceipent(email)[0].html.links[0]
.toString();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return link;
}
public Email[] getAllEmailsByReceipent(String recepient) {
try {
int ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(recepient).length;
while (ifArrayIsEmpty == 0) {
try {
Thread.sleep(3000);
ifArrayIsEmpty = getEmailBox().getEmailsByRecipient(
recepient).length;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (MailosaurException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Email[] listOfEmails = null;
try {
listOfEmails = getEmailBox().getEmailsByRecipient(recepient);
} catch (MailosaurException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listOfEmails;
}
The bottom line is that I need to parse Mailosaur email, retrieve URL from it and use it further. Any other suggestion on how to do that using Jmeter/Java/Mailosaur are appreciated.
You don't need cmd in here, but if you're adamant to stick with it - use /C key when you call it.
Then, are your sure you're looking for your file in the right place?
According to documentation:
By default the classes in the java.io package always resolve relative
pathnames against the current user directory. This directory is named
by the system property user.dir, and is typically the directory in
which the Java virtual machine was invoked.
Check it thoroughly, BTW - you should see it in your sampler result.
My program is supposed to search for a computer name and update the computer name value in the same instance of the GUI that it was searched in. If I launch the application and search for the computer name and hit search, it won't appear in the same instance. If I hit run again, the computer name I just searched for appears in the label in the new instance of the GUI.
So basically at the moment I have to launch a new instance of the GUI to see the updated computer name. Any help is appreciated. I've been stuck on this for a long time now.
Relevant Code:
try (BufferedReader br = new BufferedReader(new FileReader("resultofbatch.txt")))
{
final Pattern PATTERN = Pattern.compile("CN=([^,]+).*");
try {
while ((sCurrentLine = br.readLine()) != null) {
String[] tokens = PATTERN.split(","); //This will return you a array, containing the string array splitted by what you write inside it.
//should be in your case the split, since they are seperated by ","
// System.out.println(sCurrentLine);
CN = sCurrentLine.split("CN=",-1)[1].split(",",-1)[0];
System.out.println(CN);
testLabel.setText(CN);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MISControlPanel window = new MISControlPanel();
window.frame.setVisible(true);
//testLabel.setText(CN);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
You can view the full class here: http://pastebin.com/8hH1TMD3
I have a method that allows me to type part of the computer name into a jtextfield and I submit via jbutton. The cmd prompt successfully gives me the full computer name. So if I typed 111255 the command prompt will output coud111255. Query I'm using (#dsquery computer -name *%1)
This part works great. My issue is pulling the full computer name out of the batch file and assigning it to a java variable. I'm trying to append the full computer name to textArea, but it is only pulling the hardcoded value from here:
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";)
Any Suggestions on how to get the full computer name appended to textArea?
sendParam() passes half of computer name into batch script to find full computer name.
public static void sendParam(){
try{
String val = MISControlPanel.textField.getText(); //Put whatever you want to pass as a prefix in place of "Computer"
jLabel1.setText(val);
Process p ;
p = Runtime.getRuntime().exec("cmd /c start c:\\computerQuery.bat "+val+"");
}
catch(Exception e){
e.printStackTrace();
}
}
StringBuffer sbuffer = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(p
.getInputStream()));
try {
while ((line = in.readLine()) != null) {
System.out.println(line);
//textArea.append(line);
String dn = "CN=FDCD111304,OU=Workstations,OU=SIM,OU=Accounts,DC=FL,DC=NET";
LdapName ldapName = new LdapName(dn);
String commonName = (String) ldapName.getRdn(ldapName.size() - 1).getValue();
textArea.append(String.format(" %s%n", commonName));
//textArea.setText(ComputerQuery.val);
selectedComputerFromAD.setText(commonName);
selectedComputerFromAD.setFont(new Font("Tahoma", Font.BOLD, 14));
selectedComputerFromAD.setForeground(Color.RED);
selectedComputerFromAD.setBounds(349, 84, 102, 19);
frame.getContentPane().add(selectedComputerFromAD);
}
ComputerQuery.sendParam();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InvalidNameException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally
{
try {
fw.close();
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ComputerQuery.sendParam();
}
});
I'm have created a java app that reads files from a FTP server.I have tested this app locally(with success) and now i have deployed this app to heroku.
This is a piece a my code :
public void CSVListing() {
String[] fnames = {"1","2","3","4"};
try {
try {
client.connect(host);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
//----------------------------------------
boolean login = false;
try {
login = client.login(user, pass);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
if (login) {
System.out.println("Login success...");
//boolean logout = false;
System.out.println("ready to work");
}
else {
System.out.println("Login fail...");
}
//----------------------------------------
System.out.println(client.printWorkingDirectory());
fnames = client.listNames();
System.out.println("FNAMES ARE" + fnames);
for(String s: fnames){
System.out.println(s);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
......................................................
I have locally executed this code and it gives me a list of the files, but when I execute this on my heroku app online >>fnames = client.listNames();<< returns null according to my logs. I'm accessing the same FTP host in both executions (locally and online).
Can somebody help me and tell me where i'm wrong?
Did you check your permissions? Awhile ago I pass through something similar, the problem was that the user connecting to the FTP server didn't have permission to download files.