Java FX - can't close window in loop - file

I write short program in JavaFX which monitors folder for every 5 seconds . When it finds any PDF file then shows informations about number of finds files. And everything works fine, but when in folder is any files, then I will see window (and this is ok), but after this, when I will delete files (folder will be empty) then window is still showing (but is inactiv). Why this window doesn't close? Have you any idea?
Below is my code:
package testFolder;
import java.io.*;
import javafx.application.Application;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
public class App extends Application{
private static String searchPath;
private File[] childrenFiles;
#Override
public void init(){
setPath();
}
#Override
public void start(Stage primaryStage){
run();
}
public File[] findPDFFiles(){
System.out.println("Find file in: " + searchPath);
File directory = new File(searchPath);
File[] childrenFiles = directory.listFiles(
(dir, name) -> {
return name.toLowerCase().endsWith(".pdf");
}
);
System.out.println("Number files: " + childrenFiles.length);
return childrenFiles;
}
// search folder
public void run(){
while (true){
childrenFiles = findPDFFiles();
if ((childrenFiles.length > 0)){
String countFile = "Number files: " + childrenFiles.length;
showAndWait(AlertType.INFORMATION, "FILES FOUND", countFile);
}
// wait 5 seconds
try{
Thread.sleep(5000);
}
catch (InterruptedException iex){
iex.printStackTrace();
};
}
}
// shows window with information about number of found files
private static void showAndWait(
AlertType alertType,
String title,
String content) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(content);
alert.getDialogPane().setPrefWidth(800);
alert.showAndWait();
}
// set folder to search files
public void setPath(){
searchPath = "/Users/Marcin/Desktop/IN/";
}
public static void main(final String[] args){
launch();
}
}

I tried your code and it worked fine for me even after deleting all pdf files it will print Number files: 0 in the console and no alerts are showing.
however, i will suggest using an AnimationTimer instead of the while(true) loop
an animationTimer has a handle method which is an abstract method that you'll have to override when you create the AnimationTimer
the code inside handle will be executed every frame so it will work like your while(true) but better
but be careful ! you can't directly call showAndWait inside an AnimationTimer handle so you'll do it by calling Platform.runLater, and this won't stop the animation timer from executing its handle method
so you can stop the animationTimer whenever you have to show an alert, and start it back when the alert gets hidden (closed) mainly to prevent the timer from creating a lot of alerts if you do not close old ones
one last problem is that the javafx platform will automatically shutdown whenever there is no javafx context shown so you can stop that by setting ImplicitExit to false in your start method !
after applying all of the above explained stuff, your code will look like this
package testFolder;
import java.io.*;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Alert;
import javafx.stage.Stage;
public class App extends Application{
private static String searchPath;
private static File[] childrenFiles;
static AnimationTimer timer;
static long then = 0;
#Override
public void init(){
setPath();
}
#Override
public void start(Stage primaryStage){
Platform.setImplicitExit(false);
run();
}
public static File[] findPDFFiles(){
System.out.println("Find file in: " + searchPath);
File directory = new File(searchPath);
File[] childrenFiles = directory.listFiles((dir, name) -> {
return name.toLowerCase().endsWith(".pdf");
});
System.out.println("Number files: " + childrenFiles.length);
return childrenFiles;
}
// search folder
public static void run(){
timer = new AnimationTimer() {
long sum = 0;
#Override
public void handle(long now) {
long dt = now - then;
sum+=dt;
if(sum/1000000 > 5000) {
childrenFiles = findPDFFiles();
if ((childrenFiles.length > 0)){
this.stop();
String countFile = "Number files: " + childrenFiles.length;
showAndWait(AlertType.INFORMATION, "FILES FOUND", countFile);
}
sum=0;
}
then = now;
}
};
timer.start();
}
// shows window with information about number of found files
private static void showAndWait(AlertType alertType, String title, String content) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);
alert.setContentText(content);
alert.getDialogPane().setPrefWidth(800);
alert.setOnHidden(e->{
then = System.nanoTime();
timer.start();
});
Platform.runLater(alert::showAndWait);
}
// set folder to search files
public void setPath(){
searchPath = "/Users/Marcin/Desktop/IN/";
}
public static void main(final String[] args){
launch(args);
}
}
hope this solves you're problem

Related

How to create automation report folders with date and time to maintain earlier executed reports for extent report 3.1.5?

I am using extent report 3.1.5 to generate reports for automation execution. I want to maintain previous executed reports folders too. i.e. I want folders created at run time for extent reports.
(Please refer screen shot)
Automation_Reports
-- 081020221030
-- 091020221120
-- 101020220130
POM.xml
com.aventstack
extentreports
3.1.5
ExtentManager.Java
package reporter;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.aventstack.extentreports.reporter.configuration.Theme;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ExtentManager {
private static String reportBaseDirectory;
private static ExtentReports extent;
public static final String OUTPUT_FOLDER_SCREENSHOTS ="/Screenshots/";
public static final String REPORT_FILE_PATH =System.getProperty("user.dir")+ "/Automation_Reports/";
public static ExtentReports getInstance() {
if (extent == null)
createInstance();
return extent;
}
//Create an extent report instance
public static void createInstance() {
ExtentManager.initDirectories();
setReportBaseDirectory(REPORT_FILE_PATH);
ExtentHtmlReporter htmlReporter = new ExtentHtmlReporter(REPORT_FILE_PATH+"/extent-reports/extent-report.html");
htmlReporter.config().setTheme(Theme.STANDARD);
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setReportName("Automation Test Report");
htmlReporter.config().setEncoding("utf-8");
htmlReporter.config().setJS("$('.brand-logo').text('Cemtrex');");
htmlReporter.config().setTimeStampFormat("EEEE, MMMM dd, yyyy, hh:mm a '('zzz')'");
extent = new ExtentReports();
extent.attachReporter(htmlReporter);
extent.setSystemInfo("OS", System.getProperty("os.name"));
extent.setSystemInfo("Java", System.getProperty("java.specification.version"));
extent.setSystemInfo("App Version", "22.200.17.26120)");
extent.setSystemInfo("User", "Admin");
}
public synchronized static String getReportBaseDirectory() {
return reportBaseDirectory;
}
public synchronized static void setReportBaseDirectory(String reportBaseDirectory) {
ExtentManager.reportBaseDirectory = reportBaseDirectory;
}
public static void initDirectories() {
try {
createFolder(REPORT_FILE_PATH + OUTPUT_FOLDER_SCREENSHOTS);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void createFolder(String folderPath) {
try {
File file = new File(folderPath);
// if(!file.exists()){
file.mkdirs();
// }
}catch(Exception e) {
}
}
public static String getSystemDateTime() {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd");
LocalDate localDate = LocalDate.now();
return dtf.format(localDate);
}
}

The codeScanner doesn't work when it's used with my application

I have a problem with the code scanner, I use this lib https://github.com/codenameone/cn1-codescan in my application to scan the barcode. I work on an android application and I try to scan code_128 code format.
public class ScanQr extends Form {
final Container cnt = this;
public ScanQr(Form parent){
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
final RadioButton qr = new RadioButton("QR Code");
final RadioButton bar = new RadioButton("Bar Code");
bg.add(qr);
bg.add(bar);
this.addComponent(new Label("Code Type"));
this.addComponent(qr);
this.addComponent(bar);
Button scanBtn = new Button("Scan Code");
scanBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(qr.isSelected()){
CodeScanner.getInstance().scanQRCode(new ScanResult() {
public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
//barCode.setText("Bar: " + contents);
cnt.addComponent(new Label(contents));
cnt.revalidate();
}
public void scanCanceled() {
cnt.addComponent(new Label("cancelled"));
}
public void scanError(int errorCode, String message) {
cnt.addComponent(new Label("err " + message));
}
});
}else{
CodeScanner.getInstance().scanBarCode(new ScanResult() {
public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
//barCode.setText("Bar: " + contents);
cnt.addComponent(new Label(contents));
cnt.revalidate();
}
public void scanCanceled() {
cnt.addComponent(new Label("cancelled"));
}
public void scanError(int errorCode, String message) {
cnt.addComponent(new Label("err " + message));
}
});
}
}
});
if (CodeScanner.isSupported()) {
this.addComponent(scanBtn);
} else {
this.addComponent(new SpanLabel("Sorry. Codescanner not supported on this platform"));
}
}
}
First it installs Barcode Scanner+ Simple if it's not installed then when this app is used with my application, it takes a lot of time to find and display the information scanned on the barcode or it doesn't find anything but when I just use Barcode Scanner+ Simple alone, it works very well, I don't have any problem with it.
I don't understand where's the problem since I use the same codescanner application but in 2 differents contexts, when it's launched alone and when it's launched with my application.
You need to try narrowing the types that are scanned to get a better result e.g. do this some time before invoking the scan:
Display.getInstance().setProperty("android.scanTypes", "CODE_128");

Why is my Flink standalone-cluster not receiving my job?

I created a program in Flink (Java) to calculate the average of 9 fake sensors on 3 different rooms. The program runs fine if I start the jar file. So I decided to start the flink standalone-cluster to check the TaskManagers running my Job and respective tasks, like here (https://ci.apache.org/projects/flink/flink-docs-stable/tutorials/local_setup.html). I am running everything on my machine.
Why Can I not see the job running on the dashboard (http://localhost:8081/#/overview) but if I watch the log files (tail -f log/flink--client--*-T430.log) I can see something being processed?
Moreover, the print() method is spilling the output to the console.
I start my application with this command ./bin/flink run examples/explore-flink.jar -c
But maybe there is some parameter on a config file that I have to configure. Here is my code:
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.sense.flink.mqtt.MqttTemperature;
import org.sense.flink.mqtt.TemperatureMqttConsumer;
public class SensorsMultipleReadingMqttEdgentQEP {
private boolean checkpointEnable = true;
private long checkpointInterval = 1000;
private CheckpointingMode checkpointMode = CheckpointingMode.EXACTLY_ONCE;
public SensorsMultipleReadingMqttEdgentQEP() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime);
if (checkpointEnable)
env.enableCheckpointing(checkpointInterval, checkpointMode);
DataStream<MqttTemperature> temperatureStream01 = env.addSource(new TemperatureMqttConsumer("topic-edgent-01"));
DataStream<MqttTemperature> temperatureStream02 = env.addSource(new TemperatureMqttConsumer("topic-edgent-02"));
DataStream<MqttTemperature> temperatureStream03 = env.addSource(new TemperatureMqttConsumer("topic-edgent-03"));
DataStream<MqttTemperature> temperatureStreams = temperatureStream01.union(temperatureStream02)
.union(temperatureStream03);
DataStream<Tuple2<String, Double>> average = temperatureStreams.keyBy(new TemperatureKeySelector())
.map(new AverageTempMapper());
average.print();
String executionPlan = env.getExecutionPlan();
System.out.println("ExecutionPlan ........................ ");
System.out.println(executionPlan);
System.out.println("........................ ");
// env.execute("SensorsMultipleReadingMqttEdgentQEP");
env.execute();
}
public static class TemperatureKeySelector implements KeySelector<MqttTemperature, Integer> {
private static final long serialVersionUID = 5905504239899133953L;
#Override
public Integer getKey(MqttTemperature value) throws Exception {
return value.getId();
}
}
public static class AverageTempMapper extends RichMapFunction<MqttTemperature, Tuple2<String, Double>> {
private static final long serialVersionUID = -5489672634096634902L;
private MapState<String, Double> averageTemp;
#Override
public void open(Configuration parameters) throws Exception {
averageTemp = getRuntimeContext()
.getMapState(new MapStateDescriptor<>("average-temperature", String.class, Double.class));
}
#Override
public Tuple2<String, Double> map(MqttTemperature value) throws Exception {
String key = "no-room";
Double temp = value.getTemp();
if (value.getId().equals(1) || value.getId().equals(2) || value.getId().equals(3)) {
key = "room-A";
} else if (value.getId().equals(4) || value.getId().equals(5) || value.getId().equals(6)) {
key = "room-B";
} else if (value.getId().equals(7) || value.getId().equals(8) || value.getId().equals(9)) {
key = "room-C";
} else {
System.err.println("Sensor not defined in any room.");
}
if (averageTemp.contains(key)) {
temp = (averageTemp.get(key) + value.getTemp()) / 2;
} else {
averageTemp.put(key, temp);
}
return new Tuple2<String, Double>(key, temp);
}
}
}
Thanks,
Felipe
After I select the option "Extract required libraries into generated JAR" it worked. Strange because I was generating the JAR with the option "Package required libraries into generated JAR" and it was not working.

How to generate report (Extent Report) in Specflow Project

Currently I am working designing my project in Specflow. I want to implement some reporting to my project. Currently I have created one separate .cs file and kept all my report setting. But these steps are getting unreachable. Can anyone please guide me how i can design my flow and how i can integrate with the feature file?
Please find the below BaseReport.cs file and my Step definition file.
namespace Verivox.CommonLib
{
public class BaseReport
{
public static ExtentReports extent;
public static ExtentTest test;
[BeforeFeature()]
public static void BasicSetUp()
{
//string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Reports\\" + FeatureContext.Current.FeatureInfo.Title + ".html";
extent = new ExtentReports(reportPath, true);
extent.LoadConfig(projectPath + "CommonLib\\Extent-config.xml");
}
[BeforeScenario()]
public static void BeforeScenarioSetUp()
{
test = extent.StartTest("Running Scenario -->" + ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario()]
public static void AfterScnario()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
//Add capture screen shot line here
extent.EndTest(test);
}
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
// extent.Close();
}
}
}
Steps
namespace Verivox.Steps
{
[Binding]
class CalculationVerificationSteps
{
[Given(#"I have navigate to Home Page")]
public void GivenIHaveNavigateToHomePage()
{
Browser.Current.Navigate().GoToUrl(ConfigurationManager.AppSettings["seleniumBaseUrl"]);
PropertyCollection.currentPage = new HomePage();
Browser.Current.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
[Given(#"Navigate to Mobile Calculator under All Comparison Section")]
public void GivenNavigateToMobileCalculatorUnderAllComparisonSection()
{
PropertyCollection.currentPage.As<HomePage>().MainCompItemClick("Telekommunikation");
PropertyCollection.currentPage.As<HomePage>().SubCompItemClick("Mobilfunk");
PropertyCollection.currentPage.As<HomePage>().CalculatorLinkClick("Mobiles Internet");
}
[Then(#"Mobile Calculator should appear")]
public void ThenMobileCalculatorShouldAppear()
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().IsMobileInternetCalcExistance());
}
[Then(#"(.*) option and (.*) option is selected by default\.")]
public void ThenMonatsflatrateOptionAndSIMOptionIsSelectedByDefault_(string defaultTarif, string hardware)
{
try
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().VerifyMobiIntSelectedItem(defaultTarif));
string colorCode = PropertyCollection.currentPage.As<HomePage>().VerifySelectedHardWare();
Assert.AreEqual(0, string.Compare("rgba(253, 138, 2, 1)", colorCode, StringComparison.OrdinalIgnoreCase));
}
catch (Exception)
{
BaseReport.test.Log(LogStatus.Fail, "Default selections are incorrect.");
}
}
You are missing the Binding- attribute on the BaseReport class. Without that, the hooks defined there are not called.

Need examples headers and cookies

IDE: NetBeans
Desktop OS Windows 10
Simulator Android/iOS
Device Android/iOS
I am able to get authentication to work with connection request. I am having to get header information and then in another part of the app, send that same information back to the cgi-bin. Below is my code and I commented on the parts where I believe I need to do something with a header and or cookie. I'm very new to this and It's been difficult finding even a basic header/cookie tutorial.
/**
* Your application code goes here<br>
* This file was generated by Codename One for the purpose
* of building native mobile applications using Java.
*/
package userclasses;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.Cookie;
import com.codename1.io.NetworkEvent;
import com.codename1.io.NetworkManager;
import com.codename1.io.Storage;
import com.codename1.notifications.LocalNotification;
import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;
import java.util.Timer;
import java.util.TimerTask;
//import org.apache.commons.httpclient.UsernamePasswordCredentials;
//import org.apache.commons.httpclient.auth.AuthScope;
/**
*
* #John Barrett
*/
public class StateMachine extends StateMachineBase {
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class members there,
// the constructor might be invoked too late due to race conditions that might occur
}
/**
* this method should be used to initialize variables instead of
* the constructor/class scope to avoid race conditions
*/
protected void initVars(Resources res) {
}
boolean stop = false;
boolean notify = false;
String OnOff;
#Override // Starts monitor action.
protected void onMain_ButtonAction(Component c, ActionEvent event){
// starts a timer to repeat monitor every minute.
Timer timer = new Timer();
String text = (String) Storage.getInstance().readObject("SavedData");
timer.schedule( new TimerTask(){
#Override
public void run(){
if (stop == true){
cancel();//Monitor ends
}
//Starts a connection with the URL to monitor
ConnectionRequest r = new ConnectionRequest();
r.setUrl("http://vault.infinitevault.com/cgi-bin/absentmedia?customer=" + text.toLowerCase().trim());
r.setPost(true);
// Post Header/Cookie information to URL for access NEED HELP WITH THIS!
r.setHttpMethod("HEAD");
r.setContentType("text/xml");
r.setCookiesEnabled(true);
findCodeLabel(c).setText("Monitoring: " + text.toUpperCase());
r.addResponseListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev){
// Monitor starts
try{
NetworkEvent event = (NetworkEvent) ev;
// Need to post header/cookie information here? HELP!
Cookie.isAutoStored();
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
boolean none;
none = decodedData.endsWith("NONE\n");
if (!none){
System.out.println(decodedData);
findCodeTextArea(c).setText(decodedData);
LocalNotification n = new LocalNotification();
n.setId("OSStorage");
n.setAlertBody(decodedData);
n.setAlertTitle("Absent Media");
Display.getInstance().scheduleLocalNotification(
n,
System.currentTimeMillis() + 10 * 1000, // fire date/time
LocalNotification.REPEAT_MINUTE // Whether to repeat and what frequency
);
if (notify != true){
Display.getInstance().vibrate(5000);
}
Storage.getInstance().writeObject("MonitorData", decodedData);
}
else{
System.out.println("None");
findCodeTextArea(c).setText("System is Good");
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
NetworkManager.getInstance().addToQueue(r);
}
}, 0, 60*1000);
}
#Override // Stops the monitoring action.
protected void onMain_StopButtonAction(Component c, ActionEvent event) {
super.onMain_StopButtonAction(c, event);//To change body of generated methods, choose Tools | Templates.
stop = true;
findCodeLabel(c).setText("Monitor Stopped");
findCodeTextArea(c).setText("");
findCodeTextArea(c).setHint("System information will show here");
Storage.getInstance().deleteStorageFile("MonitorData");
}
#Override // Saves the settings to storage.
protected void onSettings_SetSaveAction(Component c, ActionEvent event) {
String Station = findSetStation(c).getText();
Storage.getInstance().writeObject("SavedData", Station);
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findStationLabel(c).setText("Saved Station is " + LoadStation);
}
#Override // Sets what is saved to appear when in settings.
protected void beforeSettings(Form f) {
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findStationLabel(f).setText("Saved Station is " + LoadStation);
findSetStation(f).setText(LoadStation);
String CurrentNotify = (String) Storage.getInstance().readObject("OnOff");
findSetNotifyLabel(f).setText("Vibration is " + CurrentNotify);
}
#Override // Sets what is saved to appear when in monitor screen.
protected void beforeMain(Form f) {
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findCodeLabel(f).setText(LoadStation);
if (findCodeTextArea(f) != null){
String foundData = (String) Storage.getInstance().readObject("MonitorData");
findCodeTextArea(f).setText(foundData);
}
}
#Override // Sets notification for turning vibration on.
protected void onSettings_SetNotifyOnAction(Component c, ActionEvent event) {
notify = false;
OnOff = "ON";
Storage.getInstance().writeObject("NotifyOn", notify);
Storage.getInstance().writeObject("OnOff", OnOff);
findSetNotifyLabel(c).setText("Vibration is " + OnOff);
}
#Override // Sets notification for turning vibration off.
protected void onSettings_SetNotifyOffAction(Component c, ActionEvent event) {
notify = true;
OnOff = "OFF";
Storage.getInstance().writeObject("NotifyOn", notify);
Storage.getInstance().writeObject("OnOff", OnOff);
findSetNotifyLabel(c).setText("Vibration is " + OnOff);
}
#Override // Sets message for monitoring or not.
protected void beforeStartPage(Form f) {
Storage.getInstance().deleteStorageFile("MonitorData");
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
}
#Override // Login button pressed after entering username and password.
protected void onLogin_LoginAction(Component c, ActionEvent event) {
// Gets the username and password entered.
String userName = findUsename().getText();
String passWord = findPassword().getText();
// Establishes a conneciton to authentication.
ConnectionRequest req=new ConnectionRequest();
req.setPost(false);
req.setUrl("http://authentication.infinitevault.com/validate.php");
req.addArgument("username",userName);
req.addArgument("password",passWord);
req.addArgument("grant_type","client_credentials");
// To get the Header/Cookie information.
req.getHttpMethod();
req.setCookiesEnabled(true);
Cookie.setAutoStored(true);
Cookie.isAutoStored();
// Sends message to user that system is verifying.
findDenied(c).setText("Verifying");
NetworkManager.getInstance().addToQueueAndWait(req);
if (req.getResponseData() != null) {
String token = new String(req.getResponseData());
token = token.substring(token.indexOf('=') + 1);
System.out.println(token);
// Checks credentials if response is denied, goes back,
// If response is authenticated goes to main monitor form.
if (token.endsWith("denied")){
/*try {
Thread.sleep(2000); //1000 milliseconds is one second.
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}*/
back();
}
else {
showForm("Main",null);
}
}
}
}//end of app
Just override the connection request method cookieReceived(Cookie c) and handle the logic of each cookie there.

Resources