Applet and Servlet communication - java

I have an applet that needs to submit a score to a servlet and it is not working correctly.
This is the code for the applet
private URLConnection getConnection() throws MalformedURLException, IOException {
URL serverAddress = null;
URLConnection conn = null;
serverAddress = new URL("http://localhost/GamesPortal/submitScore");
conn = serverAddress.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-java-serialized-object");
return conn;
}
private void sendRecievedata(GameInfo info) {
try {
URLConnection c = this.getConnection();
OutputStream os = c.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(info);
oos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
And this is the servlet code
try {
HttpSession s = request.getSession(true);
response.setContentType("application/x-java-serialized-object");
InputStream in = request.getInputStream();
ObjectInputStream ois = new ObjectInputStream(in);
GameInfo info = (GameInfo) ois.readObject();
if (info.getUserId() > 0) {
Scores score = new Scores();
score.submitScore(info);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet submitScore</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet submitScore at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} catch {
ex.printStackTrace();
} finally {
out.close();
}
Now I have tried accessing the servlet via the browser, just to make sure that the address is correct (it is), but for some reason when I try to access it from the applet itself, it does not connect. (the debugger does not even launch).
(added the ex.printStackTrace(); to each of the try catches, as per suggestion, but I have no idea what or where I'm supposed to look for this)
The code calling the applet looks similar to this:
http://roseindia.net/jsp/simple-jsp-example/applet-in-jsp.shtml
<jsp:plugin code="Pong.class" name="Games/Pong/Pong" type="applet" width="800" height="600">
<jsp:params>
<jsp:param name="userId" value="<%= user.getUserId()%>" ></jsp:param>
</jsp:params>
</jsp:plugin>
Is there something that I am overlooking here?

I have managed to make it work.
This is the code for the applet:
private URLConnection getServletConnection()
throws MalformedURLException, IOException {
URL urlServlet = new URL("http://localhost:8080/GamePortal/submitScore");
URLConnection con = urlServlet.openConnection();
con.setDoOutput(true);
con.setRequestProperty(
"Content-Type",
"application/x-java-serialized-object");
return con;
}
private void onSendData(GameInfo info) {
try {
// send data to the servlet
URLConnection con = getServletConnection();
OutputStream outstream = con.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstream);
oos.writeObject(info);
oos.flush();
oos.close();
// receive result from servlet
InputStream instr = con.getInputStream();
ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
String result = (String) inputFromServlet.readObject();
//JOptionPane.showMessageDialog(null, result);
inputFromServlet.close();
instr.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
This is the code for the servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setContentType("application/x-java-serialized-object");
// read a String-object from applet
// instead of a String-object, you can transmit any object, which
// is known to the servlet and to the applet
InputStream in = request.getInputStream();
ObjectInputStream inputFromApplet = new ObjectInputStream(in);
GameInfo score = (GameInfo) inputFromApplet.readObject();
System.out.println(score.getScore());
GameInfo info = score;
if (info.getUserId() > 0) {
Scores instance = new Scores();
instance.submitScore(info);
}
OutputStream outstr = response.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(outstr);
oos.writeObject("reply");
oos.flush();
oos.close();
} catch (ClassNotFoundException ex) {
}
}
Thanks for your help and forgive me for taking too long to reply.

Related

Java program to read objects from a .ser file located in a server

My idea is that I want to read an object from a serialized file located in a server. How to do that?
I can only read .txt file using the following code :
void getInfo() {
try {
URL url;
URLConnection urlConn;
DataInputStream dis;
url = new URL("http://localhost/Test.txt");
// Note: a more portable URL:
//url = new URL(getCodeBase().toString() + "/ToDoList/ToDoList.txt");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
dis = new DataInputStream(urlConn.getInputStream());
String s;
while ((s = dis.readLine()) != null) {
System.out.println(s);
}
dis.close();
} catch (MalformedURLException mue) {
System.out.println("Error!!!");
} catch (IOException ioe) {
System.out.println("Error!!!");
}
}
You can do this with this method
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
feed it with urlConn.getInputStream() and you'll get the Object. DataInputStream is not fit to read serialized objets that are done with ObjectOutputStream. Use ObjectInputStream respectively.
To write an object to the file there's another method
public void serialize(Object obj, String fileName) {
FileOutputStream fos;
ObjectOutputStream out;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(obj);
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}

Download image on clicking an image

I want to download image on click. I had set content type but I couldn't write image in response. In controller I get URL of image.
String image=myimageUrl;
File file = new File(image);
String contentType = getServletContext().getMimeType(file.getName());
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setHeader("Content-Length", String.valueOf(file.length()));
For writing into response I used this code
DataInputStream input = new DataInputStream(new FileInputStream(file));
ServletOutputStream output = response.getOutputStream();
Here input returns null.
How to resolve this problem?
Please check following code.
for uploading image into database.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
String path=request.getParameter("h2");
out.println(path);
Connection connection=null;
ResultSet rs = null;
PreparedStatement psmnt = null;
FileInputStream fis;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
File image = new File(path);
psmnt = connection.prepareStatement("insert into new1(id,imagepath)"+"values(?,?)");
String s1=request.getParameter("h1");
psmnt.setString(1,s1);
fis = new FileInputStream(image);
psmnt.setBinaryStream(2, (InputStream)fis, (int)(image.length()));
int s = psmnt.executeUpdate();
if(s>0) {
out.println("Uploaded successfully !");
}
else {
out.println("unsucessfull to upload image.");
}
}
catch (Exception ex) {
System.out.println("Found some error : "+ex);
}
and for downloading image.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Connection connection = null;
ResultSet rs = null;
PreparedStatement psmnt = null;
InputStream sImage;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/image", "root", "kshitij");
psmnt = connection.prepareStatement("SELECT imagepath FROM new1 WHERE id = ?");
psmnt.setString(1, "23");
rs = psmnt.executeQuery();
if(rs.next()) {
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
//response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}
}
}
catch(Exception ex){
// out.println("error :"+ex);
}
}

403 Forbidden in a servlet

I have a url of a file which works perfectly in browser and Java SE application but it gives me 403 forbidden error in servlet. Following are the codes of both Java SE program and the servlet
Java SE code
public class UrlDownload {
final static int size=1024;
public static void fileUrl(){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try{
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL("http://o-o---preferred---bharti-del2---v17--- lscache7.c.youtube.com/videoplayback?upn=6BFud0UQ_-0&sparams=cp%2Cgcr%2Cid%2Cip%2Cipbits%2Citag%2Cratebypass%2Csource%2Cupn%2Cexpire&fexp=900147%2C907217%2C922401%2C919804%2C920704%2C912806%2C906831%2C911406%2C913550%2C912706&key=yt1&itag=37&ipbits=8&signature=6EBF4572274A427AFF58E023CEC8B62439E0B914.BD6827306B81393BE3998FA0F0701E6F2701A3F8&mv=m&sver=3&mt=1345685891&ratebypass=yes&source=youtube&ms=au&gcr=in&expire=1345708167&ip=116.203.237.173&cp=U0hTSldLVl9LUUNOM19PRVpCOkV6WE5pcUF1NjQ5&id=9d8c9310d90eae67&quality=hd1080&fallback_host=tc.v17.cache7.c.youtube.com&type=video/mp4");
outStream = new BufferedOutputStream(new
FileOutputStream("video"));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1)
{
System.out.println("Downloading file");
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
System.out.println("Downloaded Successfully.");
}catch (Exception e) {
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
Servlet Code
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("video/mp4");
String url=request.getParameter("url");
URLConnection con = null;
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
InputStream in=null;
byte[] buffer;
int ByteRead,ByteWritten=0;
try {
URL dUrl=new URL(url);
con=dUrl.openConnection();
in=con.getInputStream();
buffer = new byte[1024];
while ((ByteRead = in.read(buffer)) != -1)
{
System.out.println("Downloading file");
out.write(buffer, 0, ByteRead);
ByteWritten += ByteRead;
}
} finally {
out.close();
in.close();
}
}
url is the same url given as a parameter to this servlet
YouTube download URLs are intended for one-time use only -- they are bound to the IP range that they were initially generated for, and expire after some time. Hard-coding one in your application, as you've done here, will lead to inevitable failure.

Having problems retrieving response from a servlet in J2ME

I am trying to retreive a response from a servlet to a midlet using the code below
public String receiveData() {
HttpConnection connection = null;
String url = "http://localhost:8084/MCastServer/Create";
DataInputStream is = null;
OutputStream os = null;
StringBuffer stringBuffer = new StringBuffer();
String res = null;
try {
connection = (HttpConnection) Connector.open(url);
connection.setRequestMethod(HttpConnection.GET);
connection.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Confirguration/CLDC-1.0");
connection.setRequestProperty("Content-Language", "en-CA");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os = connection.openOutputStream();
is = connection.openDataInputStream();
System.out.println(url);
int ch = 0;
while ((ch = is.read()) == -1) {
stringBuffer.append((char) ch);
System.out.println(stringBuffer);
}
res = stringBuffer.toString();
System.out.println(res);
//ByteArrayOutputStream bos = new ByteArrayOutputStream();
} catch (Exception e) {
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (connection != null) {
connection.close();
}
//display.setCurrent(textBox);
} catch (Exception e) {
}
}
return res;
}
But it keeps returning a null output. I have searched and tried various means but it still returns the same.
Below is the Servlet which I wrote
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String groupNames = "SELECT phone_group_name FROM phone_group_name";
InteractToDB dbCall = new InteractToDB("org.postgresql.Driver");
dbCall.connect("jdbc:postgresql://localhost:5432/mcast", "postgres", "mimi");
out.print(dbCall.getNames());
System.out.println(dbCall.getNames() + " call");
try {
} finally {
out.close();
}
}
You have an empty catch block - that's not a good idea. You should print the stack trace at minimum.
I also think it's a terrible idea to put database code in a servlet. I'd write an interface-based POJO, test out the code thoroughly without the servlet, and then call its methods in the servlet. It decomposes the problem into smaller ones and helps your unit testing efforts.
Why are you creating a connection per request? Why aren't you using a connection pool to amortize the cost of creating connections?
Why are you hard-wiring your information in plain text in the class? What happens if dbCall is null? What if a SQLException is thrown?
The more I look at this code, the worst it gets. I'd better stop now.

Error handling for URLConnection

I have this method that downloads .csv files from yahoo finance and saves them locally. It is accessed during a loop so it is downloading many files from a list. However sometimes a symbol is entered incorrectly, no longer exists, or the connection times out. How can I amend this method so that connection time outs are retried and incorrect symbols (meaning the url does not work) are just skipped over without ending the program?
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
System.out.println("Error while downloading "+symbol);
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Why not call the method again when an exception is thrown. You can narrow down the exception type to indicate when a retry should be initiated.
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
getFile(symbol);
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}

Categories

Resources