Android App code design message handling for commands - java

I'm having two main code design problems in my app.
My app mainly consists in sending ssh commands to a remote host.
Right now I have a separated thread (singleton) which gets messages through the handler which specifies which is the next command to be sent, or the username/password/ip (kind of messy but works...).
This approach works good for unidirectional commands, but I'm planning to make it bidirectional which I don't know how to implement. As far as I know Android doesn't allow to change UI elements by another thread so a listener pattern wouldn't be it.
Also, I just read that we shouldn't save things in the application object, which is also what I'm doing by saving whether my app is running full or lite mode... I don't know where should I save it in order to not make it obviously hackable (sqlite-SharedPrefs are easily editable...)

Only a general hint: There is Activity.runOnUiThread() to execute code (later) on main thread.

Related

Notify a separate JVM to preform a task

So I am making a program that will only run one instance at a time and am doing so by using this solution
However now I would like to make it so that if the user trys to launch another instance it will consume that attempt and notify the current instance to show its gui.
Currently I am thinking about doing this by the use of a file. Upon the launching of a second instance, a file called show.stage will be created. When the other instance detects that file it will show its gui and delete the file.
I know this works but I was wondering if there was a more graceful way to do this.
Could I some how set a environment flag that the other instance could check for or maybe notify it via a socket listener, although those seem to be discouraged by others. I get the feeling creating the file will be the easiest and most robust way but I am open to any suggestions
This program will be running on normal windows.
If you don't want to use a lock file (which I think is a perfectly good solution), you can use sockets.
Have your application create a socket server and listen at some port in localhost. If it fails to listen, it would mean that someone else is listening to that port already - most likely, another instance of your app. You can even connect to that port and send messages to notify the primary instance that a second instance tried to be spawned.
The caveat is that if another app legitimately uses that port your app would never be able to run - but I find that very unlikely to happen.
There are many ways to go about this:
as you already figured, the file system can be used as communication channel between two jvms. But that only works for jvms running on the same server.
thus the already suggested socket solution enables you to (later) apply the same solution to a distributed environment. The downside is that you have to implement a protocol on a very low level.
in the past, people often turned to message bus solutions (think ActiveMQ for example)
in 2018, the other alternative would be to implement a simple restful API, using jaxrs and jersey for example.
As said: the effort you want to put into this depends on your requirements. How long will it be used? What are the odds that your solution will grow and has to scale to more than one server?!
try to use pidfile as lock and process single like kill 9 as communication tool

How to get information from a Java Process?

So, say I have multiple instances of a java program running, and I need to get information from each instance, ie if the program is performing its function correctly and if its not I need to get information to the process on what to do, I essentially need to open a tunnel. How would I do so? I hope this question isn't to vague.
I'm basically writing a manager, the manager loads a bunch of clients and I need a way to communicate between the manager and each client.
Have you looked into Java Management Extensions? It's built-in and made for monitoring java processes:
http://openjdk.java.net/groups/jmx/
if you need to look at custom info for your processes (some state of execution, or some special log info), you can create your own info-providers (aka "MBeans"):
https://blogs.oracle.com/WebLogicServer/entry/developing_custom_mbeans_to_ma
hope that helps

Java - Online game, should the game happen in the server or the client?

I'm implementing a multiplayer option for a chess game I made, but I'm starting from zero to do both client and server. A friend said to me to make the game happen in the server, and the client only gets the data and shows in the GUI. Does this means that I have to implement the game in the server (without GUI); and in the client project, just the GUI, actionListeners and stuff, so that, for example, when I click on a piece and then click where I want it to go, the server will "make" the move (set new position etc) and then send this information back to the client so that it can print? Is this the best approach?
By the way, my server can (will) host several games (each time 2 sockets connect it creates a game thread). Oh and also, after finishing the game, I want to implement a little chat in-game. Don't know if this information changes something...
Longer answer is that you really have a lot of flexibility in how you want to do this. The "traditional" way of doing this is the model-view-controller pattern, where you separate the model (game state) from the view (what the board looks like), and a controller (your server code) handles interaction between the two.
The question is where to place each section of code.
One option is to place have the client do the heavy lifting with the server acting as a middleman between clients and communicating updates. This has the advantage that servers don't need to do as much work, but results in a client that can be easily modified for cheating.
The other option is to place most of the important code on the server and simply have each client be a "dummy" display that just shows whatever the server sends and just send the bare minimum amount of information to the server for the server to determine what was done. This is more hackproof, but places greater load on the server.
You can also do a hybrid model where the both the client and the server share the load of sanity checking, so the load on either isn't quite as severe. I think that this is a pretty good option, even though it violates the "pure" MVC pattern.
What works "best" for you might depend on the kind of load you expect on your server. For a small number of connections, "pure" MVC with "dumb" clients might work. Client makes move, server verifies that the move is valid, and if so, sends updates to both clients. If your framework starts to get overwhelmed you might want to consider putting some checking code in the client though.
None of this affects having multiple pairs of clients or a chat. You should be able to implement each of those parts separately, and if done correctly piecing the modules together shouldn't be bad.

Web applications and multi-threading

I'm working on porting a desktop application (WinForm) to a web application (Java/Spring/JPA). The problems are many and I'm struggling a bit...
Now the problem is threading!
In the original application, that performs the export of certain data from the DB, there is a progress-bar indicating the progress of the process.
I want to port this progress-bar in the new web application. To do this I thought of using AJAX and use a separate thread to run the data export.
The main concerns are:
Am I following the right approach? Are there problems using multi-threading in web applications?
If during the export process F5 or refresh button are pressed what exactly happens? How can I stop the process?
How do I update the progress bar periodically? Do I have to make calls via ajax to the server?
I'm primarily an ASP.Net developer but from what I know of the HTTP protocol this just isn't the way to go about it. I've seen a lot of fairly clever solutions for this but in the end what becomes clear is that the HTTP protocol simply isn't designed to work like this.
Obviously you're aware that a flash or silverlight app would be able to do this but that comes with it's own set of issues.
Myself I prefer to keep all the weirdness on the server. In the past I've had to come up with a way to deliver several thousand emails through a web application and update the user on how it's coming along. I designed a set of tables to act as a queue. The web application would simply place any delivery requests in this queue and the progress bar would be determined by a request that checks the status of the items in the queue. Running in the background was a windows service which would also check this queue and was actually responsible for delivering the mail and setting the status of each item as it completed or failed.
It was a bit difficult to develop since windows services can be tricky but once it was up and running it was extremely smooth and reliable. Depending on your circumstances perhaps a simple scheduled task set to run every few minutes would do the trick for you.
I wouldn't necessarily jump straight to running a separate thread explicitly for the export. While it would be ideal to do this, the capability of the web container to do this is going to be a limiting factor. Your traditional Java EE app server generally discourages spawning threads for this (though you can hook up to a thread pool for this). Some containers are great at freeing up the threads from blocking until the work is done (Karaf with Jetty and Camel, for instance) so that they can service other web requests while the export is occurring. But my guess is that you're probably okay with the "start export" thread blocking until it receives a response.
How long does this export take? A couple of seconds, or are we talking closer to minutes here? If it's shorter, I'd think that just putting a little "Waiting" icon with the little circular spinner on it (using your favorite Ajax library, whatever that is) would be sufficient.
If you really want a true status bar that periodically refreshes itself, then yes you'd have to poll for it at some frequency. Presumably that could be a simple request that would load some kind of progress for the job from a database table for that job ID.
Find my answers Inline
I am following the right approach? Are there problem in using multi-threading in web applications?
-Yes you are on correct path. No there is no such problem in multi-threading in web application and its as easy as you do it in WinForm. Instead of using Dispatcher to update the UI, you would be making AJAX calls and with javascript DOM manipulation would take place.
If during the export process F5 or refresh button are pressed what exactly happens? How an I stop the process?
-Unfortunately there is no easy way. The standard way is, when such kind of processing is done and the user hits F5, you would show a dialog(with help of javascript) and inform user that the job is still running. If the user still wants to refresh then you have make another request to the server for cancelling the task.(You need to store thread id or cancellation token some where to cancel the task)
How do I update the progress bar periodically? Do I have to make calls via ajax to the server?
-The standard way is, generally you show show a loading image. IF you want to show a context senstive progress bar, it would mean you have to do polling. Here is an example by Dino Espito. Though its in ASP.NET, you could understand the underlying principle
Dino Espito

Updating an application information using other applications (plugins)

I am doing a keyboard for Android.
I am willing to have a plugin structure to allow users to improve the prediction engine.
The prediction engine is done with Android NDK and it was coded in C. I have a wrapper class that calls the C code. An instance of this wrapper class is a field in the InputMethodService.
The prediction engine gets updated by sending complete sentences. Something like:
public void updateEngine(String sentence);
Plugins should be calling that method.
An example of the plugin can be a .txt parser. You select a txt file and the plugin will start sending to the main app all sentences.
I would like plugins to be customizable, e.g.: They might have an screen where you can choose max sentence to send, to run on background, etc.
The UI (don't know if it should be on the main app or the plugin, check my questions below) should have the possibility to ask the plugin how many sentence it can send (to do a progress bar).
My questions are:
Should I use Intents or IPC?
I think I should use Intents since I just use primitive types.
Should my operations be atomic or send an array of sentences?
I am willing to start with atomic operations but I am worried about performance.
The plugins must be activities or Services?
They should be Activities and if necessary ("process on background" on) launch a service. Or perhaps they are just services and the main app takes care of the UI.
Who should save information about the last execution. Plugin or the mainApp?
e.g. When was the last time the plugin was used.
Should I use Intents or IPC?
Either works. Intents may be simpler.
Should my operations be atomic or send
an array of sentences?
I'd bundle these up into a single operation if possible. Lots of little cross-process trips is more expensive than one large one, as I understand it.
The plugins must be activities or
Services?
You appear to want the plugin to call into the engine, which is fine, but...when? Plugins won't get control automatically at install time. The choice of trigger mechanism for the plugin calling into the engine will dictate whether the plugin needs an activity or not.
Who should save information about the
last execution. Plugin or the mainApp?
This doesn't make a lot of sense to me given the rest of what you have here, so I can't comment. This may roll back to the lack-of-trigger issue I mention above. For example, under what circumstances would a plugin ever be used more than once?

Categories