Capturing windows event with java windows services - java

I want to capture lock/unlock/start/shutdown/log off and log on events through a windows service and then I want to fire a function for each event so that I can capture the time when Event occured.
I want to do this through a windows service so that I need not run the program manually. And I want to run this program through java language.

Looks like you will need to use JNA and write the capture code with native Windows calls.
There is a class java.awt.Robot that does the reverse -- simulating OS events but I am not aware of the way to capture events in pure Java.

In C# it is pretty straightforward. I can show you code in C#, you can then convert it to Ja.Net if you want to use Java as a language. (if you actually want to use JVM, this won't help as much though).
Create empty C# service.
Inside your program Main method set CanHandleSessionChangeEvent property to true:
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
LogService logService = new LogService();
logService.CanHandleSessionChangeEvent = true;
ServicesToRun = new ServiceBase[]
{
logService
};
ServiceBase.Run(ServicesToRun);
}
in service implementation override OnSessionChange event, where you can dump information on user logon/logoff and session connect/disconnect
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
EventLog.WriteEvent(
new EventInstance(100, 0, EventLogEntryType.Information),
String.Format("Reason: {0}, SessionId:{1}", changeDescription.Reason, changeDescription.SessionId));
base.OnSessionChange(changeDescription);
}
Register service, start it up and see records in event log.

Related

Calling the voice-input feature - CodenameOne app (iOS port)

My Android app features a text input box that has a button on the right of the EditText to call the voice-input feature.
I am porting the app with Codename One. At present time the iOS port is the goal.
The button has a suitable icon. This is the code:
voiceInputButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
try {
activity.startActivityForResult(voiceIntent, RESULT_SPEECH_REQUEST_CODE);
} catch (ActivityNotFoundException ex) {
}
}
});
It works very well, the voice-input screen is called and then the result is passed back to the app as a string.
The string is what the user said (for example, a single word).
I need to have this functionality in the CodenameOne app for iOS.
What should be the equivalent? Is it necessary to call native iOS functions, through the native interface?
You can implement speech-to-text via Speech framework, to perform speech recognition on live or prerecorded audio. More info: https://developer.apple.com/documentation/speech
About Codename One, you can create a native interface using Objective-C code.
To use the Speech framework with Objective-C, see this answer:
https://stackoverflow.com/a/43834120
The answer says so: «[...] To get this running and test it you just need a very basic UI, just create an UIButton and assign the microPhoneTapped action to it, when pressed the app should start listening and logging everything that it hears through the microphone to the console (in the sample code NSLog is the only thing receiving the text). It should stop the recording when pressed again. [...]». This seems very close to what you asked.
Obviously the creation of the native interface takes time. For further help, you can ask more specific questions, I hope I have given you a useful indication.
Lastly, there are also alternative solutions, again in Objective-C, such as: https://github.com/Azure-Samples/cognitive-services-speech-sdk/tree/master/quickstart/objectivec/ios/from-microphone
You can search on the web for: objective-c speech-to-text

Android SDK, Check if device is Amazon-FireTV

I am trying to write a simple piece of code that will execute some other code if true. What I want to do is check if my app is running on the 'Amazon Fire-TV (BOX, not the Fire-TV stick)' I think it would not be that hard to do but I am guessing it would be something like this?
String osName = android.getSystemOS();
if(!osName.equals("AMAZON FIRE-TV")){
Toast.makeText(MainActivity.class, "This app may not be compatible with your device..., Toast.LENGTH_LONG").show();
...
}
You can check any device name specifically using:
boolean isFireTV = Build.MODEL.equalsIgnoreCase("AFTB");
(see this page for FireTV model strings, and this one for Fire Tablets)
I'd also check out this answer for a more generic test to help you determine if your app is running on an Amazond device, or installed via the Amazon AppStore (eg on a Blackberry device)
the following function:
public static boolean isTV() {
return android.os.Build.MODEL.contains("AFT");
}
should detect either firetv or fire tv stick
see
https://developer.amazon.com/public/solutions/devices/fire-tv/docs/amazon-fire-tv-sdk-frequently-asked-questions
for details

Listening for LogCat Entires made by my own application

Am I able to listen for messages being places into the LogCat by my own application?
For example something like...
// Somewhere in my application (on a background service):
Log.i("myModule", "Something been done");
and....
// Somewhere else something like...
LogCatListener logCatListener = new LogCatListener()
{
public void onInfoRecieved(String tag, String message)
{
//Do whatever you want with the message
}
}
I'm an Android noob so be gentle with me!
Thanks.
Unfortunately it looks like you directly can't do that for typical Log calls (.d, .i, .w). If you look at the source code of the Log class (https://android.googlesource.com/platform/frameworks/base/+/android-4.3_r2.1/core/java/android/util/Log.java) you'll see that these calls are just translated into a println_native, a private function mapped to a native implementation.
Also, the Log class is final, so you can't extend it and hook into .d , .i , .e, .w
I'm afraid your only solution is to write a Log class wrapper if you need to capture those calls. This will work for your custom Log's but obviously not for the system-issued calls to the Log class.
But good news is there's a special Log function that allows listeners. There's a funny method on the Log class:
public static TerribleFailureHandler setWtfHandler(TerribleFailureHandler handler)
And you can set a handler that will be called when you do
Log.wtf (TAG, message)
funny google method names :)

Using Telegram API for Java Desktop App?

I am not that new to Java Programming, but I have never worked with external libraries etc. Now I want to develop a desktop client for the "Telegram" open-source messaging platform, and I'm stuck when it comes to API-Usage.
There is pretty much documentation about the Telegram API, found at https://core.telegram.org/api, and I've already downloaded mtproto, telegram-api and tl-core from github, and compiled my own library jar from source by using gradle. As well, I've already written a small application, where the user clicks a button and is promted to enter his phone number, I'm using the Java-swing-Libraries and an ActionListener for this.
The phone number entered by the user should now be checked if it is already registered, the auth.checkPhone method seems to be capable for that. But how can I refer to it within my eclipse project? I don't see any method "checkPhone" in any of the classes! What should I do?
Please help me, I can't help myself and I am desperately stuck in my project. Even a small hint would help.
Thanks in Advance,
Lukas
Essentially you will have to fill out the blanks in the code given on GitHub in the ex3ndr/telegram-api repository. If you've got the library Jar file you built and the tl-api-v12.jarfile on your Eclipse project's Java build path, then look at the RPC Calls section of the README and
First you need to set up an AppInfo object with your API credentials, then you will also have to create some new classes that implement the AbsApiState and ApiCallback interfaces. Once these are available, you can create the TelegramApi object and make an RPC call to the Telegram service as follows; in this case using the suggested auth.checkPhone method:
// TODO set up AbsApiState, AppInfo and ApiCallback objects
TelegramApi api = new TelegramApi(state, appInfo, apiCallback);
// Create request
String phoneNumber = "1234567890";
TLRequestAuthCheckPhone checkPhone = new TLRequestAuthCheckPhone(phoneNumber);
// Call service synchronously
TLCheckedPhone checkedPhone = api.doRpcCall(checkPhone);
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
The TelegramApi object represents your connection to the remote service, which is a request response style of API. RPC calls are made via the doRpcCall method, which takes a request object from the org.telegram.api.requests package (the TLRequestAuthCheckPhone type in the example) filled in with the appropriate parameters. A response object (TLCheckedPhone above) is then returned with the result when it is available.
In the case of an asynchronous call the method returns immediately, and the onResult callback method is executed when the result is available:
// Call service aynchronously
api.doRpcCall(checkPhone, new RpcCallbackEx<TLCheckedPhone>() {
public void onConfirmed() { }
public void onResult(TLCheckedPhone result) {
boolean invited = checkedPhone.getPhoneInvited();
boolean registered = checkedPhone.getPhoneRegistered();
// TODO process response further
}
public void onError(int errorCode, String message) { }
});
Or just look at this API https://github.com/pengrad/java-telegram-bot-api
It is really simple to use

Custom message when closing a part in Eclipse RCP 4

we have the following problem:
In our Eclipse RCP 4 application there are multiple parts and the parts are closable. When the user is closing a part there should be a custom pop-up (depending on some internal part state) which is asking the user if he really wants to close the part or not.
It seems to be not that easy to implement in Eclipse RCP 4 or we have just totally overseen something.
I'll just give you a short brieifing about the things we tried:
Use dirtable with a #persist method in the part. Though the problem is, we don't want this standard eclipse save dialog. So is there a way to override this?
public int promptToSaveOnClose(): This seemed to be promising but not for Eclipse 4 or is there a way to integrate it that way? Compare: http://e-rcp.blogspot.de/2007/09/prevent-that-rcp-editor-is-closed.html
Our last try was to integrate a custom part listener, simple example shown in the following:
partService.addPartListener(new IPartListener() {
public void partVisible(MPart part) {
}
public void partHidden(MPart part) {
partService.showPart(part, PartState.ACTIVATE);
}
public void partDeactivated(MPart part) {
}
public void partBroughtToTop(MPart part) {
}
public void partActivated(MPart part) {
}
});
The problem with this was we are running into a continuous loop. Something similar is posted over here in the last comment: Detect tab close in Eclipse editor
So I could write some more about this problem, but I think that's enough for the moment. If you need some more input just give me a hint.
Thanks for helping.
The save prompt is generated by the ISaveHandler registered in the context of the MWindow containing the MPart. You can write your own ISaveHandler and set it in the window context to replace the default.
You might also want to look at the IWindowCloseHandler also in the window context.
Thanks greg, this has helped and I was able to achieve changing the pop-up when the user closes a part. Here's a short description of what I've done:
Use the MDirtyable for marking the part as dirty whenever it's needed.
Create a custom save handler which implements ISaveHandler (when a part got closed the save method is called). Add the additional logic to this handler (e.g. a custom message dialog)
Register this handler at application start-up (I just chose a method which is called at the start-up):
#Inject
private MWindow window;
...
ISaveHandler saveHandler = new CustomSaveHandler(shell);
window.getContext().set(ISaveHandler.class, saveHandler);
Note that the registration via a model processor was sadly not that easy because the model processor is called too early. (Take a look at: http://www.eclipse.org/forums/index.php/t/369989/)
The IWindowCloseHandler is just needed when the complete window is closed, though this was not an requirement for us :).

Categories