Retrieving images using Jquery and servlet produces HTTP Status 500 error - java

I need to retrieve images from my database. For this I used jquery and servlet to retrieve all images stored in a table. But when i run the code it produces HTTP Status 500 - class oracle.jdbc.driver.OracleBlobInputStream declares multiple JSON fields named maxPosition I'm a newbie in Jquery I don't know how to use JSON for images.
My Servlet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname;// = request.getParameter("countryCode");
uname="shyam";
PrintWriter out = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
response.setHeader("Access-Control-Max-Age", "86400");
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
ArrayList<ImageFileInfo> imageInfo = getInfo(uname);
ImageFileInfo info = new ImageFileInfo();
JsonElement imageObj = gson.toJsonTree(imageInfo);
boolean nonNullElemExist= false;
for (ImageFileInfo s: imageInfo) {
if (s != null) {
nonNullElemExist = true;
break;
}
}
if(nonNullElemExist==true){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("imageInfo", imageObj);
out.println(myObj.toString());
out.close();
}
private ArrayList<ImageFileInfo> getInfo(String uname) {
ArrayList<ImageFileInfo> imageFileList = new ArrayList<ImageFileInfo>();
Connection conn = null;
PreparedStatement stmt = null;
try {
conn=prepareConnection();
StringBuilder sb=new StringBuilder(1024);
sb.append("select * from ").append(uname.trim()).append("image");
String sql=sb.toString();
stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
ImageFileInfo info = new ImageFileInfo();
info.setName(rs.getString("imagename").trim());
info.setDisc(rs.getString("imagedisc").trim());
info.setImageid(rs.getInt("imageid"));
info.setalbumid(rs.getInt("albumid"));
byte imageData[] = rs.getBytes("imagethumb");
String encoded = DatatypeConverter.printBase64Binary(imageData);
info.setThumb(encoded);
byte image1Data[] = rs.getBytes("imagethumb");
String encoded1 = DatatypeConverter.printBase64Binary(image1Data);
info.setFull(encoded1);
}
rs.close();
stmt.close();
stmt = null;
conn.close();
conn = null;
}
catch(Exception e){ System.out.println( "Error --> " + displayErrorForWeb(e));;}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sqlex) {
// ignore -- as we can't do anything about it here
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException sqlex) {
// ignore -- as we can't do anything about it here
}
conn = null;
}
}
return imageFileList;
}
And The ImageFileInfo.java file is:
package skypark;
import java.io.InputStream;
public class ImageFileInfo
{
String name = null;
String disc = null;
int imageid=0;
int albumid=0;
InputStream thumbarray;
InputStream fullarray;
public void setName(String name)
{
this.name = name;
}
public String getName() {
return name;
}
public void setDisc(String disc)
{
this.disc = disc;
}
public void setImageid(int Imageid)
{
this.imageid = Imageid;
}
public void setalbumid(int albumid)
{
this.albumid = albumid;
}
public void setThumb(InputStream inputStream)
{
this.thumbarray = inputStream;
}
public void setFull(InputStream binaryStream) {
this.fullarray = binaryStream;
}
}
And Stack trace is:
java.lang.IllegalArgumentException: class oracle.jdbc.driver.OracleBlobInputStream declares multiple JSON fields named maxPosition
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:122)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
com.google.gson.Gson.getAdapter(Gson.java:353)
com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:55)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:89)
com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:195)
com.google.gson.Gson.toJson(Gson.java:586)
com.google.gson.Gson.toJsonTree(Gson.java:479)
com.google.gson.Gson.toJsonTree(Gson.java:458)
skypark.RetriveIm.doGet(RetriveIm.java:66)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I don't know what this error tells. Please anyone help me to solve this...... thanks.....

You included two InputStream variables in your class, which are getting set to instances of OracleBlobInputStream, which your GSON provider cannot serialize. You probably want to store the image content as bytes instead (or as a (URL encoded) string).
public class ImageFileInfo implements Serializable {
// Other class variables
private byte[] thumbarray;
private byte[] fullarray;
// Constructors, Getters/Setters
}
ImageFile.setThumb(rs.getBytes("imagethumb"));
ImageFile.setFull(rs.getBytes("imagefull"));
On a side tangent, it looks like you are trying to return JSON content, but you have incorrectly specified your Content-Type as text/html, instead of application/json.

Related

How to maintain session between Android and Servlet? [duplicate]

This question already has answers here:
How to use java.net.URLConnection to fire and handle HTTP requests
(12 answers)
Making http calls from swing application to a servlet, session not saved
(1 answer)
Closed 1 year ago.
Server-side I have an HttpSession object. Each time the client starts the connection to the Servlet, the session changes.
Here I have a simplified version of my Servlet code:
//import ...
#WebServlet(name = "ServletController", urlPatterns = {"/ServletController"})
public class ServletController extends HttpServlet {
public void init(ServletConfig conf) {
//...
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//...
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
HttpSession s = request.getSession();
PrintWriter out = response.getWriter();
try {
String action = request.getParameter("action");
switch (action) {
case "login":
s.setAttribute("account", "John");
out.println("Logged in successfully. Session: " + s);
out.flush();
break;
case "account":
String account = (String) s.getAttribute("account");
out.println(account + ". Session: " + s);
out.flush();
break;
default:
break;
}
} catch (Exception x) {
System.out.println(x);
}
}
}
And here the simplified Android one:
//import ...
public class Operation {
public static Executor e = Executors.newSingleThreadExecutor();
public static void main(String[] args) {
Button login_btn = findViewById(R.id.login);
Button account_btn = findViewById(R.id.account);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String login = Operation.operation("?action=login");
});
}
});
account_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
e.execute(() -> {
String account = Operation.operation("?action=account");
});
}
});
System.out.println(login);
System.out.println(account);
}
public static String operation(String urlParameters) {
HttpURLConnection conn = null;
try {
System.out.println(urlParameters);
URL url = new URL("http://10.0.2.2:8080/progettoTweb/ServletController" + urlParameters);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(1000);
conn.setConnectTimeout(1500);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
return readIt(conn.getInputStream());
} catch (Exception ex) {
System.out.println(ex);
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
//building the output as a String
private static String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
}
}
As the System.out.println in the Android app show, I obtain a different session for each Operation.operation call I make.
In the original code I use SharedPreferences in order to save my data, but it does not solve the problem since I do not know how to use the session, gained from the interaction with the server-side, to obtain the required values.
Indeed, in the Servlet code I use s.getAttribute() but, since it creates a new HttpSession object each time, It cannot give back the requested values.

How to use network I/O with Android [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 6 years ago.
The purpose of the class below is to get text from different articles of different news websites. The version below is designed for Android, but it throws a NetworkOnMainThread Exception when run. When I used an earlier version of this class, made specifically to run on a computer, it worked fine, but I'm not really sure how network I/O works on Android. I've seen some other answers to questions about this topic, but I don't understand why in Android the program throws an exception but on a desktop it works fine. Can anyone explain?
package com.example.user.helloworld;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class ArticleReceiver {
private ArrayList<Article> newsArticles = new ArrayList<>();
private ArrayList<String> newsLinks = new ArrayList<>();
public ArticleReceiver(int numArticles, String link) {
if (numArticles != 0) {
receiveNewsArticles(numArticles, link);
}else{
System.out.println("ERROR: numArticles request for " + link + " cannot equal 0.");
}
}
private void receiveNewsArticles(int numArticles, String urlAddress) {
URL rssUrl = null;
// if connected to Internet
if (true){//isInternetAvailable()) {
try {
// gather links
rssUrl = new URL(urlAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
// fix bbc trash urls
if (urlAddress.equals(Main.BBC_URL)) {
numArticles++;
}
while ((line = in.readLine()) != null && newsLinks.size() <= numArticles) {
if (line.contains("<link>")) {
// find links through tags
int firstPos = line.indexOf("<link>");
String temp = line.substring(firstPos);
temp = temp.replace("<link>", "");
int lastPos = temp.indexOf("</link>");
temp = temp.substring(0, lastPos);
newsLinks.add(temp);
}
}
in.close();
// test if there are links and if there is remove first
// unnecessary
// link
if (!newsLinks.isEmpty()) {
if (urlAddress.equals(Main.BBC_URL)) {
newsLinks.remove(0);
newsLinks.remove(0);
}else if(urlAddress.equals(Main.CNN_URL) || urlAddress.equals(Main.FOX_URL) || urlAddress.equals(Main.ESPN_URL)){
newsLinks.remove(0);
}
} else {
System.out.println("ERROR: No Found Articles. Check If You Have Wifi.");
}
// gather articles from HTML "section" or "p" tag of article using Jsoup
for (String newsLink : newsLinks) {
// get webpage
Document doc = Jsoup.connect(newsLink).get();
// get article from different websites
String article = null;
if (urlAddress.equals(Main.FOX_URL)) {
Elements element = doc.select("p");
article = element.text();
} else if (urlAddress.equals(Main.CNN_URL)) {
Elements element = doc.select("section");
article = element.text();
} else if (urlAddress.equals(Main.BBC_URL)) {
Elements element = doc.select("p");
article = element.text();
}else if(urlAddress.equals(Main.ESPN_URL)){
Elements element = doc.select("p");
article = element.text();
}
newsArticles.add(new Article(article, Main.SUMMARY_SENTENCES));
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("ERROR: No internet connection established.");
return;
}
}
public ArrayList<Article> getArticles() {
return newsArticles;
}
public Article getArticle(int i) {
if (newsArticles.size() <= i) {
return null;
} else {
return newsArticles.get(i);
}
}
//The method below does not recognize the "getSystemService" method, and when the method is no longer present there is a NetworkOnMainThreadException
private boolean isInternetAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
You need to execute web service connections asynchronous.
What I use in my projects is have a class ApiConnection and with interface get response. Example:
Apiconnection class
public class APIConnection extends AsyncTask<Object, String, Void> {
private final String TAG = "API-CONNECTION";
private StringBuilder sbuilder;
private JSONObject json;
private APIConnectionInterface mInterface;
protected int httpResponseCode = 0;
private String entity = null, url;
private APIConnectionType mmode;
private boolean DEBUG = BuildConfig.DEBUG;
private String[][] headers;
/**
Constructor For APIConnection
*/
public APIConnection(APIConnectionInterface thisdelegate, APIConnectionType mode, String murl, String entity) {
this.mInterface = thisdelegate;
this.mmode = mode;
this.url = murl;
this.entity = entity;
initHeaders();
}
private void initHeaders(){
headers = new String[][]{
{"token", "MY_TOKEN"},
{"Content-Type", "application/json;charset=utf-8"},
{"user-agent", "android"},
{"Accept-Language", "es"}
};
}
#Override
protected Void doInBackground(Object... params) {
BufferedReader buffer = null;
InputStreamReader in = null;
OutputStream os = null;
int timeoutConnection = 30000, timeoutSocket = 20000;
try{
sbuilder = new StringBuilder();
url = convertURL(url);
if (entity==null)entity="{}";
URL u = new URL(url);
HttpURLConnection conn;
if (url.startsWith("https://"))
conn = (HttpsURLConnection) u.openConnection();
else
conn = (HttpURLConnection) u.openConnection();
conn.setReadTimeout(timeoutConnection);
conn.setConnectTimeout(timeoutSocket);
for (String[] arr : headers){ conn.addRequestProperty(arr[0], arr[1]); }
/*GET*/if (mmode == APIConnectionType.GET) {
conn.setDoInput(true);
conn.setRequestMethod(mmode.toString());
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(),"UTF-8");
/*OTHER*/} else if (mmode == APIConnectionType.POST || mmode == APIConnectionType.PUT ||
mmode == APIConnectionType.PATCH || mmode == APIConnectionType.DELETE) {
conn.setRequestMethod(mmode.toString());
conn.setDoOutput(true);
byte[] outputInBytes = entity.getBytes("UTF-8");
os = conn.getOutputStream();
os.write( outputInBytes );
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(), "UTF-8");
}
if (in!=null){
buffer=new BufferedReader(in);
String line;
while ((line = buffer.readLine()) != null) {
sbuilder.append(line);
}
}else {
sbuilder.append("");
}
}
catch(IOException e) {
if (DEBUG)Log.d(TAG, "onBackground Exception " + e.getMessage());
sbuilder= new StringBuilder();
httpResponseCode = 0;
cancel(true);
return null;
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (os!=null){
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result){
try{
if (DEBUG) timelapse_e = System.currentTimeMillis();
if (sbuilder != null) {
json = new JSONObject(sbuilder.toString());
}
if (sbuilder != null){
sbuilder.setLength(0);
sbuilder.trimToSize();
}
sbuilder = null;
GoRunning();
hideDialog();
}
catch(RuntimeException e) {
if (DEBUG)Log.d(TAG, "PostExecute RuntimeException " + e.getMessage());
cancel(true);
}
catch(Exception e) {
if (DEBUG)Log.d(TAG, "PostExecute Exception " + e.getMessage());
cancel(true);
}
}
#Override protected void onCancelled() {
if (mInterface != null) mInterface.onCancelled(APIConnection.this);
super.onCancelled();
}
#Override protected void onPreExecute() {
super.onPreExecute();
if (DEBUG) timelapse_s = System.currentTimeMillis();
if (mInterface != null) mInterface.onStartLoading(APIConnection.this);
}
public void GoRunning(){
if (mInterface != null) try {
mInterface.onDataArrival(APIConnection.this, json, httpResponseCode);
} catch (JSONException e) {
onCancelled();
e.printStackTrace();
}
}
/**
* Hide Dialog (Progress dialog) if is showing and activity NOT Finishing
*/
private void hideDialog() {
if (mInterface != null) mInterface.onFinishedLoading(APIConnection.this);
}
/** <b>convertURL(String str);</b><br/>
* replaces any special characters to <b>%??</b><br/>
* Replacements actived:<br/>
* "{Space}" ==> "%20"
* #param str URL to encode
* #return url encoded
*/
public static String convertURL(String str) {
return str.trim().replace(" ", "%20");
// .replace("&", "%26")
// .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
// .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
// .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
// .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
// .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
// .replace(";", "%3B").replace("?", "%3F").replace("#", "%40")
// .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
// .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
// .replace("|", "%7C").replace("}", "%7D"));
}
public interface APIConnectionInterface {
void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) throws JSONException;
void onStartLoading(APIConnection apiConnection);
void onFinishedLoading(APIConnection apiConnection);
void onCancelled(APIConnection apiConnection);
}
public enum APIConnectionType {
GET("GET"),
POST("POST"),
PUT("PUT"),
PATCH("PATCH"),
DELETE("DELETE");
private String methodName;
APIConnectionType(String methodName){this.methodName = methodName;}
#Override public String toString() {return methodName;}
}
}
And then from any Activity or Fragment I can call the web service async
like this:
new APIConnection(new APIConnection.APIConnectionInterface() {
#Override public void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) {
try {
if (isHttpResponseOk(httpResponseCode, json)){//200 or 201
JSONObject obj = json.getJSONObject("results");
// do things with json
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override public void onStartLoading(APIConnection apiConnection) {showProgressDialog();}
#Override public void onFinishedLoading(APIConnection apiConnection) {hideProgressDialog();}
#Override public void onCancelled(APIConnection apiConnection) {hideProgressDialog();}
}, APIConnection.APIConnectionType.GET, MyApp.API_URL + "/master_data/", null).execute();
The only thing you need is to adapt the response to other object you need.
I hope that helps

Unrecognized temporary token when attempting to complete authorization: FITBIT4J

I am trying to create a app for fitbit using fitbit4j . I found their sample code
at
https://github.com/apakulov/fitbit4j/blob/master/fitbit4j-example-client/src/main/java/com/fitbit/web/FitbitApiAuthExampleServlet.java
When i tried to implement it I am getting many errors.
below is their doGet function()
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
FitbitAPIClientService<FitbitApiClientAgent> apiClientService = new FitbitAPIClientService<FitbitApiClientAgent>(
new FitbitApiClientAgent(apiBaseUrl, fitbitSiteBaseUrl, credentialsCache),
clientConsumerKey,
clientSecret,
credentialsCache,
entityCache,
subscriptionStore
);
if (request.getParameter("completeAuthorization") != null) {
String tempTokenReceived = request.getParameter(OAUTH_TOKEN);
String tempTokenVerifier = request.getParameter(OAUTH_VERIFIER);
APIResourceCredentials resourceCredentials = apiClientService.getResourceCredentialsByTempToken(tempTokenReceived);
if (resourceCredentials == null) {
throw new ServletException("Unrecognized temporary token when attempting to complete authorization: " + tempTokenReceived);
}
// Get token credentials only if necessary:
if (!resourceCredentials.isAuthorized()) {
// The verifier is required in the request to get token credentials:
resourceCredentials.setTempTokenVerifier(tempTokenVerifier);
try {
// Get token credentials for user:
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
} catch (FitbitAPIException e) {
throw new ServletException("Unable to finish authorization with Fitbit.", e);
}
}
try {
UserInfo userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
request.setAttribute("userInfo", userInfo);
request.getRequestDispatcher("/fitbitApiAuthExample.jsp").forward(request, response);
} catch (FitbitAPIException e) {
throw new ServletException("Exception during getting user info", e);
}
} else {
try {
response.sendRedirect(apiClientService.getResourceOwnerAuthorizationURL(new LocalUserDetail("-"), exampleBaseUrl + "/fitbitApiAuthExample?completeAuthorization="));
} catch (FitbitAPIException e) {
throw new ServletException("Exception during performing authorization", e);
}
}
}
When i run the code it goes into the 'else' part first and i get the URL with
localhost:8080/fitbitApiAuthExample?completeAuthorization=&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX, and i get the fitbit login screen and when i log in
and since the
'completeAuthorization==null',
it is executing the else part again.So i manually added a value so that it will enter the 'if' section .
So the new URL became
localhost:8080/fitbitApiAuthExample?completeAuthorization=Success&oauth_token=5bccadXXXXXXXXXXXXXXXXXXXXXXXXXX&oauth_verifier=h35kXXXXXXXXXXXXXXXXX and entered the 'if' section.
Now am getting the exception
'Unrecognized temporary token when attempting to complete authorization:'I tried many workarounds but still cant understand the error.
Please Help.
Solved the problem. the 'apiClientService' was going null when i reload the servlet. Made it member variable and everything started working.
public class NewServlet extends HttpServlet {
public String apiBaseUrl = "api.fitbit.com";
public String webBaseUrl = "https://www.fitbit.com";
public String consumerKey = "your key";
public String consumerSecret = "your secret";
public String callbackUrl = "*****/run?Controller=Verifier";
public FitbitAPIClientService<FitbitApiClientAgent> apiClientService = null;
public String oauth_token = null;
public String oauth_verifier = null;
public String token = null;
public String tokenSecret = null;
public String userId = null;
public APIResourceCredentials resourceCredentials=null;
public FitbitApiClientAgent agent =null;
public LocalUserDetail user=null;
public Gson gson =null;
public UserInfo userInfo=null;
private static Properties getParameters(String url) {
Properties params = new Properties();
String query_string = url.substring(url.indexOf('?') + 1);
String[] pairs = query_string.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
params.setProperty(kv[0], kv[1]);
}
return params;
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParserConfigurationException, SAXException, Exception {
PrintWriter out = response.getWriter();
response.addHeader("Access-Control-Allow-Origin", "*");
// out.println(" ----- process Request Called-----");
String controllerValue = request.getParameter("Controller");
// out.println(" Controller Request : "+param);
if (controllerValue == null) {
// out.println(" inside if part ");
FitbitAPIEntityCache entityCache = new FitbitApiEntityCacheMapImpl();
FitbitApiCredentialsCache credentialsCache = new FitbitApiCredentialsCacheMapImpl();
FitbitApiSubscriptionStorage subscriptionStore = new FitbitApiSubscriptionStorageInMemoryImpl();
FitbitApiClientAgent apiClientAgent = new FitbitApiClientAgent(apiBaseUrl, webBaseUrl, credentialsCache);
out.println("testing2");
apiClientService
= new FitbitAPIClientService<FitbitApiClientAgent>(
apiClientAgent,
consumerKey,
consumerSecret,
credentialsCache,
entityCache,
subscriptionStore
);
// out.println("<script>localStorage.setItem('api',apiClientService);</script>");
LocalUserDetail userDetail = new LocalUserDetail("-");
try {
// out.println("testing4");
String authorizationURL = apiClientService.getResourceOwnerAuthorizationURL(userDetail, callbackUrl);
out.println("access by web browser: " + authorizationURL);
out.println("Your web browser shows redirected URL.");
out.println("Input the redirected URL and push Enter key.");
response.sendRedirect(authorizationURL);
} catch (FitbitAPIException ex) {
out.println("exception : " + ex);
//Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (controllerValue.equalsIgnoreCase("Verifier")) {
oauth_token = request.getParameter("oauth_token");
oauth_verifier = request.getParameter("oauth_verifier");
resourceCredentials = apiClientService.getResourceCredentialsByTempToken(oauth_token);
if (resourceCredentials == null) {
out.println(" resourceCredentials = null ");
throw new Exception("Unrecognized temporary token when attempting to complete authorization: " + oauth_token);
}
if (!resourceCredentials.isAuthorized()) {
resourceCredentials.setTempTokenVerifier(oauth_verifier);
apiClientService.getTokenCredentials(new LocalUserDetail(resourceCredentials.getLocalUserId()));
}
userId = resourceCredentials.getLocalUserId();
token = resourceCredentials.getAccessToken();
tokenSecret = resourceCredentials.getAccessTokenSecret();
user = new LocalUserDetail(userId);
userInfo = apiClientService.getClient().getUserInfo(new LocalUserDetail(resourceCredentials.getLocalUserId()));
user = new LocalUserDetail(userId);
agent = apiClientService.getClient();
response.sendRedirect("http://localhost:8084/FitbitClientCheck/");
}

Serializing over HTTP correct way to convert object

I'm trying to serialize an object and send it over HTTP. I'm using a few tutorials as most deal with sockets but I can't use sockets for this, or with a file been stored locally.
Here is the test class Employee:
public class Employee implements java.io.Serializable {
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck() {
System.out.println("Mailing a check to " + name + " " + address);
}
}
Client Side:
public class SerializeAndSend {
public static void main(String args[]){
one.Employee e = new one.Employee();
e.name = "Reyan Ali";
e.address = "Phokka Kuan, Ambehta Peer";
e.SSN = 11122333;
e.number = 101;
sendObject(e);
}
public static Object sendObject(Object obj) {
URLConnection conn = null;
Object reply = null;
try {
// open URL connection
URL url = new URL("///myURL///");
conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
// send object
ObjectOutputStream objOut = new ObjectOutputStream(conn.getOutputStream());
objOut.writeObject(obj);
objOut.flush();
objOut.close();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
// recieve reply
try {
ObjectInputStream objIn = new ObjectInputStream(conn.getInputStream());
reply = objIn.readObject();
objIn.close();
} catch (Exception ex) {
// it is ok if we get an exception here
// that means that there is no object being returned
System.out.println("No Object Returned");
if (!(ex instanceof EOFException))
ex.printStackTrace();
System.err.println("*");
}
return reply;
}
}
I think thats correct. But I'm stuck on the server end, I have the employee class on the server side too:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Object obj;
ObjectInputStream objIn = new ObjectInputStream(req.getInputStream());
try {
obj = objIn.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Employee e = obj;
}
How do I turn this object back into an employee class object?
Any help appreciated!
Just typecast it.
Employee emp = (Employee)objIn.readObject();

java.lang.NullPointerException Issue

I realize this is an easy issue usually, but I've been looking at other similar questions on this site and others and have not been able to fix the code, nor seeing exactly where the error is coming from. What seems to be my problem is calling an OnClickListener assigned to a button, but then again I could be wrong. I had basically straight copied this code (with minimal changes) from another application where this had worked. This fact baffles me a little bit more. Thanks in advance for your help with this relatively easy question.
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update_activity);
final Handler handler;
handler = new Handler();
final EditText getCustID = (EditText) findViewById(R.id.customer);
final EditText custvar1 = (EditText) findViewById(R.id.var1);
final EditText custvar2 = (EditText) findViewById(R.id.var2);
final EditText custvar3 = (EditText) findViewById(R.id.var3);
class sendGET implements Runnable
{
private String url;
public sendGET(String mUrl)
{
url = mUrl;
}
public void run()
{
try
{
//Declare HttpClient and HttpGet
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
//Run HttpGet
client.execute(httpget);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class getCustomerData implements Runnable
{
public void run()
{
try
{
InputStream stream = null;
XMLparser xmlParser = new XMLparser();
List<Customer> customers = null;
String parseUrl = URL + getCustID.getText().toString();
try
{
stream = downloadUrl(parseUrl);
customers = xmlParser.parse(stream);
}
finally
{
stream.close();
}
final Customer data = customers.get(0);
handler.post(new Runnable() {
public void run() {
custvar1.setText(String.valueOf(data.var1));
custvar2.setText(String.valueOf(data.var2));
custvar3.setText(String.valueOf(data.var3));
}
});
}
catch (IOException e)
{
//return getResources().getString(R.string.connection_error);
}
catch (XmlPullParserException e)
{
//return getResources().getString(R.string.xml_error);
}
}
private Customer readCustomer(XmlPullParser parser) throws XmlPullParserException, IOException
{
parser.require(XmlPullParser.START_TAG, null, "customer");
String custID = null;
String var1 = null;
String var2 = null;
String var3 = null;
while(parser.next() != XmlPullParser.END_TAG)
{
if (parser.getEventType() != XmlPullParser.START_TAG)
{
continue;
}
String name = parser.getName();
if (name.equals("CustID"))
{
custID = readCustID(parser);
} else if (name.equals("custvar1"))
{
var1 = readVar1(parser);
} else if (name.equals("custvar2"))
{
var2 = readVar2(parser);
} else if (name.equals("custvar3"))
{
var3 = readVar3(parser);
} else
{
skip(parser);
}
}
return new Customer(custID, var1, var2, var3);
}
private String readCustID(XmlPullParser parser) throws IOException, XmlPullParserException
{
parser.require(XmlPullParser.START_TAG, null, "CustID");
final String custID = readText(parser);
parser.require(XmlPullParser.END_TAG, null, "CustID");
return custID;
}
private String readVar1(XmlPullParser parser) throws IOException, XmlPullParserException
{
parser.require(XmlPullParser.START_TAG, null, "custvar1");
String var1 = readText(parser);
parser.require(XmlPullParser.END_TAG, null, "custvar1");
return var1;
}
private String readVar2(XmlPullParser parser) throws IOException, XmlPullParserException
{
parser.require(XmlPullParser.START_TAG, null, "custvar2");
String var2 = readText(parser);
parser.require(XmlPullParser.END_TAG, null, "custvar2");
return var2;
}
private String readVar3(XmlPullParser parser) throws IOException, XmlPullParserException
{
parser.require(XmlPullParser.START_TAG, null, "custvar3");
String var3 = readText(parser);
parser.require(XmlPullParser.END_TAG, null, "custvar3");
return var3;
}
private String readText(XmlPullParser parser) throws IOException, XmlPullParserException
{
String result = "";
if (parser.next() == XmlPullParser.TEXT)
{
result = parser.getText();
parser.nextTag();
}
return result;
}
private void skip(XmlPullParser parser) throws IOException, XmlPullParserException
{
if (parser.getEventType() != XmlPullParser.START_TAG)
{
throw new IllegalStateException();
}
int depth = 1;
while (depth != 0)
{
switch (parser.next()) {
case XmlPullParser.END_TAG:
depth --;
case XmlPullParser.START_TAG:
depth++;
break;
}
}
}
class XMLparser
{
public List<Customer> parse(InputStream in) throws XmlPullParserException, IOException {
try
{
XmlPullParser parser = Xml.newPullParser();
parser.setInput(in, null);
parser.nextTag();
return readXML(parser);
} finally {
in.close();
}
}
private List<Customer> readXML(XmlPullParser parser) throws XmlPullParserException, IOException
{
List<Customer> custData = new ArrayList<Customer>();
parser.require(XmlPullParser.START_TAG, null, "xml");
while (parser.next() != XmlPullParser.END_TAG)
{
if (parser.getEventType() != XmlPullParser.START_TAG)
{
continue;
}
String name = parser.getName();
//Look for customer tag
if (name.equals("customer"))
{
custData.add(readCustomer(parser));
}
else
{
skip(parser);
}
}
return custData;
}
}
private InputStream downloadUrl(String urlString) throws IOException
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
//start the query
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
}
final Button getData = (Button) findViewById(R.id.getData);
getData.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
//Declare and start thread
final Runnable mGetData = new getCustomerData();
final Thread getData = new Thread(mGetData);
getData.start();
}
});
final Button submit = (Button) findViewById(R.id.Submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//set url
String url = "**removed**";
url += "var1=" + custvar1.getText().toString() + "&var2=" + custvar2.getText().toString() + "&var3=" + custvar3.getText().toString();
//Declare and start thread
final Runnable mConnect = new sendGET(url);
final Thread Connect = new Thread(mConnect);
Connect.start();
}
});
}
public class Customer
{
public final String custID;
public final String var1;
public final String var2;
public final String var3;
private Customer()
{
custID = null;
var1 = null;
var2 = null;
var3 = null;
}
private Customer(String custID, String var1, String var2, String var3)
{
this.custID = custID;
this.var1 = var1;
this.var2 = var2;
this.var3 = var3;
}
}
Logcat Error:
01-09 19:20:53.478: W/dalvikvm(911): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
01-09 19:20:53.478: E/AndroidRuntime(911): FATAL EXCEPTION: Thread-99
01-09 19:20:53.478: E/AndroidRuntime(911): java.lang.NullPointerException
01-09 19:20:53.478: E/AndroidRuntime(911): at us.rns.editdata.UpdateActivity$1getCustomerData.run(UpdateActivity.java:90)
01-09 19:20:53.478: E/AndroidRuntime(911): at java.lang.Thread.run(Thread.java:856)
01-09 19:20:54.408: W/IInputConnectionWrapper(911): showStatusIcon on inactive InputConnection
Your downloadUrl method is failing.
InputStream stream = null;
XMLparser xmlParser = new XMLparser();
List<Customer> customers = null;
String parseUrl = URL + getCustID.getText().toString();
try
{
stream = downloadUrl(parseUrl);
customers = xmlParser.parse(stream);
}
finally
{
stream.close();
}
The stream object is set to null, then you assign stream = downloadUrl(parseUrl).
The downloadUrl method fails, without having assigned anything to stream.
You then try to close the stream in the finally clause.
private InputStream downloadUrl(String urlString) throws IOException
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
//start the query
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
Put a breakpoint on this method, and debug through it. Please return with the exact line it is breaking on. I suspect it is conn.connect(); or InputStream stream = conn.getInputStream();
I would also do this in the finally clause:
finally
{
if(stream != null)
stream.close();
}
It could also be the following:
You need to move all of these:
final EditText getCustID = (EditText) findViewById(R.id.customer);
final EditText custvar1 = (EditText) findViewById(R.id.var1);
final EditText custvar2 = (EditText) findViewById(R.id.var2);
final EditText custvar3 = (EditText) findViewById(R.id.var3);
final Button getData = (Button) findViewById(R.id.getData);
final Button submit = (Button) findViewById(R.id.Submit);
into onResume, rather than onCreate()

Categories

Resources