Updating Value in same instance using invokeLater - java

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

Related

last object serialized gets overwritten

I am writing a program for keeping track of library books. There is an object book that includes a title, sku number, price and quantity. All the books are stored in an Array List. I'm trying to serialize the books and add new books but every time a book is added the last is overwritten.
here is the code below to load objects from save
public static void readSave() {
File stockFile = new File("inventory.txt");
try {
if(!stockFile.createNewFile() && stockFile.length() != 0) {
ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(stockFile));
int size = objIn.readInt();
for(int i = 0; i < size; i++) {
Book t = (Book) objIn.readObject();
bookList.add(t);
}
objIn.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
here is my save method and it is set to save every time the program executes.
public static void save() {
File inventoryFile = new File("inventory.txt");
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(new FileOutputStream(inventoryFile));
objOut.writeInt(bookList.size());
Iterator<Book> i = bookList.iterator();
while(i.hasNext()){
objOut.writeObject(i.next());
}
objOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
below is my main method which calls these functions
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
readSave();
CampusBookWindow window = new CampusBookWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
save();
}
});
}
My problem was when I hit the add book button I would not create a new book object for that item, but instead I was reassigning that last book object so the object last book object was erased from the bookList array list

Place to declare "throws IOException" in GUI

I am new (and German so my English is not the best :D)
I am working at a program, but I need to insert a BufferedReader & FileReader.
I am working with GUI(graphical user interface) , and I know the mistake that I have to insert a throws IOException but I honestly do not know at which position. (because it is everywhere right next to public static void main(String[] args) but this does not exist in GUI)
FileReader fr = new FileReader("pi.txt");
BufferedReader br = new BufferedReader(fr);
String zeile1 = br.readLine();
char[] c = zeile1.toCharArray();
System.out.println(c[2]);
Can somebody help me?
I have never used GUI, but you can catch it with try-catch:
try{
// your code
} catch (Exception e){
}
As suggested in comment, the best way is to catch specific exception and not the generic one.
In your case, You need:
FileReader fr;
try {
fr = new FileReader("pi.txt");
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//and
try {
String zeile1 = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
or
try {
// your code
} catch (FileNotFoundException e1) {
// log
} catch (IOException e) {
// log
}

JMeter does not execute Java code correctly if it's ran as .jar file from command line

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.

How to implement Eclipse's 'Terminate' button functaionality in Swings application

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

API Connections only working once

I am creating an application that makes calls to the Hitbox API. I am trying to get the game name (listed as category_name from a list.
Thus far, I have managed to get the game name one time during the programs running stage, however when I change where to get the game name from, the program doesn't do anything. I am at a loss as to what could cause it not to send another request to the server.
public void apiConnect(){
String channel = text.getText();
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://api.hitbox.tv/media/live/" + channel);
HttpResponse response = null;
try {
response = client.execute(request);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Get the response
BufferedReader rd = null;
try {
rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
} catch (UnsupportedOperationException | IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String line = "";
try {
while ((line = rd.readLine()) != null) {
hitbox.append(line);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
FileUtils.writeStringToFile(new File("hitbox.json"), hitbox.getText());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String game = null;
FileInputStream fileHitbox = null;
try {
fileHitbox = new FileInputStream(new File("hitbox.json"));
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String strHitbox = null;
try {
strHitbox = IOUtils.toString(fileHitbox, "UTF-8");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject obj = new JSONObject(strHitbox);
JSONArray ar = obj.getJSONArray("livestream");
for (int i = 0; i < ar.length(); i++)
{
game = ar.getJSONObject(i).getString("category_name");
nameOf.setText("Game Name: " + game);
}
File hb = new File("hitbox.json");
if(hb.exists()){
hb.delete();
}
}
The above sample is the defined function, and the Get Game Name button code is below:
btnGetGameName.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
apiConnect();
}
});
Could anyone suggest what is causing it to not work after the first request, and if possible suggest a solution?
EDIT: I have found the issue. The reading of the data from the API is appended to the hitbox variable. I have thus added a snippet that clears what "hitbox" variable has when the button is pressed, thus meaning the code works without issues.
Try to consume your response after your read it to release the resource :
rd = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
response.getEntity().consumeContent();
//Or if you have EntityUtils
EntityUtils.consume(response.getEntity());
source

Categories