delay processing in java application - java

Can someone please help me out. I have an application that creates a file to be processed by an external application. I need to somehow delay my code to wait until there is a file created from the external application. But I am having issues finding anything that cause a delay in the Java.
Thanks in advance

Pretty rudimentary and crude but technically, Thread.sleep() induces delay.

As per comment, simple, but crude:
File f = new File("your-file.txt");
for (;;)
{
try
{
if (f.isFile())
{
break;
}
}
catch (Exception e)
{
e.printStackTrace();
// Or some other appropriate
// handling of the exception.
}
try
{
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
}

delay my code to wait until there is a file created
It is better to activate methods in your code when something happens. To do that I would suggest a separate Thread that runs and checks the condition, then calls your apps. method if needed. For an app. with a GUI, this would typically be achieved using a Swing Timer, but I believe it can also be achieved using a java.util.Timer.

you can try
while(!file.exists());

Instead of polling for a file change with a timer, you could just use the Java file API and wait for a file modification event. Here are the docs:
http://docs.oracle.com/javase/tutorial/essential/io/notification.html
and here is a small example:
http://docs.oracle.com/javase/tutorial/essential/io/examples/WatchDir.java

Related

Better optimization for changing audio's volume JavaSwing

Been testing a new system for increasing/decreasing the audio within my JavaSwing application using a fade in and fade out effect. This works on one hand though by doing my own research, it's not as optimal as one hoped to be since it utilizes Thread.sleep(x); rather than using Timer(); from JavaSwing.
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
value = (value <= 0.0) ? 0.0001 : ((value > 1.0) ? 1.0 : value);
try {
float db = (float) (Math.log(percent) / Math.log(10.0) * 20.0);
gainControl.setValue(db);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void shiftVolumeTo(double value) {
value = (value <= 0.0) ? 0.0001 : ((value > 1.0) ? 1.0 : value);
targetDB = (float)(Math.log(value)/Math.log(10.0)*20.0);
if (!fading) {
Thread t = new Thread();
t.start();
}
}
public static void run() {
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
fading = true;
if(currDB > targetDB) {
while (currDB > targetDB) {
currDB -= fadePerStep;
gainControl.setValue(currDB);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (currDB < targetDB) {
while(currDB < targetDB) {
currDB += fadePerStep;
gainControl.setValue(currDB);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
fading = false;
currDB = targetDB;
}
public static void volTest() {
setVolume(1);
shiftVolumeTo(.2);
run();
}
Again, this works properly when run(); is called, but it puts the entire application to sleep within the duration of the while loop's runtime. Which is what I'm having an issue with. I've tried setting up a JavaSwing Timer(); within the code though I couldn't figure out how to set it up properly to make the delay run like the Thread.sleep(x); method. Whether it is adding the code from run(); into the ActionListener created or utilized by the timer or just having run(); within the ActionListener. Unlike Thread.sleep(x);, the program will just jump values without taking it's time to decrease the volume as there's no delay between the incremental increase/decrease of the while loop.
What would be the optimal way to utilize a JavaSwing Timer(); that would work similar to a Thread.sleep(x); in this situation?
I'm not clear what you are doing from the given code. I suspect you are mixing up aspects of the util.Timer with the swing.Timer (not uncommon).
With the util.Timer, one extends TimerTask, and within that, one overrides the run() method. The run() method is never static, afaik.
With the swing.Timer, the code to be executed resides in the actionPerformed() method of the ActionListener.
Another alternative, and likely a better way to manage the separate thread would be to use a ScheduledThreadPoolExecutor.
I'd consider using the util.Timer in this case. I think the calls to change the value of the FloatControl could be set up to be thread safe if you are careful about limiting the calls to a single sound at a time. (Here is a link for more about Swing's Event Dispatch Thread) It would be necessary to use the swing.Timer if thread safety is an issue.
But you understand here that you can only fade in or out a single sound at a time, and ALL sounds playing at that moment will also be affected? The FloatControl.MASTER_GAIN controls all playing sounds. Also, I don't think there are no guarantees that the FloatControls are implemented on a given computer. There are many listed in the documentation that I have discovered do not function on various PCs I own.
Another issue is that sometimes it can be difficult to find the best interval for the updates and corresponding amount to vary the volume. Sometimes we get as soft, fast sequence of clicks, like the sound of scraping a thumbnail over the tines of a comb, if the individual volume changes are too large.
I'd like to mention a library for you to consider that bypasses the use of the FloatControl: AudioCue. The class is basically a rewrite of the Clip but with a built in, dynamic, volume controller. When you alter the volume of a given playback instance, it will only affect that single instance. (The class supports playing back concurrent instances.) All the amplitude computations are done internally, within the code of the class.
The library can be run as a Maven resource. The project is a work in progress: I've just added a lot of test code that I'm about to push to the master. I'm working to publish it on Maven Central. (Learning as I go.) But if you fork the project and run the Maven install command, it will create a resource that you can reference locally via the Maven pom file.
I'm considering adding an optional duration argument to the dynamic controls. Then (if implemented) one could specify both the desired volume and the number of frames or milliseconds over which the change should be applied. Seems like a good addition for version 1.2 (after 1.1 is up on Maven central!)
With AudioCue, changes are applied per individual frames. I'm not sure what the situation is with FloatControl and Clips. The changes might be limited in granularity to some internal buffer size.

delay between Camera.takephoto and callback

guys. I am trying to use custom camera and found one problem: i have delay for 1 second between camera.takephoto and callback (onTakePicture). But why, because i havent any delay in default camera, when i take some photos, it works very faster, thanks.
Just use
try{
Thread.sleep(1000);
}catch(Error e){
}

How to set a Java Gui listener for unexpected program end

I am making a personal planning program. I utilize XML documents to store user data and login data. This does not utilize a server and all accounts created in the program are localized to the computer it is stored on (in the XML documents.)
In the login XML document, I keep track of the users that are logged in so that one user can't have two windows at the same time to prevent any conflicts with data. This feature runs smoothly and I have no problem with it.
The only thing I want to know is if there is some way to catch an unexpected shut down of a program (such as a task-manager close or a forced close when shutting down the computer) so that I can "log" the user off of the XML document. Otherwise the user would never be able to get back on after an unexpected program close without going into the XML document and deleting the username from the logged in list.
It seems a shutdown hook does not work well with the event queue for a java GUI. much like this thread
I tried setting up my code exactly as shown and the shutdown hook doesn't work for me either. Are there any suggestions for ways of catching an unexpected shutdown without shutdown hooks?
this is my code:
import java.awt.EventQueue;
public class Gui {
private static Controller controller;
public static void main (String[] args) {
controller = new Controller();
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
controller.saveState();
controller.logUserOut();
}
});
EventQueue.invokeLater(
new Runnable() {
public void run() {
controller.start();
}
});
}
}
This is a closer look at my controller that logs the user out
public void logUserOut() {
loginDatabase.logUserOut(username);
saveLoginState();
}
All loginDatabase does is removes that username from the list of logged in users so that user is free to log in again
public void saveLoginState() {
XStream xStream = new XStream(new DomDriver());
OutputStream outFile;
try {
String filePath = "data" + File.separator + "loginDatabase.xml";
outFile = new BufferedOutputStream(new FileOutputStream(filePath));
xStream.toXML(loginDatabase, outFile); // This writes your state to the outputFile;
outFile.close(); //close the writer
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This is my process for writing on the login state xml file. I suspect it might be too long for a Shutdown Hook even if it were actually being called as I expect.
Any suggestions? I thought for a long time about possibly using simple variables to solve the problem but because I have the program set so that the user can be logged into multiple accounts, the use of variables is impossible.
Also, will the controller object contained in the scope of the shutdown hook be the same controller that is modified in the event queue scope?
The shutdown hook can be a solution here. For details see e.g. this answer: https://stackoverflow.com/a/2541618/2045440
[Off topic] However, if you're at risk that unexpected termination of your application can result in lost of important data, maybe it would be worth to consider the more persistent way of processing this data (autosaving, backup files etc).
I resolved the problem by checking the task manager of the operating system. It allowed me to see if the user the xml document said was logged in actually had a program open. If not then I knew there was a problem. This is a fix for my particular program but it might be a help for others as well.
The link to that thread is here.

Getting Selenium to pause for X seconds

What I am trying to accomplish is browsing to a page, waiting for something to load and then taking and saving a screenshot.
The code I already have is
WebDriver driver = new FirefoxDriver();
driver.get("http://www.site.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try {
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("/home/Desktop/image.png"));
} catch (Exception e) {
e.printStackTrace();
}
driver.close();
The reason I need to wait, even if the page is loaded is because it'll be loaded but on the site the content I'd like to take a picture of loads after a few seconds. For some reason the page is not waiting, is there another method that I can use to get the driver/page to wait for X amount of seconds?
You can locate an element that loads after the initial page loads and then make Selenium wait until that element is found.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ID")));
That wouldnt really be a selenium specific thing. You just want java to sleep for a bit after loading the page but before taking the screenshot.
Thread.sleep(4000);
put that after your driver.get statement.
If you want to delay a certain number of seconds, rather than to respond as soon as possible, here is a function for pause similar to what selenium IDE offers:
public void pause(Integer milliseconds){
try {
TimeUnit.MILLISECONDS.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
source
The most simple of all.
Just try this and forget rest! The equivalent of this code can be used in any language.
I am writing this in python.
import time
time.sleep(2)
this will make the compiler go to sleep for 2 seconds.
Just in case it will help somebody, you should always try to avoid implicit waits and especially Thread#sleep as much as you can. If you do Thread.sleep(10), your code will always wait for 10 seconds even in case your page is ready after 1 sec. So this can slow your tests substantially if you use this often.
Better way is to use ExplicitWaits which you means you will wait exactly as long as some action happens or some element gets rendered on the page. So in your case, I would use explicit wait to check whether is everything loaded and then take a screenshot.
const { By, until } = require('selenium-webdriver');
this.wait = async function (amount: number) {
try {
await this.driver.wait(
until.elementLocated(By.css('[data-test-id="does-not-exist"]')),
amount,
'Looking for element'
);
} catch (e) {
console.log('waiting')
}
We look for a css identifier that isn't there for x amount of seconds. This is typescript btw. This would be a method on some relevant class, or a function by itself. Use it like this
const button = await this.findByCSSSelector('[data-test-id="get-quote-button"]')
const actions = this.driver.actions({ bridge: true });
await actions.move({origin: button }).perform();
// Small pause to observe animation is working correctly in all browsers
await this.wait(700)
const carat = await this.findByCSSSelector('[data-test-id="carat"]');
This waits for .7 of a second so that you can see that whatever animation is working in your functional tests.

A proper way to output text immediately in Java Swing GUI

Such a piece of code:
private void log(String message) {
LogBox.append(message + "\n");
}
private void log(Exception e) {
log(e.getMessage());
}
private void ConvertButtonActionPerformed(java.awt.event.ActionEvent evt) {
String url = UrlBox.getText();
if (url.isEmpty()) {
log("Empty URL");
return;
}
LogBox.setText("");
try {
log("URL "+url+" accepted. Trying to download...");
String content = URLConnectionReader.getText(url);
log("Downloaded. Parsing the content...");
//
} catch (Exception e) {
log(e);
}
}
should output each message to the LogBox (JTextArea) immediately after each log call, but outputs URL ... accepted only when URLConnectionReader.getText(url) finishes.
There were several ways do do an immediate output:
Application.DoEvents in Visual Basic 6 and .NET
Application.ProcessMessages in Delphi
Is there some simple way to do an immediate output? I was studying questions about the DoEvents and how to do this in Java, but I think that starting to learn Java from multi-threading isn't a right approach.
Create a SwingWorker to do the download: http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html
The role of an ActionListener is just that: to listen for user action, and initiate a response to that action by the program.
Sometimes, the program's response is very quick, and only involves the GUI. For example, in a calculator app, you could have a listener attached to an "equals" button that calculates the result of the current expression and writes it to a textbox. This can all be done within the listener method (although you might want to separate behavior for testing).
If the response to an user action is to initiate some long-running process, like downloading and parsing the file, then you don't want to do this within the listener body, because it will freeze the UI. Instead, gather any information (in your case, the URL value) from within the listener, and spin up a SwingWorker to handle the program's response.
In my comment, I suggested moving everything after the getText() into a SwingWorker. This is because, to me, the response is "download a file if you have a valid URL, and log the progress." And as I see it, testing for an empty string is part of that response. If you want to leave the empty-string test inside the listener, that's fine, but imo it's less testable.
You must leave the call to getText() inside the body of the listener, because you are only allowed to access Swing components from the event dispatch thread. If you moved that call into the worker, then it might access the textbox at the same time the textbox is updating itself, resulting in corrupt data.
Read up on Concurrency.
You should probably use a SwingWorker for the long running task, then you can publish results to the GUI as they become available.

Categories

Resources