How to readline() without blocking - stream

Im trying to readline from console input using the System.readline() stream.
I want the method to check whether a line was inserted to console, and if so check if its equale to "Exit". if a line was not inserted to the console I want the method to do nothing.
/**
* this method checks if the Exit command with written on the Servers console
*/
private void checkIfTypedExitOnKeyboard() {
System.out.println("checking if user printed Exit:-)");//DELETE TEST
long end=System.currentTimeMillis()+2000;
InputStreamReader fileInputStream=new InputStreamReader(System.in);
BufferedReader bufferedReader=new BufferedReader(fileInputStream);
try
{
while(System.currentTimeMillis()<end && bufferedReader.ready() && (bufferedReader.readLine()!=null))
{
if (bufferedReader.ready() && fileInputStream.ready() && bufferedReader.readLine().equals("Exit")){//TODO fix this
System.out.println("Reactor is shutting down");
stopReactor();
}
}
bufferedReader.close();
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
}
why doesnt this code work??
thanks:-)

Related

CXCallObserverDelegate: callChanged not triggering

I'm developing a NativeScript application which will make use of listening to the call state of the phone. For this i'm using CXCallObserver and CXCallObserverDelegate which I set up as following:
module.exports = {
phoneDelegate: NSObject.extend({
initWithResolveReject: function(resolve, reject){
var self = this.super.init();
if(self){
this.resolve = resolve;
this.reject = reject;
}
return self;
},
callObserverCallChanged: function(observer, call){
console.log("This log is not triggering");
if(call.hasEnded){
// call has ended
this.resolve({phoneState: "ended"});
}
if(call.isOutgoing && !call.hasConnected){
// Dialing out
this.resolve({phoneState: "outgoing call"});
}
if(!call.isOutgoing && !call.hasConnected && !call.hasEnded){
// Call is incoming
this.resolve({phoneState: "incoming call"});
}
if(call.hasConnected && !call.hasEnded){
// Call is ongoing
this.resolve({phoneState: "ongoing call"});
}
}
}, {
protocols: [CXCallObserverDelegate]
}),
registerListener: function(){
return new Promise((resolve, reject) => {
try{
this.callObserver = new CXCallObserver();
let myCallDelegate = this.phoneDelegate.alloc().initWithResolveReject(resolve, reject);
this.callObserver.setDelegateQueue(myCallDelegate, null);
console.log("phone listener registered");
} catch(error) {
reject({error: error});
}
})
}
}
The listener is getting registered as it should, at least no errors are thrown and the last console log in "registerListener" is executed as it should.
When I try to make a phone call, either incoming or outgoing nothing happens. At least the first console log in "callObserverCallChanged" should execute on any phone state change. But nothing happens.
Any one got any suggestion what might be wrong?
let myCallDelegate =
this.phoneDelegate.alloc().initWithResolveReject(resolve, reject);
this.callObserver.setDelegateQueue(myCallDelegate, null);
Ok the solution was quite embarrassing. The myCallDelegate instance was destroyed before doing anything due to not assigning it to the class. Well here is the solution:
this.myCallDelegate = this.phoneDelegate.alloc().initWithResolveReject(resolve, reject);
this.callObserver.setDelegateQueue(this.myCallDelegate, null);
Shoutout to tsonevn for taking his time and finding this misstake.

typo3 flow: catch exception and forward back to originating action

In my typo3 flow app I want to stop execution after throwing an exception as flash-message. Therefore I wrote this:
public function updateAction(Mitglied $mitglied) {
if ($xy == 'z') {
try {
throw new \TYPO3\Flow\Validation\Exception\InvalidValidationOptionsException('Fehler: In dieser Kombination nicht zulässig', 1);
} catch (\TYPO3\Flow\Validation\Exception\InvalidValidationOptionsException $e) {
$this->flashMessageContainer->addMessage(new \TYPO3\Flow\Error\Error($e->getMessage()));
}
}
$this->mitgliedRepository->update($mitglied);
$this->addFlashMessage('Mitglied erfolgreich geändert.');
$this->redirect('index');
}
The message ist shown, as I wanted, as flash-message. But the execution of the function doesn't stop. Does anybody know, why and how to prevent? A redirect to the originating action would be desired for the case, that the if-condition is true.
I got it now with the following code:
// get back to originating request - see https://git.typo3.org/Packages/TYPO3.Flow.git/blob/master:/Classes/TYPO3/Flow/Mvc/Controller/ActionController.php
$referringRequest = $this->request->getReferringRequest();
if ($referringRequest === NULL) {
return;
}
$packageKey = $referringRequest->getControllerPackageKey();
$subpackageKey = $referringRequest->getControllerSubpackageKey();
if ($subpackageKey !== NULL) {
$packageKey .= '\\' . $subpackageKey;
}
$argumentsForNextController = $referringRequest->getArguments();
$argumentsForNextController['__submittedArguments'] = $this->request->getArguments();
$argumentsForNextController['__submittedArgumentValidationResults'] = $this->arguments->getValidationResults();
$this->forward($referringRequest->getControllerActionName(), $referringRequest->getControllerName(), $packageKey, $argumentsForNextController);
In the end this is much easier:
$this->errorAction()->forwardToReferringRequest();

Error handling in Dart with throw catch. (Catch doesn't seem to execute)

I'm trying out Dart for the first time and I can't get the error handling to work for me. Here's some information about it.
Resources:
Gist with HTML, CSS and Dart: gist.github.com/enjikaka/8164610
ZIP with the project: ge.tt/6StW4cB1/v/0?c
JavaScript version on CodePen: codepen.io/enjikaka/pen/giurk
How I want it:
Making an instance of MinecraftSkin should throw an StateError if the image source returns a 403 error code. The exception should be handled in the generateHead() function where the instance of MineCraft skin is attempted to be made.
How it is:
If an image representing the skin of a MineCraft player does not exist (when the image source does not exist and returns 403) the code stops on line 22 (onError; where I throw the StateError) and prints to console "Breaking on exception: Bad state: User has no skin".
However, in the catch on generateHead, nothing gets executed. It doesn't print the StateError message when I prompt it to, neither does it insert the StateError message to the selected element in the DOM.
Code
import 'dart:html';
class MinecraftSkin {
String user;
CanvasElement ce = new CanvasElement();
void _generateCanvas(Event e) {
CanvasRenderingContext2D ctx = ce.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.drawImageScaledFromSource((e.target as ImageElement),8,8,8,8,0,0,ce.width,ce.height);
}
CanvasImageSource getHead() => ce;
String name() => user;
MinecraftSkin(String minecraftUser, num size) {
user = (minecraftUser == null) ? 'Notch' : minecraftUser;
ce.width = size;
ce.height = size;
ImageElement img = new ImageElement()
..onLoad.listen(_generateCanvas)
..onError.listen((_) => throw new StateError('User has no skin'));
img.src = "http://s3.amazonaws.com/MinecraftSkins/"+user+".png";
}
}
void generateHead(Event e) {
MinecraftSkin ms;
try {
ms = new MinecraftSkin((querySelector('#userName') as InputElement).value, 128);
} on StateError catch(se) {
print(se.message);
querySelector('#status').text = se.message;
}
CanvasElement cems = ms.getHead();
cems.id = "mc" + ms.name();
cems.title = "mc" + ms.name();
document.body.append(cems);
querySelector('#status').text = "Got head!";
}
void main() {
querySelector('#generateHead').onClick.listen(generateHead);
}
Thanks in advance!
Sincerely, Jeremy
The image listeners (onLoad, onError) are asynchronous. The MincraftSkin instantiation is completed without any errors, and only after the image resource is loaded or an error is received, is the StateError thrown, probably several hundred milliseconds later. The constructor does not wait around to see if the image will properly load or not.

Deferring persistence as device is being used in BlackBerry when listening file change

I tried to listen file change event in BlackBerry base on FileExplorer example, but whenever I added or deleted file, it always showed "Deferring persistence as device is being used" and I can't catch anything .Here is my code:
public class FileChangeListenner implements FileSystemJournalListener{
private long _lastUSN; // = 0;
public void fileJournalChanged() {
long nextUSN = FileSystemJournal.getNextUSN();
String msg = null;
for (long lookUSN = nextUSN - 1; lookUSN >= _lastUSN && msg == null; --lookUSN)
{
FileSystemJournalEntry entry = FileSystemJournal.getEntry(lookUSN);
// We didn't find an entry
if (entry == null)
{
break;
}
// Check if this entry was added or deleted
String path = entry.getPath();
if (path != null)
{
switch (entry.getEvent())
{
case FileSystemJournalEntry.FILE_ADDED:
msg = "File was added.";
break;
case FileSystemJournalEntry.FILE_DELETED:
msg = "File was deleted.";
break;
}
}
}
_lastUSN = nextUSN;
if ( msg != null )
{
System.out.println(msg);
}
}
}
Here is the caller:
Thread t = new Thread(new Runnable() {
public void run() {
new FileChangeListenner();
try {
Thread.sleep(5000);
createFile();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
Create file method worked fine:
private void createFile() {
try {
FileConnection fc = (FileConnection) Connector
.open("file:///SDCard/newfile.txt");
// If no exception is thrown, then the URI is valid, but the file
// may or may not exist.
if (!fc.exists()) {
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
outStream.write("test content".getBytes());
outStream.close();
fc.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
and output:
0:00:44.475: Deferring persistence as device is being used.
0:00:46.475: AG,+CPT
0:00:46.477: AG,-CPT
0:00:54.476: VM:+GC(f)w=11
0:00:54.551: VM:-GCt=9,b=1,r=0,g=f,w=11,m=0
0:00:54.553: VM:QUOT t=1
0:00:54.554: VM:+CR
0:00:54.596: VM:-CR t=5
0:00:55.476: AM: Exit net_rim_bb_datatags(291)
0:00:55.478: Process net_rim_bb_datatags(291) cleanup started
0:00:55.479: VM:EVTOv=7680,w=20
0:00:55.480: Process net_rim_bb_datatags(291) cleanup done
0:00:55.481: 06/25 03:40:41.165 BBM FutureTask Execute: net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
0:00:55.487: 06/25 03:40:41.171 BBM FutureTask Finish : net.rim.device.apps.internal.qm.bbm.platform.BBMPlatformManagerImpl$3#d1e1ec79
I also tried to remove the thread or create or delete file in simulator 's sdcard directly but it doesn't help. Please tell me where is my problem. Thanks
You instantiate the FileChangeListenner, but you never register it, and also don't keep it as a variable anywhere. You probably need to add this call
FileChangeListenner listener = new FileChangeListenner();
UiApplication.getUiApplication().addFileSystemJournalListener(listener);
You also might need to keep a reference (listener) around for as long as you want to receive events. But maybe not (the addFileSystemJournalListener() call might do that). But, you at least need that call to addFileSystemJournalListener(), or you'll never get fileJournalChanged() called back.

calling a webservice from scheduled task agent class in windows phone 7.1

Can we call a webservice from the scheduled periodic task class firstly, if yes,
Am trying to call a webservice method with parameters in scheduled periodic task agent class in windows phone 7.1. am getting a null reference exception while calling the method though am passing the expected values to the parameters for the webmethod.
am retrieving the id from the isolated storage.
the following is my code.
protected override void OnInvoke(ScheduledTask task)
{
if (task is PeriodicTask)
{
string Name = IName;
string Desc = IDesc;
updateinfo(Name, Desc);
}
}
public void updateinfo(string name, string desc)
{
AppSettings tmpSettings = Tr.AppSettings.Load();
id = tmpSettings.myString;
if (name == "" && desc == "")
{
name = "No Data";
desc = "No Data";
}
tservice.UpdateLogAsync(id, name,desc);
tservice.UpdateLogCompleted += new EventHandler<STservice.UpdateLogCompletedEventArgs>(t_UpdateLogCompleted);
}
Someone please help me resolve the above issue.
I've done this before without a problem. The one thing you need to make sure of is that you wait until your async read processes have completed before you call NotifyComplete();.
Here's an example from one of my apps. I had to remove much of the logic, but it should show you how the flow goes. This uses a slightly modified version of WebClient where I added a Timeout, but the principles are the same with the service that you're calling... Don't call NotifyComplete() until the end of t_UpdateLogCompleted
Here's the example code:
private void UpdateTiles(ShellTile appTile)
{
try
{
var wc = new WebClientWithTimeout(new Uri("URI Removed")) { Timeout = TimeSpan.FromSeconds(30) };
wc.DownloadAsyncCompleted += (src, e) =>
{
try
{
//process response
}
catch (Exception ex)
{
// Handle exception
}
finally
{
FinishUp();
}
};
wc.StartReadRequestAsync();
}
private void FinishUp()
{
#if DEBUG
try
{
ScheduledActionService.LaunchForTest(_taskName, TimeSpan.FromSeconds(30));
System.Diagnostics.Debug.WriteLine("relaunching in 30 seconds");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
#endif
NotifyComplete();
}

Resources