This question already has an answer here:
javafx using objects from MainController or other Controllers in proper Controller class
(1 answer)
Closed 5 years ago.
sorry. I don't speak english well so please understand me
I'm making smartmirror for java but I have problem with setText() function.
after calling weather api and saving location name to variable, I start label.setText() but it has null pointer exception.
I heard about platform.run later() method and task , but they don't work.
please help me T.T
There are my source
package SmartMirror.main;
import java.io.IOException;
public class SpeechClass {
WeatherController weather = new WeatherController();
// Logger
private Logger logger = Logger.getLogger(getClass().getName());
// Variables
public String result;
// Threads
Thread speechThread;
Thread resourcesThread;
Thread openThread;
// LiveRecognizer
private LiveSpeechRecognizer recognizer;
protected String location;
public void Speech(){
// Loading Message
logger.log(Level.INFO, "Loading..\n");
// Configuration
Configuration configuration = new Configuration();
// Load model from the jar
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// if you want to use LanguageModelPath disable the 3 lines after which
// are setting a custom grammar->
// configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.bin")
// Grammar
configuration.setGrammarPath("resource:/grammars");
configuration.setGrammarName("grammar");
configuration.setUseGrammar(true);
try {
recognizer = new LiveSpeechRecognizer(configuration);
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
}
// Start recognition process pruning previously cached data.
recognizer.startRecognition(true);
// Start the Thread
startSpeechThread();
startResourcesThread();
}
/**
* Starting the main Thread of speech recognition
*/
protected void startSpeechThread() {
// alive?
if (speechThread != null && speechThread.isAlive())
return;
// initialise
speechThread = new Thread(() -> {
logger.log(Level.INFO, "You can start to speak...\n");
try {
while (true) {
/*
* This method will return when the end of speech is
* reached. Note that the end pointer will determine the end
* of speech.
*/
SpeechResult speechResult = recognizer.getResult();
if (speechResult != null) {
result = speechResult.getHypothesis();
System.out.println("You said: [" + result + "]\n");
if(result.equals("one")){
System.out.println("startOpenThread");
startWeatherThread();
openThread.sleep(3000);
Platform.runLater(new Runnable(){
#Override
public void run(){
weather.setLabel();
openweather();
}
});
}
// logger.log(Level.INFO, "You said: " + result + "\n")
} else
logger.log(Level.INFO, "I can't understand what you said.\n");
}
} catch (Exception ex) {
logger.log(Level.WARNING, null, ex);
}
logger.log(Level.INFO, "SpeechThread has exited...");
});
// Start
speechThread.start();
}
/**
* Starting a Thread that checks if the resources needed to the
* SpeechRecognition library are available
*/
protected void startResourcesThread() {
// alive?
if (resourcesThread != null && resourcesThread.isAlive())
return;
resourcesThread = new Thread(() -> {
try {
// Detect if the microphone is available
while (true) {
if (AudioSystem.isLineSupported(Port.Info.MICROPHONE)) {
// logger.log(Level.INFO, "Microphone is available.\n")
} else {
// logger.log(Level.INFO, "Microphone is not
// available.\n")
}
// Sleep some period
Thread.sleep(350);
}
} catch (InterruptedException ex) {
logger.log(Level.WARNING, null, ex);
resourcesThread.interrupt();
}
});
// Start
resourcesThread.start();
}
protected void startWeatherThread() {
try{
openThread = new Thread(() -> {
weather.Weather(); // 날씨를 변수에 저장
});
} catch (Exception e){
}
// Start
openThread.start();
}
public void openweather(){
Stage dialog = new Stage(StageStyle.TRANSPARENT);
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(null);
Parent parent = null;
try {
parent = FXMLLoader.load(WeatherController.class.getResource("weather_scene.fxml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scene scene = new Scene(parent);
dialog.setScene(scene);
dialog.setResizable(false);
dialog.show();
}
}
package SmartMirror.Weather;
import java.io.BufferedReader;
public class WeatherController {
#FXML private Label labelLocation;
public String locationResult="", weatherResult="", tempResult="";
//날씨 API
public void Weather() {
try{
//OpenAPI call하는 URL
String urlstr = "http://api.openweathermap.org/data/2.5/weather?"
+"q=Chuncheon"
+"&appid=f1bccf50c733316db790a00a2d5165c6&units=metric";
URL url = new URL(urlstr);
BufferedReader bf;
String line;
String result="";
//날씨 정보를 받아온다.
bf = new BufferedReader(new InputStreamReader(url.openStream()));
//버퍼에 있는 정보를 문자열로 변환.
while((line=bf.readLine())!=null){
result=result.concat(line);
//System.out.println(line);
}
//문자열을 JSON으로 파싱
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(result);
//날씨 출력
JSONArray weatherArray = (JSONArray) jsonObj.get("weather");
JSONObject weather = (JSONObject) weatherArray.get(0);
//온도출력
JSONObject mainArray = (JSONObject) jsonObj.get("main");
double ktemp = Double.parseDouble(mainArray.get("temp").toString());
locationResult = (String) jsonObj.get("name");
weatherResult = (String) weather.get("main");
tempResult = Double.toString(ktemp) + "℃";
System.out.println("startWeatherThread" + locationResult);
bf.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public void setLabel(){
Platform.runLater(new Runnable(){
#Override
public void run(){
System.out.println(locationResult);
labelLocation.setText(locationResult);
}
});
}
}
First of all, I'm not recommending on using public attributes, I suggest you to check Why use getters and setters? so change your 3 public field to a private ones and then make getters and setters to them.
About your problem, I haven't seen your fxml code for it, but make sure you gave your label an identity also known as fx:id so it wouldn't cause it to be null.
Also make sure that you gave reference to your WeatherController in fx:controller
Related
I've working on an assignment that asks me to alter a method in a class to take content from a textfile and use it to create multiple instances of various subclasses of the Event Class. Here is the text file:
Event=ThermostatNight,time=0
Event=LightOn,time=2000
Event=WaterOff,time=8000
Event=ThermostatDay,time=10000
Event=Bell,time=9000
Event=WaterOn,time=6000
Event=LightOff,time=4000
Event=Terminate,time=12000
The Event=* is the name of the subclass, while time=* is a parameter that is used in the subclass' constructor. The Event class itself is an abstract class and is used for inheritance.
public class Restart extends Event {
Class eventClass;
String eventInput;
Long timeDelay;
public Restart(long delayTime, String filename) {
super(delayTime);
eventsFile = filename;
}
public void action() {
List<String> examples = Arrays.asList("examples1.txt", "examples2.txt", "examples3.txt", "examples4.txt");
for (String example : examples) {
//finding pattern using Regex
Pattern pattern = Pattern.compile(example);
Matcher matcher1 = pattern.matcher(eventsFile);
if (matcher1.find()) {
File file = new File(example);
String line;
try {
FileReader fileReader = new FileReader(file);
Scanner sc = new Scanner(file);
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
sc.useDelimiter("\n");
//Parsing through text
while (sc.hasNext()) {
String s = sc.next();
String[] array1 = s.split(",");
String[] array2 = array1[0].split("=");
eventInput = array2[1];
String[] array3 = array1[1].split("=");
String timeInput = array3[1];
try {
eventClass = Class.forName(eventInput);
timeDelay = Long.parseLong(timeInput);
try {
addEvent(new eventClass(timeDelay));
}
//catch block
catch(NoSuchMethodException e){
System.out.println("No Such Method Error");
} catch (Exception e) {
System.out.println("error");
}
//catch block
} catch (ClassNotFoundException ex) {
System.out.println("Unable to locate Class");
} catch (IllegalAccessException ex) {
System.out.println("Illegal Acces Exception");
} catch (InstantiationException ex) {
System.out.println("Instantiation Exception");
}
}
}
//Close bufferedReader
bufferedReader.close();
}
//catch block
catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
file + "'");
} catch (IOException ex) {
ex.printStackTrace();
}
break;
}
//if input match is not found
else {
System.out.println("No Match Found");}
}
}
I seem to be able to parse fine, and find the strings i'm looking for, but I'm not able to use eventInput which I've pulled from the text file as a parameter to create a new event.
eventClass = Class.forName(eventInput);
doesn't seem to be turning my string into an acceptable parameter either.
Any help would be much appreciated!
I know I'm probably missing something key here, but I've been staring at it too long that it seems like a lost cause.
Here is the Event class:
public abstract class Event {
private long eventTime;
protected final long delayTime;
public Event(long delayTime) {
this.delayTime = delayTime;
start();
}
public void start() { // Allows restarting
eventTime = System.currentTimeMillis() + delayTime;
}
public boolean ready() {
return System.currentTimeMillis() >= eventTime;
}
public abstract void action();
} ///:~
I think you've misunderstood how reflection works. Once you have a Class object (the output from Class.forName(), you have to find the appropriate constructor with
Constructor<T> constructor = eventClass.getConstructor(parameter types)
and then create a new instance with
constructor.newInstance(parameters);
For a no-arg constructor there's a shortcut
eventClass.newInstance();
I strongly suggest you read the tutorials on reflection before proceeding.
I have a class called HomeView that is used to extend a Vaadin Designer HTML class. This class has a Vaadin table that takes input from an uploaded file. So far the file uploads fine and I can split the file up into lines for testing. I was trying to use Vaadin threads to lock the session and go to the UploadFile class in which I will split up the file and add to a row in the table. I would then unlock the session, exit back to the background thread and the UI should update the table with new rows. This is not happening with the code below.
public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
//upload notification for upload
new Notification("File Uploaded Successfully",
Notification.Type.HUMANIZED_MESSAGE)
.show(Page.getCurrent());
//create new class for parsing logic
uf = new UploadFile();
new Thread(new Runnable() {
#Override
public void run() {
try {
getSession().lock();
uf.parseFile();
getSession().unlock();
} catch (IOException e) {
new Notification("Could not parse file type",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
}
catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (ReadOnlyException e) {
e.printStackTrace();
}
}
}).start();
//outputFile.delete();
}
});
UploadFile class
public class UploadFile extends HomeView {
/**
*
*/
private static final long serialVersionUID = 839096232794540854L;
public void parseFile() throws IOException {
//container.removeAllItems();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println("before add:" + uploadTable.size());
container = uploadTable.getContainerDataSource();
container.addItem("row3");
Item item2 = container.getItem("row3");
Property property2 = item2.getItemProperty("name");
property2.setValue("hello");
uploadTable.setContainerDataSource(container);
System.out.println("after add:" + uploadTable.size());
}
reader.close();
}
}
If I take the code above and just put it in place of the method call, then the table updates fine. The table is updating the row count in the background, it's just not refreshing the view. What am I missing to make the UI refresh?
#Override
public void uploadSucceeded(Upload.SucceededEvent succeededEvent) {
//upload notification for upload
new Notification("File Uploaded Successfully",
Notification.Type.HUMANIZED_MESSAGE)
.show(Page.getCurrent());
//create new class for parsing logic
uf = new UploadFile();
new Thread(new Runnable() {
#Override
public void run() {
try {
getSession().lock();
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile.getAbsolutePath()), StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null)
{
System.out.println("before add:" + uploadTable.size());
container = uploadTable.getContainerDataSource();
container.addItem("row3");
Item item2 = container.getItem("row3");
Property property2 = item2.getItemProperty("name");
property2.setValue("hello");
uploadTable.setContainerDataSource(container);
System.out.println("after add:" + uploadTable.size());
}
reader.close();
getSession().unlock();
} catch (IOException e) {
new Notification("Could not parse file type",
e.getMessage(),
Notification.Type.ERROR_MESSAGE)
.show(Page.getCurrent());
}
catch (UnsupportedOperationException e) {
e.printStackTrace();
} catch (ReadOnlyException e) {
e.printStackTrace();
}
}
}).start();
//outputFile.delete();
}
});
UI.getCurrent() helper uses a ThreadLocal variable to get the active UI and it only works in a code executed in UI thread (e.g. a init method or button click listener). Get the UI reference before constructing the Thread and use the access method around your code that modifies UI. Do not use getSession().lock() or similar, you'll most likely do something wrong with that. Here is a simple usage example that should help you to resolve your use case as well.
// Get the reference to UI to be modified
final UI ui = getUI();
new Thread() {
#Override
public void run() {
// Do stuff that don't affect UI state here, e.g. potentially
// slow calculation or rest call
final double d = 1*1;
ui.access(new Runnable() {
#Override
public void run() {
// This code here is safe to modify ui
Notification.show("The result of calculation is " + d);
}
});
}
}.start();
In addition to properly synchronised UI access you need to have properly working push connection or polling to get changes to the client. If you want to use "real push" you need to add the annotation and add vaadin-push module to your app. Simpler method (and most often just as good) is just to enable polling:
ui.setPollInterval(1000); // 1000ms polling interval for client
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am having some major problems with my new project. I have a client app on my PC that is sending a simple String of data to the phone over the WiFi LAN connection. When recieved it should be split to its component parts and then an SMS sent.
I'll be honest, this is my first Android project but I'm determined to get this working.
When I send the command from my client, the app is failing and being caught in the catch labeled with Log.w("ServerRunnable", "Exception 2"); below. Id really appreciate some advice on this? I don't know why it won't work!
public class ListeningService extends Service {
private int iNotificationIcon = 1;
Handler hHandler;
Thread thServerThread = null;
private ServerSocket oServerSocket = null;
private static final String _S_DELIMITER = "##t2tDELIMITER##";
private static final int _I_SERVER_PORT = 50001;
#Override
public IBinder onBind(Intent arg0) {
Toast.makeText(this, "Service Bound", Toast.LENGTH_LONG).show();
return null;
}
#Override
public int onStartCommand(Intent oIntent, int iFlags, int iStartID) {
addNotification(getString(R.string.app_name), "Server listening on xxx.xxx.xxx.xxx:ppppp", iNotificationIcon, true);
/* Server Threading */
/*hHandler = new Handler() {
#Override
public void handleMessage(Message mMsg) {
// TODO Auto-generated method stub
showMessageBox(mMsg.getData().toString(), "Data Bundle", true);
super.handleMessage(mMsg);
}
};*/
this.thServerThread = new Thread(new ServerRunnable());
//showToast("Thread Created but not started yet", false);
this.thServerThread.start();
return START_STICKY;
}
public class ServerRunnable implements Runnable {
public ServerRunnable() {
/**/
}
public void run() {
Socket oSocket;
try {
oServerSocket = new ServerSocket(_I_SERVER_PORT);
Log.w("ServerRunnable", "oServerSocket created");
} catch (Exception e) {
e.printStackTrace();
Log.w("ServerRunnable", "Exception 1");
}
while (!Thread.currentThread().isInterrupted()) {
try {
oSocket = oServerSocket.accept();
CommsThread commThread = new CommsThread(oSocket);
new Thread(commThread).start();
Log.w("ServerRunnable", "oSocket created");
} catch (Exception e) {
e.printStackTrace();
Log.w("ServerRunnable", "Exception 2");
}
}
}
}
public class CommsThread implements Runnable {
private Socket oClientSocket;
private BufferedReader brInput;
public CommsThread(Socket oSocket) {
this.oClientSocket = oSocket;
try {
this.brInput = new BufferedReader(new InputStreamReader(this.oClientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String sRead = brInput.readLine();
//hHandler.post(new SendSMSThread(sRead));
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class SendSMSThread implements Runnable {
String sPhoneNumber = "";
String sTextMessage = "";
int iMessageLength = 0;
public SendSMSThread(String sRead) {
/* Received */
//showMessageBox(sRead, "Raw Data", true);
int iDelimiterStart = sRead.indexOf(_S_DELIMITER);
int iDelimiterLen = _S_DELIMITER.length();
/* Split the input */
sPhoneNumber = sRead.substring(0, (iDelimiterStart+1));
sTextMessage = sRead.substring((iDelimiterStart + iDelimiterLen));
//showMessageBox(sTextMessage, sPhoneNumber, true);
}
public void run() {
if ((sPhoneNumber.length() == 11) && (sTextMessage.length() > 0)) {
sendSMS(sPhoneNumber, sTextMessage, true);
}
}
}
StackTrace:
01-23 23:48:42.673: W/ServerRunnable(15567): Exception 2
01-23 23:48:42.673: W/StackTrace(15567): java.lang.NullPointerException
01-23 23:48:42.673: W/StackTrace(15567): at uk.co.tip2tail.wintextserver.ListeningService$ServerRunnable.run(ListeningService.java:78)
01-23 23:48:42.673: W/StackTrace(15567): at java.lang.Thread.run(Thread.java)
This only seems to be occuring after I have stopped and restarted the service. The initial running of the service seems to be ok, although it still does nothing when the data is recieved! Im totally lost. Every book ive read has code like i do but this just wont work!
Any help appreciated.
I had over complicated things.
I have since went back and completely changed the code for the Service, only running 2 Threads.
And it now works!
Thank you for the constructive comments above. :)
I am trying to send accelerator values over bluetooth from an Android App to the PC. I am working on the BluetoothChat demo application. In the Android App I have a method called onSensorChanged that will be called every time when the accelerations changes. the method looks like below:
#Override
public void onSensorChanged(SensorEvent e) {
// the work done when the accelerometer data changes
try {
Thread.sleep(25);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
sensorX = e.values[0];
sensorY = e.values[1];
Toast.makeText(BluetoothChat.this, "x coordinate = " + sensorX + "y coordinate = " + sensorY Toast.LENGTH_SHORT).show();
BigDecimal sensorXDec = new BigDecimal(e.values[0]).setScale(2,BigDecimal.ROUND_HALF_UP);
BigDecimal sensorYDec = new BigDecimal(e.values[1]).setScale(2,BigDecimal.ROUND_HALF_UP);
String vals = String.valueOf(sensorXDec.toPlainString() + "," + sensorYDec.toPlainString());
mChatService.writeFromString(vals);
}
The method writeFromString
public void writeFromString(String temp){
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.writeString(temp);
}
and the writeString method is the following:
public void writeString(String out) {
try {
if(D) Log.d(TAG, "Sending File....AS STRING");
mmOutStream.write(out.getBytes(), 0, out.getBytes().length);
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
in the following method I process the inputStream on the PC side
#Override
public void run() {
try {
// prepare to receive data
InputStream inputStream = mConnection.openInputStream();
System.out.println("waiting for input");
while (true) {
int command = inputStream.read();
if (command == EXIT_CMD)
{
System.out.println("finish process");
break;
}
processCommand(command);
}
} catch (Exception e) {
e.printStackTrace();
}
}
The question again is: How can I retrieve each set of Strings I am sending from the Android App?
Try this
String msg = null;
BufferedReader br = new BufferedReader(
new InputStreamReader(inputStream)
);
msg = br.readLine();
This will solve problem
Scanner scanner = new Scanner (inputStream);
while(true){
if(!scanner.hasNextInt()){
continue;
}
// at this point we've got an int, so get it and use it
try{
int commmand = scanner.nextInt();
if (command == EXIT_CMD){
System.out.println("finish process");
break;
}
processCommand(command);
} catch (Exception catchThem){
// Deal with the caught exceptions
}
}
I didn't test this, hope it works for you.
I have problem with my login application in java and flex. we use fingerprint login. the system waits for 60 seconds for any fingerprint input from the user. After that it automatically goes out of the page. The user also has text password option on that page. When user clicks on that option, control goes to some other page. But the problem is whenver user click on text password option, he is redirected but the thread of 60 seconds keep running. Can any one help me how to stop that thread. Here is my code. I am using blocking queue concept to get out of the input screen by inputting some dummy value of one bit.
private void interruptCaptureProcess() {
System.out.println("Interrupting Capture Process.");
ExactScheduledRunnable fingerScanInterruptThread = new ExactScheduledRunnable()
{
public void run()
{
try
{
if (capture != null)
{
DPFPSampleFactoryImpl test = new DPFPSampleFactoryImpl();
samples.put(test.createSample(new byte[1]));
capture.stopCapture();
}
}
catch (Exception e)
{
LOGGER.error("interruptCaptureProcess", e);
e.printStackTrace();
}
}
};
timeOutScheduler.schedule(fingerScanInterruptThread, getTimeOutValue(), TimeUnit.SECONDS);
}
/**
* Scans and Verifies the user finger print by matching it with the previous registered template for the user.
*
* #param userVO is the user value object which has to be verified.
* #return the acknowledgment string according to result for operation performed.
* #throws UserServiceException when there is an error in case of getting user record.
*/
public String verifyUserFingerPrint(Long userId) throws LoginServiceException {
System.out.println("Performing fingerprint verification...\n");
interruptCaptureProcess();
UserVO userVO = null;
try {
userVO = new UserService().findUserById(userId, true);
if (userVO != null) {
stopCaptureProcess();
DPFPSample sample = getSample(selectReader(), "Scan your finger\n");
timeOutScheduler.shutdownNow();
if (sample.serialize().length == 1) {
System.out.println("Coming in code");
return null;
} else if (sample.serialize().length == 2) {
System.out.println("Capturing Process has been Timed-Out");
return TIMEOUT;
}
if (sample == null)
throw new UserServiceException("Error in scanning finger");
DPFPFeatureExtraction featureExtractor = DPFPGlobal.getFeatureExtractionFactory()
.createFeatureExtraction();
DPFPFeatureSet featureSet = featureExtractor.createFeatureSet(sample,
DPFPDataPurpose.DATA_PURPOSE_VERIFICATION);
DPFPVerification matcher = DPFPGlobal.getVerificationFactory().createVerification();
matcher.setFARRequested(DPFPVerification.MEDIUM_SECURITY_FAR);
byte[] tempByte = userVO.getFingerPrint();
DPFPTemplateFactory facotory = new DPFPTemplateFactoryImpl();
for (DPFPFingerIndex finger : DPFPFingerIndex.values()) {
DPFPTemplate template = facotory.createTemplate(tempByte);
if (template != null) {
DPFPVerificationResult result = matcher.verify(featureSet, template);
// Fix of enh#1029
Map<ScriptRxConfigType, Map<ScriptRxConfigName, String>> scriptRxConfigMap = ScriptRxConfigMapSingleton
.getInstance().getScriptRxConfigMap();
Map<ScriptRxConfigName, String> fingerPrintPropertiesMap = scriptRxConfigMap
.get(ScriptRxConfigType.FINGERPRINT);
String fingerPrintDemoMode = fingerPrintPropertiesMap.get(ScriptRxConfigName.DEMOMODE);
if (fingerPrintDemoMode != null && fingerPrintDemoMode.equalsIgnoreCase("DemoEnabled")) {
return "LOGS_MSG_101";
}
// End of fix of enh#1029
if (result.isVerified()) {
System.out.println("Matching finger: %s, FAR achieved: %g.\n" + fingerName(finger)
+ (double) result.getFalseAcceptRate() / DPFPVerification.PROBABILITY_ONE);
return "LOGS_MSG_101";
}
}
}
}
} catch (IndexOutOfBoundsException iob) {
LOGGER.error("verifyUserFingerPrint", iob);
throw new LoginServiceException("LOGS_ERR_101", iob);
} catch (Exception exp) {
LOGGER.error("verifyUserFingerPrint", exp);
System.out.println("Failed to perform verification.");
throw new LoginServiceException("LOGS_ERR_105", exp);
} catch (Throwable th) {
LOGGER.error("verifyUserFingerPrint", th);
throw new LoginServiceException("LOGS_ERR_106", th.getMessage(), th);
}
System.out.println("No matching fingers found for \"%s\".\n" + userVO.getFirstName().toUpperCase());
throw new LoginServiceException("LOGS_ERR_107", null);
}
/* finger scanning process
*/
private void stopCaptureProcess() {
ExactScheduledRunnable fingerScanInterruptThread = new ExactScheduledRunnable() {
public void run() {
try {
DPFPSampleFactoryImpl test = new DPFPSampleFactoryImpl();
samples.put(test.createSample(new byte[2]));
capture.stopCapture();
} catch (Throwable ex) {
ex.printStackTrace();
}
}
};
timeOutScheduler.schedule(fingerScanInterruptThread, getTimeOutValue(), TimeUnit.SECONDS);
}
/**
* API will get the value for the finger scanner time out configuration(Default will be 60 seconds)
*/
private long getTimeOutValue() {
long waitTime = 60;
String configValue = ScriptRxSingleton.getInstance().getConfigurationValue(ConfigType.Security,
ConfigName.FingerprintTimeout);
try {
waitTime = Long.valueOf(configValue);
} catch (NumberFormatException e) {
LOGGER.debug("Configuration value is not a number for FingerTimeOut", e);
}
return waitTime;
}
Stopping blocking tasks in Java is a complicated topic, and requires cooperation between the blocking code and the code that wants to unblock it. The most common way in Java is to interrupt the thread that is blocking, which works if the code that is blocking and the code around it understands interruption. If that's not the case you're out of luck. Here's an answer that explains one way to interrupt a thread that is blocking in an Executor: https://stackoverflow.com/a/9281038/1109