developing android application with server using web service - java

I am developing client/server apps (the client is an Android application which sends data to the server). I am developing the server using Java. I already connected the sever application "using NetBeans" using SQL Navigator 5.5. I want to use Json as a middle ware, but I don't know how! What is the most suitable, XML or Json? Do i need to use HTTP? If so, how (as I want to be able to secure the application)?
The other thing that the server should respond to is the Android application by sending "longitude and latitude", for which Android should "geocode" and display on the form of map "location." Also, I need to understand more about the concept of web service that should work on the application.
This is the server code:
(The values that the server should get from the client are "long and lat")
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pkg;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
#WebService(serviceName = "lbsws")
public class lbsws {
/** This is a sample web service operation */
#WebMethod(operationName = "hello")
public String hello(#WebParam(name = "name") String longg) {
String result=null;
try
{
Connection con = dbConnection.getdbConnection("system","lbs","orcll", "localhost");
Statement st = con.createStatement();
String lat ="10";
String query="select longg,lat,abs(("+longg+"-longg))/abs(("+lat+"-lat)) as function1 from lbs where abs(("+longg+"-longg))/abs(("+lat+"-lat)) = ("+
"select min(abs(("+longg+"-longg))/abs(("+lat+"-lat))) from lbs)";
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
result = rs.getFloat("longg")+","+ rs.getFloat("lat")+"-"+ rs.getFloat("function1");
}
}
catch(Exception e)
{
System.out.println(e.toString());
}
return result;
}
}

A few things:
1) JSON Thumbs up for the transport layer. Don't give it a second thought.
2) Consuming JSON Web Services. Use HttpClient in Java based systems. Just to get the response back
than you can convert JSON to objects as needed. But calling web service is via HttpClient
3) Creating JSON Services. Well you could use Jersey. There are a few choices. I would recommend developing in Tomcat server. Its faster and not so much up/down as with Java EE servers. There are some other good choices beside Jersey.
But mainly write the simplest thing first and get it working from end-to-end. Thats what you want to do.
Just produce a service that returns the Sytem time and send that back via JSON consume it on the client and display. Then re-evaluate Jersey vs. whatever. But get something running end to end.
So step one is write a JSON Web Service and just test it in the browser. Don't worry about client side right now. Just get the service running and invoke it using the browser. BTW, there are reason to go with RESTful JSON web service. Its a good way to structure your web services.
Never attack two problems at the same time. Forget about connecting to a database until you have got the service up and running with just data that is stubbed out.

Related

Java httpservlet and routing. How starting?

my boss asked me to develop an webservice that should work in this matter:
an external app contact my app and:
if the method used is GET and the url contacted is:
http://localhost:8080/webapp/webservice/?findall
will return all rows find in a table;
If the same external app contact my app in the same method but send a key and a value like:
http://localhost:8080/webapp/webservice/?field1=value1
my app will return a set of rows filtered by field/value.
And soon on with with any method sending request and with other fields.
I know how do the operations using JPA 2.1 but how mapping the actions?
Someone could help me to starting in the right direction with JDK1.8?

how to set request time out of web service client(java)

I am working on a desktop based application that is like drop box, I have a function downloadFile(long fileId) that download file for me from web, desktop side of the application is in java where web service is written in .Net
I have generated WS client using netbeans
The issue is: Some times it happens that downloadFile(long fileId) function get stuck,
What ever the reason behind it, I want if web service function does not give any response till a given time I snatch the control back from that function and generate a new call after some time. Is it possible using java?
EDIT I think that it could be done if can set the request time out of the web service but i don't have idea how to set time out in the client generated by netbeans
In the class FileUpload that is root class of web service(Generated by netBeans) there were some constructors of the class and function of the super class, one of them i was using to create SOAP object. That was looking like
#WebEndpoint(name = "FileUploadSoap")
public FileUploadSoap getFileUploadSoap() {
return super.getPort(new QName("http://svc.qleapahead.com/",
"FileUploadSoap"), FileUploadSoap.class);
}
in this function i made some modifications in order to set time out parameter and this became like
#WebEndpoint(name = "FileUploadSoap")
public FileUploadSoap getFileUploadSoap() {
FileUploadSoap fileUploadSoap = super.getPort(new QName(
"http://svc.qleapahead.com/", "FileUploadSoap"),
FileUploadSoap.class);
((BindingProvider) fileUploadSoap).getRequestContext().put(
"com.sun.xml.internal.ws.request.timeout", 1000 * 2 * 60);
return fileUploadSoap;
}
and problem solved...
in short this statement helped me a lot
((BindingProvider) fileUploadSoap).getRequestContext().put(
"com.sun.xml.internal.ws.request.timeout", 1000 * 2 * 60);
Depending on the framework you use for calling the webservice, there will be some way of setting a readTimeout causing the call to fail with some kind of exception.
Cheers,

comunication between Web browser and java

I Am developing a private web site in PHP-html / Ajax and a client program in Java.
I have just seen that apple can, by Firefox or other, open iTunes to load content.
I want to do the same or better:
I try to make a program which can “talk” to javascript or just write a lockFile (tempfile) and so get data through this one, i try to get at least a communication Web browser - > java, but i'd rather if possible a bi-directional communication.
So if somebody have any solution, it’s will be great cause I googlised it, i tried local Storage in html5, File access in javascript … nothing really works and I don’t want the program to ask the server Avery time.
You can do this in a number of ways but you must have in mind the cross-domain restrictions. I've been doing this with sockets.
1 - You need a bridge to comunicate your web with your server this could be done with a java applet or a flash socket bridge so that you can call your server and your javascript client code.
2 - You need url-redirect rule in your server so that when your client makes a request it always makes it in the same domain but gets where your socket server finally is. You client can't go to a different domain but your server can. This is needed to skip the cross-domain restriction.
I hope this helps.
You can take a look at JxBrowser library that allows embedding Google Chromium engine into Java Swing applications. You can use this library to embed Browser component into your client Java application and load your PHP web page, like iTunes loads App Store.
It provides API for two-way communication Java-to-JavaScript-to-Java: http://www.teamdev.com/downloads/jxbrowser/docs/JxBrowser-PGuide.html#javascript-java-bridge
The following code demonstrates how to embed Browser component, load URL, invoke JavaScript code on the loaded web page and register Java function on JavaScript side that will be invoked every time when JavaScript invokes it:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.BrowserFactory;
import com.teamdev.jxbrowser.chromium.BrowserFunction;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
/**
* The sample demonstrates how to register a new JavaScript function and
* map it to a Java method that will be invoked every time when the JavaScript
* function is invoked.
*/
public class JavaScriptJavaSample {
public static void main(String[] args) {
Browser browser = BrowserFactory.create();
// Register "MyFunction" JavaScript function and associate Java callback with it
browser.registerFunction("MyFunction", new BrowserFunction() {
public JSValue invoke(JSValue... args) {
for (JSValue arg : args) {
System.out.println("arg = " + arg);
}
return JSValue.create("Hello!");
}
});
// Create JFrame and embed Browser component to display web pages
JFrame frame = new JFrame();
frame.add(browser.getView().getComponent(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Register Load listener to get notification when web page is loaded completely
browser.addLoadListener(new LoadAdapter() {
#Override
public void onFinishLoadingFrame(FinishLoadingEvent event) {
if (event.isMainFrame()) {
Browser browser = event.getBrowser();
// Invoke our registered JavaScript function
JSValue returnValue = browser.executeJavaScriptAndReturnValue(
"MyFunction('Hello JxBrowser!', 1, 2, 3, true);");
System.out.println("return value = " + returnValue);
}
}
});
browser.loadURL("about:blank");
}
}

Communication between two Machines using java

I have Gui Application written which running on windows,and i want to connect to remote unix machine and perform actions there such like API's ,go over the log file in the machines and send back to the application the last log file or others API that i want to perform on the remote machine.
In the remote machine i don;t have application server i just have Java which installed there.
I want to use Java in order to perform remote API over the remote machine;
what is the advice ,can i use web services ,can any one please advise.
Thanks in advance.
If Java can perform the actions you're talking about, I would use Sockets to communicate with the UNIX-Machine (over TCP/IP).
Your Windows-PC would be the client sending commands to the Unix-PC.
Web services would be a bit heavy handed option, esp if you opt for the SOAP ones. If you don't have a problem with the client and server always being Java, RMI seems to be the simplest solution to this problem since it's communication between two different JVM's using the normal method calling mechanism (with some additional interfaces and rules to be followed to please the RMI specification).
The Spring Framework ships with a number of remoting options that are all very easy to setup. You can use their classes for simpler configuration of something standard like RMI or JMS, or use a lightweight web services protocol such as Spring's HTTP invoker or Hessian.
For analyzing log files of remote machines you can always use Apache Commons sftp programmatically to FTP a copy of the remote log file to your PC.
If you configure the log files to be rotatable or to rotate each time they reach a specific size, you can avoid reloading the same information over and over.
You can use Ganymed SSH-2 for Java to ssh to the remote host from Client Java App and run the commands. No need to run any additional components on remote server. You can do password based authentication or key based authentication to login to remote host. We had successfully used it to administer (start/stop/grep log files, etc.) applications running on remote UNIX hosts. You can capture output of the remote command using the StreamGobbler class provided in the package. You can pass multiple commands separated by semi-colon in one remote call.
Basic Example included in the package:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class Basic
{
public static void main(String[] args)
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";
try
{
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("uname -a && date && uptime && who");
System.out.println("Here is some information about the remote host:");
/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}
/* Show exit status, if available (otherwise "null") */
System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}
}

Is there any free java open source application that can monitor website status?

Anyone know any? I need to send in a http request and make sure the http response i got back is not http 500
I believe Hyperic HQ meets all of your criteria. It is open source, I believe it is written at least partially in Java, and it is designed to do all kinds of server monitoring.
It should be able to handle not only the kind of monitoring you requested but other necessary monitoring like memory, CPU usage, and disk space on your servers as well.
You could use httpunit - web-centric unit testing
While you find it you can use this:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.IOException;
public class SimplisticMonitor {
public static void main( String [] args ) throws IOException {
HttpURLConnection c = ( HttpURLConnection )
new URL( "http://stackoverflow.com" ).openConnection();
System.out.println( c.getResponseCode() );
}
}
If you want to do this yourself, Apache HttpClient is an option:
GetMethod get = new GetMethod("http://www.stackoverflow.com");
try
{
int resultCode = client.executeMethod(get);
if (resultCode == 500)
{
//do something meaningful here
} // if
} // try
catch (Exception e)
{
e.printStackTrace();
}
finally
{
get.releaseConnection();
}
http-unit
Written in Java, HttpUnit emulates the relevant portions of browser behavior, including form submission, JavaScript, basic http authentication, cookies and automatic page redirection, and allows Java test code to examine returned pages either as text, an XML DOM, or containers of forms, tables, and links. When combined with a framework such as JUnit, it is fairly easy to write tests that very quickly verify the functioning of a web site.
or html-unit
HtmlUnit is a "GUI-Less browser for Java programs". It models HTML documents and provides an API that allows you to invoke pages, fill out forms, click links, etc... just like you do in your "normal" browser.
It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use.

Categories

Resources