execute a jsp program on background of a running java program - java

I just want execute my jsp program when a button on my running java program is clicked, it doesn't need to be visible, the jsp program i am saying is for printing and once it is loaded in the browser it will just pop up the print dialog confirm box, so again it doesn't need to be visible, once the button in my java program is clicked the print dialog will just pop up and that's it. By the way i am new here in this site, and also know only basics of java, so i do not have any idea how to do it, but i like to do it that way and with just a link of the jsp page from the localhost, something like that,
Thanks in advance buddies! Hope you will help me!...

this should be working , cant be sure if it serves properly , please assure me the outcome
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class callURL {
public static void main(String[] args)
{
String url = "http://localhost:8080/OpenID/asd.html";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
StringBuilder builder= new StringBuilder();
try
{
response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
char[] buf = new char[8000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = in.read(buf);
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
for this java program to ececute your jsp
you have to add this line in your jsp page
<script>
window.location.href="http://localhost:8080/OpenID/asd.html"
</script>
where OpenId : Application Name
asd.html is your jsp page , the same jsp which you are calling from java program

Related

Is possible to call servlet from applet

I am not familiar with java and applets, so any one please let me know the possibilities for the following my questing.
I would like to call the Servlet from applet.. is this possible?
If the 1st one is possible can we store the Servlet output like XML data or string in the applet variable?
If the 2nd one is possible, then can get that that variable value using JavaScript or J Query?
If possible please give me the simple example.
Thanks in advance.
Yes you can. The servlet exposes a URL, which you can get with the help of the URLConnection class.
Again you can do this, see here on how you can use the URL connection.
You can do that too, create an applet to get the applet field, and look here on how you can invoke the method.
But all these sound awfully complicated. Why don't you tell us what you are trying to achieve, maybe there is a simpler way to do things.
One : yes you can call the servlet from applet making http calls
step 1 : make a http call to your servlet
step 2 : make your servlet return XML response
step 3 : parse xml response
using this program you can make a call to your servlet
package com.hussain;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class callServlet {
public static void main(String[] args)
{
String servletResponse = callServlet.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb");
callServlet.parseFromXMLResponse(servletResponse);
}
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void parseFromXMLResponse(String respo)
{
// parse your XML response here
}
}
Moving in the flow of your question,
You may call the servlet from your applet:
Construct the url that will hit your servlet.
Use java.net.URLConnection object to hold the connection from your appletURLConnection con = urlToServlet.openConnection()
'con.setDoOutput(true)' => Application intends to write data to the URL connection.
Use the input and output streams to communicate with the Servlet.
con.getInputStream() and con.getOutputStream()
[Note: Don't forget to close all the connections and streams]
Now, use the data you obtained from the InputStream, in what so ever form you want.
Its extreamly simple, use this code:
In Applet:
public String getYourString(){ return responseFromServlet;}
In Javascript:
var jsResp = document.name_of_your_applet.getYourString();
Hope, you've got your answers!

sending parameters across applications

Is there a way I can send attributes across applications that may or may not be on the same machine ?
For example :
// IN APPLICATION 1 (APP-1)
request.setAttribute("Truth","Ghazal is the food for the soul of separation");
RequestDispatcher rd = request.getRequestDispatcher("http://IP/App-2/servlet");
rd.forward(request,response);
// IN APPLICATION 2'S (APP-2) SERVLET
String truth = request.getAttribute("Truth").toString();
// NOW USE THIS STRING
Let us suppose that IP on which app-1 is deployed is not the same as the IP on which the app-2 is deployed.
Is there any way I can send parameters like these across applications that are hosted far away from each other ? When I tried I couldn't do this way,but may be there is a way around.
Both the applications use Tomcat.
If you are going to be sharing state between a variable number of machines, then using HTTP as the method to store that state is not very reliable.
"Attributes" are not transmitted over HTTP, they are merely shared state that reside on the application for the given session. Attributes are 100% purely server-side information.
From the Javadocs:
"It is warned that when the request is dispatched from the servlet
resides in a different web application by RequestDispatcher, the
object set by this method may not be correctly retrieved in the caller
servlet."
you can create a base package to be used through the application
package base;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetXMLTask
{
static double longitute;
static double latitude;
public ArrayList<JSONObject> getOutputFromUrl1(String url)
{
ArrayList<JSONObject> output = new ArrayList<JSONObject>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
StringBuilder builder= new StringBuilder();
JSONObject myjson ;
JSONArray the_json_array;
try
{
response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
char[] buf = new char[8000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = in.read(buf);
}
myjson = new JSONObject("{child:"+builder.toString()+"}");
JSONObject mmm = new JSONObject(builder.toString());
JSONArray mmmArr = mmm.getJSONArray("status");
the_json_array = myjson.getJSONArray("child");
for (int i = 0; i < the_json_array.length(); i++)
{
JSONObject another_json_object = the_json_array.getJSONObject(i);
output.add(another_json_object);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return output;
}
}
now from your application call this method by
ArrayList<JSONObject> obj = new GetXMLTask().getOutputFromUrl1("url for the other application method which responds");

Android Simple HTTP Request?

I have this code for an Android application I'm trying to create into interact with my PHP website. I have the android.permission.INTERNET permission activated and it keeps creating a toast that says "ERROR." instead of the contents of the website. Here is my only java file:
package com.http.request;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class HttprequestActivity extends Activity {
/** Called when the activity is first created. */
private String doHTTPRequest(String url){
String results = "ERROR";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
results = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return results;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String results = doHTTPRequest("http://www.yahoo.com");
Toast.makeText(getApplicationContext(), results, Toast.LENGTH_LONG).show();
}
}
I would check to make sure that,
If there is an exception being thrown, investigate what is causing the IOException
Your server could potentially be returning a non-200 response code.
Put in some breakpoints and see whats happening there. My bet is on the response code.
That is your own "ERROR" string which the Toast() displays. Better change
catch(IOException e){
e.printStackTrace();
}
to
catch(IOException e){
result = "ERROR IOException";
e.printStackTrace();
}
The exception is thrown as you try to connect in the main thread which is not permitted. Put doHTTPRequest() in a thread or AsyncTask.
What is your stacktrace says, LogCat? What is the error? Add more info, make it more clear to understand than "guessing of coffee beans"
My guess is: this happens because you are trying to do network operation in UI thread which is not allowed in 3.0+ versions.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Automate HTML form submission using Java to find grocery hours

I'm trying to automate form submission using Java to get the hours of a grocery store here:
www.giantfood.com
I've posted the query and the hidden miles and storeType fields of the form, but my output.html is just the original web header and footer with an error message in the body. What am I doing wrong?
import java.io.*;
import java.net.*;
public class PostHTML
{
public static void main(String[] args)
{
try
{
URL url = new URL( "http://www.giantfood.com/our_stores/locator/store_search.htm" );
HttpURLConnection hConnection = (HttpURLConnection)
url.openConnection();
HttpURLConnection.setFollowRedirects( true );
hConnection.setDoOutput( true );
hConnection.setRequestMethod("POST");
PrintStream ps = new PrintStream( hConnection.getOutputStream() );
ps.print("groceryStoreAddress=20814&groceryStoreMiles=10&storeType=GROCERY");
ps.close();
hConnection.connect();
if( HttpURLConnection.HTTP_OK == hConnection.getResponseCode() )
{
InputStream is = hConnection.getInputStream();
OutputStream os = new FileOutputStream("output.html");
int data;
while((data=is.read()) != -1)
{
os.write(data);
}
is.close();
os.close();
hConnection.disconnect();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
UPDATE
Thanks! Using &'s worked. I'm trying to use HttpClient but I'm getting another error now:
package clientwithresponsehandler;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
/**
* This example demonstrates the use of the {#link ResponseHandler} to simplify
* the process of processing the HTTP response and releasing associated resources.
*/
public class ClientWithResponseHandler {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpost = new HttpPost("http://www.giantfood.com/our_stores/locator/store_search.htm");
System.out.println("executing request " + httpost.getURI());
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("groceryStoreAddress", "20878"));
nvps.add(new BasicNameValuePair("groceryStoreMiles", "10"));
nvps.add(new BasicNameValuePair("storeType", "GROCERY"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpost, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
System.out.println("----------------------------------------");
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}
Output:
run:
executing request http://www.giantfood.com/our_stores/locator/store_search.htm
Exception in thread "main" org.apache.http.client.HttpResponseException: Moved Temporarily
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:67)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:55)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:945)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:919)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:910)
at clientwithresponsehandler.ClientWithResponseHandler.main(ClientWithResponseHandler.java:39)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)
I don't understand the Moved Temporarily error.
try to use
ps.print("groceryStoreAddress=20814&groceryStoreMiles=10&storeType=GROCERY")
instead
BTW, it's easier to use some http-library, like Apache HttpClient
Solved the Moved Temporarily by learning about HTML Redirects:
Httpclient 4, error 302. How to redirect?

Rails action not responding to Java POST

Really simple, or so I thought.
Java Code
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class UrlConnectionTest {
private static final String TEST_URL = "http://localhost:3000/test/hitme";
public static void main(String[] args) throws IOException {
URLConnection urlCon = null;
URL url = null;
OutputStreamWriter osw = null;
try {
url = new URL(TEST_URL);
urlCon = url.openConnection();
urlCon.setDoOutput(true);
urlCon.setRequestProperty("Content-Type", "text/plain");
osw = new OutputStreamWriter(urlCon.getOutputStream());
osw.write("HELLO WORLD");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (osw != null) {
osw.close();
}
}
}
}
TestController#hitme
def hitme
puts "SOMEONE IS HITTING ME!" * 100
puts request.env.inspect
end
When I run the Java code, I see nothing in my Rails Server Console. However, when I hit the URL in my browser, I get output as specified in TestController#hitme. I thought it would be simple, but haven't had any luck. Any ideas?
Thanks in advance!
You're probably getting an exception, which you aren't seeing, because you're swallowing it. At least print the exception in the catch block.
Even if this isn't the problem, your going to chase your tail a lot if you make a habit of swallowing errors.
I don't think you're actually sending any data until you call
urlCon.getInputStream();
Is it that your URL in your java code shows the controller name of "test" (test/hitme) but you mention that your controller name is TestController? i.e., the URL in your java code should be changed.
private static final String TEST_URL = "http://localhost:3000/TestController/hitme";
Don't fiddle around with URLConnection yourself, let Resty handle it.
Here's the code you would need to write (I assume you are getting text back):
import static us.monoid.web.Resty.*;
import us.monoid.web.Resty;
...
new Resty().text(TEST_URL, content("HELLO WORLD")).toString();

Categories