Handling user connections on Android - architecture tips - java

I am implementing an android based chat. I want to make it almost as low level as possible.
The reason for that is simple - i want to gain more knowledge on how things work.
I am using sockets to connect to a server. With a single socket everything is working quite well but my question is:
Will i need multiple connections when the user using the application opens multiple chat windows. If so - what is the best aproach for making those connections.
I was thinking about using something like a Util class that opens a connection when needed but i'm still not quite sure what architecture this class must have. For example would it make sense to make it a singleton class? Will i be able to keep track of all the opened connections and close them when they are no longer needed.
Any help would be appreciated.
P.S. If i missed something feel free to tell me what and i will try to edit the question to be as clear as possible.

This is clearly more of an architectural question, but I'll offer some thoughts. I would say this depends on your setup.
It sounds like you are connecting to your "contacts" directly, instead of using a central server. I assume you are determining and using the IP address directly to initiate a chat session. If this is the case, then yes, you will need to open a connection for each chat session you have going on.
If instead you are using a chat server, then theoretically, you only need one connection to that server. This server, of course, will require a connection to each user. Using a chat server requires more work on your part, but it could allow for a more user friendly experience. For example, registering your user name on the server would allow you to speak with other people via their usernames instead of having to know their IP. You still need to connect to your server via a well known IP address or DNS name, however.
As for class architecture, I highly recommend you check out something called "Dependency Injection". Dependency injection in practice usually means you interact with services and providers through an interface. The actual class that implements the interface is also written by you, and "injected" at run time. This allows you to decouple your application from a specific technology or protocol, which means that someday, you can replace your custom sockets implementation with, say, a web service implementation without having to make changes to the code that uses the service. In addition, most dependency injection frameworks allow you to specify how classes are instantiated and used when they are injected. You can use configuration to specify if one and only one class will ever be instantiated (effectively a singleton), or if a new class will be instantiated each time the service is requested.

Related

Implement Java Web Server with database, GCM and background threads

I am trying to create a web server that provides web service functions, communicates with android devices using GCM, uses a database and probably also has some background work to do.
I am currently unsure on the architecture of such a server.
I know how to create a simple web service, but have not found tutorials or descriptions that go beyond simple "Hello World" examples. As far as i know i can create a class with the #WebService annotation, and once deployed to e.G. Tomcat the server will create at least one instance of this class and provide the annoteted functions in this class as web services.
Now i wonder how to best implement database connection. From what i know the server would create an instance of this class for every request, wich will be garbage collected once the connection is closed. Since the web server needs the database for nearly every function it provides i think it would not be a good idea to create a database connection for every instance, but rather use a global connection to query the database.
From what i found out so far this could be achieved by injecting a class that handles the database connection as #Resource or #Singleton into the web service class.
But is this the proper way to do this ? Or am i worring too much and just creating a new database connection for each request is fine ?
Then i want to send GCM messages (the simple POST ones using the HTML google server), so i would probably create a controller or manager class to handle these requests. Would this also be injected as a #Resource or #Singleton into the web service class ?
And last but not least the server probably has to do some work periodicaly, wich would be some kind of background thread, that is independant of the requests the web service is recieving. Here i am at a loss on how to do this. A web service does not have a main() method i am aware of, so i am unsure on how to create this.
Can anyone give me a guick overview on how to design such a web server or can point me to documentation that describe on how to achieve this ?
All i found so far were simple examples that don't cover advanced stuff like this.
Ok, so you have 3 questions/problems.
How to create a Webservice
How to manage database connections
Execute batch process
All of this, in the same App. First of all, I should advice you to split into 2 app, one for consume (Web Services) and another for batch processing, including push notifications (IMHO). But lets go one step at a time.
1. Webservice: It's depends on the framework you choose. I usually made a choice between Spring-MVC or Jersey
2. How to manage database connections When you are querying a database, you usually don't want to open and close connections crazily. You want to use a connection pool. In a connection pool you'll ask for an open connection, will use it, and will free it when you are done. Normally, a connection pool is managed por the application server. If you want to manage the connections manually, you have to use a singleton to centralise acquiring and releasing.
3. Execute batch process You probably should use a singleton to manage batch process. This job manager will launch the job executions on other threads
Don't know if that answers your question/concern.. please let me know.
Ryu,
I found myself in a similar scenario. After going through the webs for over 2 days, I stumbled upon this solution of running a background thread which is triggered during the initialization of a servlet(init method).
Perhaps you can give this a shot and let me know if it works for you.
Here's the link which has an example to try - http://docstore.mik.ua/orelly/java-ent/servlet/ch03_05.htm
Cheers!

What is the advantages in using rmi without connecting to the database directly

We have asked to design an application for a company which has 10 branches.
they need a distributed database app, using that they can store and retrieve data of other branches. In order to achieve that i'm planning access the database through a network using the ip address for the connection string.
But i found some articles which say that using RMI
technology is the best way to achieve this. But i can't find any detailed advantages using rmi over directly connecting the apps to the database. Is it necessary to use RMI technology?
I don't know about rmi. Please give me a detailed answer. Thanks in advance.
Is RMI the best technology for doing this? We'd have to agree on "best". But my first reaction is "no".
The answer depends on whether those branches access the data over a secure network, internal to the company, or if they do it via browser and the public Internet.
RMI might be acceptable if all the branches are inside the firewalls on the same secure network. If all of them can deal with Java clients you'll be able to make it work.
But if they're going over the public Internet the only solution that makes sense is HTTPS through port 443. Clients will be written in HTML5 and CSS3 to run in browsers.
Regardless of the answer to that question, I think you want to put an intermediary between clients and the database in every case. You don't want clients accessing data directly, because it's insecure. The intermediary will be responsible for:
Authentication and authorization of users.
Validating request data.
Binding requests to queries to avoid SQL injection attacks.
Logging and monitoring.
Transaction maintenance.
RMI makes sense only if all the servers and clients are Java-based.
A more modern approach would use HTTP web services, either SOAP or REST, instead of RMI. This has the advantage of working with non-Java clients. You'll be in a better position for mobile clients that way, too.

Java Swing client server synchronization and not reinventing the wheel to keep consistency

I need to implement a proof of concept application Swing application where there's a server having a list of users and several clients which connect to the server and do CRUD operations on the database and hence on the list of users.
I have an obvious synchronization dilemma of keeping all clients lists updated so that if one client removed a user another one who still has it in his list cannot change its name.
Now I know a protocol in which before updating a user the client asks the server whether it still exists would work.
However this is just a simple example but in the real application I might have junction tables and complex references between objects which need always to be kept consistent and I don't want to reinvent the wheel.
What I'm wondering if there's some ready made solutions or some library which does this job which doesn't require me to change database or load extremely complex dependencies.
I did some research on Google but nothing seems to fit and the most similar example of client server synchronization I found was "chat programs", however chat programs are inherently simple because a message is never modified or deleted and all you have to keep consistent is the chronological order. I would need something more involved than that or some useful hints on the subject.
What you need is some sort of messaging between server and clients. Clients will either long-poll the server, asking for the updates, or subscribe to some streaming endpoint on your server.
You can take a look on Comet model, long-polling itself, websockets, etc.
Alternatively - there are couple of data management servies - BlazeDS, GraniteDS or any similar purpose solution. You can integrate one of those in your application and use for complete data management cycle.

JMX scalabilty: can it be used to manage 400+ instances?

I'm evaluating solutions for managing 400+ instances of a kiosk-like application. Each instance runs a custom Java application that displays information and interacts with users. We are pondering if we should develop a custom solution, try to include JMX support for it or find something else.
The requirements are simple:
It must be a free and open source solution;
It must be able to manage more than 400 instances (for example: one manager managing 400 JMX-enabled clients);
It should be preferably programmed in Java;
We need standard metrics (for example: available resources, running times, current status, etc);
Optionally we would like to send some control messages to the instances.
It seems that JMX features and flexibility is what we were looking for. However, I haven't found much about JMX scalability. How many "clients" can one JMX manager handle? Is it possible to manage 400 JMX instances concurrently? Is there any recommended architecture or workaround if it doesn't handle so many clients directly?
Thanks for any hints
JMX is exactly what you want.
As far as how many clients you can connect to, I'd imagine that for the monitoring portions of it, you'd only really need to fetch data from the remote clients every few seconds, at the most, right?
I'm not sure if a solution already exists which will allow you to monitor N clients and also control them, so you'd likely want to develop something yourself - interacting with remote MBeans with JMX code seems to be trivial, which then turns this into an exercise of being able to write a program which can concurrently communicate with 400 nodes successfully.

Communication between two Web Services

I have a problem with web services. They are programed in Java and are running on a WASCE server ( both are on the same server).
My problem that i want to solve:
We have two Web services: App1 and App2
In App1 i want to call a function that is in App2. How can i do this? Is this even possible?
I tried creating a soapClient inside the App1 so i can connect to the App2 but that doesn't work.
exp:
I have a client that calls app1 gets data from app1 and send it to app2 then get back the response data from app2 and send it to an other function into the app1.
What i want to do is to skip the client part and do it directly so that app1 can send directly the data to the app2 and then receive an answer do whatever it needs to do.
For the note: Both of the web services use the connection to the database.
Thank you in advance.
(it has been edited with additional data)
What does "doesn't work" mean? Exactly what happens?
Start by generating some client code for App2. Can you use that from some simple Java environment, or say a Servlet. If that works, what happens when you try to call it from inside your App 1 Service implementation code?
However: if these are related services running in the same JVM can you not set up some simpler relationship using java libraries. My preferred way of developing a service is first to develop some useful Java code, and make sure that works, then "wrap" it as a Web Service. In which case I have a callable routine that can just be invoked as Java.
It's definitely possible, with differing levels of complexity and feasibility depending on exactly what it is you want, and the restrictions you place on it.
Probably one of the simplest ways to go about this, if you don't have a problem with the method in App2 being public, is to simply create a web service exposing that method and call if from App1.
If you want App2's method to be essentially "protected", so that it can be called by App1 but not by public clients, then there are several alternative options. Firstly, you could use firewalls or equivalent to prevent external requests to the service URL. Alternatively, you could expose the method through some form of interprocess communication; RMI would be the obvious native one for Java (set up an RMI method in App2 and export this through a manager, then obtain the reference in App1 and invoke the method remotely). Depending on exactly what it is you want to do, you may be better off with a framework that does all this under the covers; e.g. distributed objects through something like Terracotta.
You should give more detail in your question, though - currently the only thing you've really specified is that you want to call "a function" in App2 from App1. There are dozens (if not hundreds) of ways to go about this and the best one(s) will depend on the details of what you're trying to do.
EDIT (in light of comments): It's not the details of what you want to do that are lacking - I understand fine that you want to call some method in App2 from within App1. It's more the architectural details - what languages are both clients coded in, what libraries are you using to do the web services, are both clients on the same machine or separate ones (and if same machine, same JVM or not), are there any firewall issues that could inhibit certain kinds of connectivity, are there any office-political restrictions that could inhibit your options, are there any security restrictions that could do the same (such as whether you can expose the functionality of App2's method publically or not). All of these will shape what is possible and what is optimal - because at the end of the day, all networking is basically I want to use resources on that remote computer from here. Without more architectural specifics, there are literally dozens of ways that you could achieve this.
Regarding exposition: You would create a web service to expose App2's function in the same way you would create any other web service (with the details being dependent on the tool/framework you're using). As an example if you're using a tool that supports the JSR-181 annotations, you'd write a method in App2 that performs this function, and annotate it with #WebMethod. Then you'd ensure that if this method is not part of an existing webservice class you'd annotate its class with #WebService. I was presuming that since you already have a couple of web services, you'd know how to write/define them.
As for accessing the web service from App1, this can be done quite simply by a Java SOAP client. A tool such as WSDL2Java can create a stub class modelling the remote service that you can call; alternatively you can get a richer interface with something like CXF.
What WS library are you using currently, and what errors have you encountered when trying to use it to perform this interaction?

Categories