Calling java object/class from java servlet - servlets

I have created a dynamic web project in eclipse.
It contains a Servlet ResidentApi.java and two java classes:GeoLocationDemo.java and Geolocation.java. I am calling GeoLocationDemo.java from my servlet and getting result in a ResultSet.But i am not getting any value in ResultSet.
When i ran same GeoLocationDemo.java separatly i am getting right results.I don't know servlet is able to call my java class or not but if it is then why i am not getting results.
I am having hard time debugging it.What i am doing is running .war file of this project every time on tomcat server and checking results there.Please suggest a good method to test it on eclipse.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ResultSet rs = null;
try{
GeoLocationDemo geo = new GeoLocationDemo(); //Here i created a new object
rs = geo.getResults(); //here i called a method of GeoLocation
}catch(Exception e){
// System.out.println(e);
out.write("<head><b You suck</b></head>");
}
out.write("<head><b>Congratulation! connected</b></head>"); //i am getting this output
try{
while(rs.next()){
String s = rs.getString("Details");
out.write("<head><b> "+s+ " </b></head>"); //not able to get this output
}
}catch(Exception e){
// System.out.println(e);
out.write("<head><b>You Built </b></head>");
}
out.close();
}

Don't put everything in a <head> tag! Open a body somewhere. Don't silently swallow any Exception you might be getting. Do remember to close() the ResultSet. Also, you should probably be returning all of your data in a List with a POJO.
out.write("<body>");
out.write("<b>Congratulation! connected</b><br/>");
try {
while (rs.next()) {
String s = rs.getString("Details");
out.write("<b> "+s+ "</b><br/>");
}
} catch (Exception e){
// System.out.println(e);
out.write("<b>" + e.getMessage() + "</b>");
e.printStackTrace(out);
} finally {
try {
out.close();
} catch (Exception ignored) {
}
try {
rs.close();
} catch (Exception ignored) {
}
}

configure remote debugging between your IDE and Tomcat server e.g. take a look on Remote debugging Tomcat with Eclipse
localize the problem - is the problem in GeoLocationDemo or in ResultSet or in output processing
p.s. do not close resources you never open - out.close(); - it is managed by servlet container

Related

Webscraping Firebase Page with HTMLUnit

I use htmlunit 2.36.0 and try to scrape:
https://delightful.dussmann.com/menu/B%C3%BCropark%20Bredeney/B%C3%BCropark%20Bredeney
Somehow no dynamic content fetch is executed via javascript.
Anyone any ideas how to fix it?
#Test
public void testPDFFetch() throws IOException {
String url = "https://delightful.dussmann.com/menu/B%C3%BCropark%20Bredeney/B%C3%BCropark%20Bredeney";
WebClient client = new WebClient(BrowserVersion.CHROME);
client.getOptions().setJavaScriptEnabled(true);
client.getOptions().setThrowExceptionOnScriptError(true);
client.getOptions().setCssEnabled(true);
client.getOptions().setUseInsecureSSL(true);
client.setAjaxController(new AjaxController() {
#Override
public boolean processSynchron(HtmlPage page, WebRequest request, boolean async) {
return true;
}
});
try {
HtmlPage page = client.getPage(url);
// page.wait(20000);
client.waitForBackgroundJavaScript(10000);
client.waitForBackgroundJavaScriptStartingBefore(10000);
Thread.sleep(10000);
System.out.println(page.asXml());
} catch (Exception e) {
e.printStackTrace();
} finally {
client.close();
}
}
Looks like this page uses javascript modules - this is currently not supported by HtmlUnit (Rhino)

Download file with redirection

I am trying to make the user able to download a file
<h:commandLink value="yes" actionListener="#{Bean.readFileFromServer}"/>
the method redFileFromServer is a method that returns void, it does some logic then it calls anthoer method to return the file to the response
public void exportList() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
try {
userLogger.info("Exposting report ");
ec.setResponseContentType("application/octet-stream"); // Check
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + result.getFileName() + "\"");
OutputStream output = ec.getResponseOutputStream();
int octet;
while ((octet = input.read()) != -1) {
output.write(octet);
}
input.close();
output.close();
fc.responseComplete();
} catch (Exception e) {
e.printStackTrace();
}
}
the file downloaded is compressed zip file, I have 2 problems, first sometimes this works and sometimes not, and I don't know why the behavior is not consistence.Second problem if there is any exception the page is redirected, which is unacceptable duo to my structure design, I need this to work every time and in case of any problem the page won't redirect.

Error for GetStringAsync if triggered by ScheduledAgent but no error during WP8 App usage

I have a wrapper for the webclient that I am using to retrieve some data. This same function is being used by the WP8 App and also used by the WP8 ScheduledAgent.
Somehow, when the function is used by the WP8 App, there is no error and it returns correctly.
However, when the ScheduledAgent uses the function, it erred out at the bold code below. I tried a try catch but it is not catching. Via Debugger, the GetSTringAsync(uri) had completed without any exception. The error seemed to be only happening when it is assigning the return Task to the result string.
The error I received is:
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
public class HttpClient : WebClient
..
private async Task GetStringAsync(string strUri)
{
Uri uri = new Uri(strUri);
string result = string.Empty;
try
{
result = await GetStringAsync(uri);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
...
private Task GetStringAsync(Uri requestUri)
{
TaskCompletionSource tcs = new TaskCompletionSource();
try
{
this.DownloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
tcs.TrySetResult(e.Result);
}
else
{
tcs.TrySetException(e.Error);
}
};
this.DownloadStringAsync(requestUri);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
if (tcs.Task.Exception != null)
{
throw tcs.Task.Exception;
}
return tcs.Task;
}
Please advise if I am missing something.
My problem is because I am using pushpin as one of my object types within my Model. Apparently, in the scheduled agent, it is not able to access that object type and thus threw the above error.

How to call HTTP URL using wifi in J2ME code for BlackBerry 5.0 and above?

I am calling a web service from BlackBerry using J2ME code. When I try to open a connection using HttpConnection, it is checking only the GPRS connection. Now, I want to check the Wi-Fi connection and call a webservice through Wi-Fi.
The following code is my connection section. How to change the code for a Wi-Fi connection?
public boolean HttpUrl()
{
HttpConnection conn = null;
OutputStream out = null;
String url = "http://www.google.com";
try
{
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
if (conn != null)
{
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0");
}
}
catch (Exception e)
{
return false;
}
finally
{
try
{
out.close();
}
catch (Exception e2)
{
}
}
//Only if exception occurs, we close the connection.
//Otherwise the caller should close the connection himself.
try
{
conn.close();
}
catch (Exception e1)
{
}
return true;
}
Check this way:
HttpConnection conn = null;
String URL = "http://www.myServer.com/myContent;deviceside=true;interface=wifi";
conn = (HttpConnection)Connector.open(URL);
source
Making Connections
Rafael's answer will certainly work if you know you'll only be using Wi-Fi.
However, if you only need to support BlackBerry OS 5.0 - 7.1, I would recommend that you do use the ConnectionFactory. Normally, you will not limit your code to only using one transport. You'll normally support (almost) any transport the device has, but you may want to code your app to choose certain transports first.
For example,
class ConnectionThread extends Thread
{
public void run()
{
ConnectionFactory connFact = new ConnectionFactory();
connFact.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_BIS_B,
TransportInfo.TRANSPORT_MDS,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.google.com");
if (connDesc != null)
{
HttpConnection httpConn;
httpConn = (HttpConnection)connDesc.getConnection();
try
{
// TODO: set httpConn request method and properties here!
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " +
Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: "
+ e.getMessage());
}
}
}
}
will choose the Wi-Fi transport if Wi-Fi is available, but use the GPRS connection if it isn't. I think this is generally considered best practice for the 5.0+ devices.
Request Properties
This code
conn.setRequestProperty("Content-Length", "application/x-www-form-urlencoded");
is not right. Content-Length should be the size, in bytes, of your HTTP POST parameters. See an example here.
Threading
Remember that making network connections is slow. Do not block the user interface by running this code on the main/UI thread. Put your code into a background thread to keep the UI responsive while you request remote content.

Get XML by Post method from Webservice in Flex

I created a servlet in java that will give me a xml response when called
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/xml; charset=utf-8"); // Set the servlet's response type to XML.
PrintWriter out = null;
try {
out = response.getWriter();
XMLOutputFactory of = XMLOutputFactory.newInstance();
XMLStreamWriter writer = of.createXMLStreamWriter(out);
writer.writeStartDocument();
writer.writeStartElement("Test");
for(int i = 1; i <= 100; i++) {
writer.writeStartElement("TheNumber");
writer.writeAttribute("number", "" + i);
writer.writeAttribute("value", "" + Math.pow(2, i));
writer.writeEndElement();
}
writer.writeEndElement();
writer.close();
out.close();
} catch (Exception ex) {
}
}
Now I want to get this xml in flex, can someone give me a hint? I tried mx:WebService and mx:HttpService but both of them did not work.
Thanks in advance
Sebastian
Since you've already solved your issue with HttpService, now it's time to graduate to using Flex remoting with their Granite Data Services or BlazeDS, unless you have some major reason you can't. Parsing XML and using XML for data transmission is a no-no, terrible performance, and in general a bad idea if you can avoid it.
http://www.graniteds.org/
http://opensource.adobe.com/wiki/display/blazeds/BlazeDS/
Just a straight URLLoader will work for you as well.

Resources