Spring MVC: NullReferenceException when generating form - forms

I'm having problems to figure out this problem. The exception is thrown when I try to go to /users/add url which should show the empty form for creating user entry. After that this exception is propagated throught the whole application.
Here is the controller code:
#Controller
#SessionAttributes(value = "user")
#RequestMapping(value = "/users")
public class UserController {
#Inject
private UserService userService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView getAllUsers() {
List<User> users = userService.getAllUsers();
return new ModelAndView("allUsers", "users", users);
}
#RequestMapping(value = "/add", method = RequestMethod.GET)
public ModelAndView addUser(ModelMap map, #RequestParam(value = "id", required = false) Long id) throws EntityNotFoundException {
User user = null;
if(id != null) {
user = userService.findById(id);
if(user == null)
throw new EntityNotFoundException("Can't find user!");
}
else {
user = new User();
user.setGender(Gender.MALE);
}
map.addAttribute("genders", generateGenders());
return new ModelAndView("addUser", "user", user);
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView addUser(ModelMap map, #Valid #ModelAttribute(value = "user") User user, BindingResult result,
HttpServletResponse response, final RedirectAttributes redirectAttributes) throws IOException {
if(!result.hasErrors()) {
try {
String userStatus = user.getId() != null ? "User Updated: " : "User Created: ";
userService.saveOrUpdateUser(user);
redirectAttributes.addFlashAttribute("userStatusMessage", userStatus + user.toString());
return new ModelAndView(new RedirectView("/users"));
} catch (EntityNotFoundException e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
return null;
}
}
else {
for (ObjectError error : result.getAllErrors()) {
System.out.println(error.getObjectName() + ": " + error.getDefaultMessage());
}
}
map.addAttribute("genders", generateGenders());
return new ModelAndView("addUser", "user", user);
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public ModelAndView deleteUser(#RequestParam(value = "id", required = true) Long id,
HttpServletResponse response, final RedirectAttributes redirectAttributes) throws IOException {
try {
User user = userService.deleteUser(id);
redirectAttributes.addFlashAttribute("userStatusMessage", "Deleted User: " + user);
} catch (EntityNotFoundException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
return null;
}
return new ModelAndView(new RedirectView("/users"));
}
private Map<String, String> generateGenders() {
Map<String,String> genders = new HashMap<String,String>();
for (Gender gender : Gender.values()) {
genders.put(gender.toString(), gender.getDisplayName());
}
return genders;
}
}
And here is the error I get when I go to /users/add:
HTTP ERROR 500
Problem accessing /users/add. Reason:
Server Error
Caused by:
java.lang.NullPointerException
at java.util.Calendar.setTime(Calendar.java:1106)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:955)
at java.text.SimpleDateFormat.format(SimpleDateFormat.java:948)
at java.text.DateFormat.format(DateFormat.java:336)
at com.code9.data.User.toString(User.java:157)
at java.lang.String.valueOf(String.java:2854)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:146)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:533)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:475)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:514)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:920)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:403)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:184)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:856)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:247)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:151)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:114)
at org.eclipse.jetty.server.Server.handle(Server.java:352)
at org.eclipse.jetty.server.HttpConnection.handleRequest(HttpConnection.java:596)
at org.eclipse.jetty.server.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:1049)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:590)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:212)
at org.eclipse.jetty.server.HttpConnection.handle(HttpConnection.java:426)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:510)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.access$000(SelectChannelEndPoint.java:34)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:40)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:450)
at java.lang.Thread.run(Thread.java:744)
Any suggestions?

I have found the problem. It's inside toString() method of User class. I'm still not shure when it's called, because I don't call it explicitly. Sorry for inconvenience.
This is User toString() method before:
#Override
public String toString() {
return String.format("%d, %s %s, %s, %s, %s, %s", this.getId(), this.getFirstName(), this.getLastName(),
new SimpleDateFormat("yyyy-MM-dd").format(this.getBirthday()), this.getGender().getDisplayName(), this.getPersonalNumber(),
this.getEmail());
}
And this is a fix:
#Override
public String toString() {
return String.format("%d, %s %s, %s, %s, %s, %s", this.getId(), this.getFirstName(), this.getLastName(),
this.getBirthday() == null ? "" : new SimpleDateFormat("yyyy-MM-dd").format(this.getBirthday()), this.getGender().getDisplayName(), this.getPersonalNumber(),
this.getEmail());
}

Related

codename one FB authentication

I have been using the following code
String clientId = "1171134366245722";
String redirectURI = "http://www.codenameone.com/";
String clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
Login fb = FacebookConnect.getInstance();
fb.setClientId(clientId);
fb.setRedirectURI(redirectURI);
fb.setClientSecret(clientSecret);
//Sets a LoginCallback listener
fb.setCallback(...);
//trigger the login if not already logged in
if(!fb.isUserLoggedIn()){
fb.doLogin();
} else {
//get the token and now you can query the facebook
String token = fb.getAccessToken().getToken();
...
}
After login into facebook account, it directly takes me to the sendRedirectURI(XXX) as specified in code and the callback function is not working. I need to run setcallback(), how do I achieve that?
You have a couple of things to do for Facebook login to work.
You need to define what kind of data you will like to fetch. The best way is to create a UserData interface and implement it in your class:
public interface UserData {
public String getId();
public String getEmail();
public String getFirstName();
public String getLastName();
public String getImage();
public void fetchData(String token, Runnable callback);
}
Then implement it like this:
class FacebookData implements UserData {
String id;
String email;
String first_name;
String last_name;
String image;
#Override
public String getId() {
return id;
}
#Override
public String getEmail() {
return email;
}
#Override
public String getFirstName() {
return first_name;
}
#Override
public String getLastName() {
return last_name;
}
#Override
public String getImage() {
return image;
}
#Override
public void fetchData(String token, Runnable callback) {
ConnectionRequest req = new ConnectionRequest() {
#Override
protected void readResponse(InputStream input) throws IOException {
try {
JSONParser parser = new JSONParser();
Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
id = (String) parsed.get("id");
email = (String) parsed.get("email");
first_name = (String) parsed.get("first_name");
last_name = (String) parsed.get("last_name");
image = (String) ((Map) ((Map) parsed.get("picture")).get("data")).get("url").toString();
} catch (Exception ex) {
}
}
#Override
protected void postResponse() {
callback.run();
}
#Override
protected void handleErrorResponseCode(int code, String message) {
if (code >= 400 && code <= 410) {
doLogin(FacebookConnect.getInstance(), FacebookData.this, true);
return;
}
super.handleErrorResponseCode(code, message);
}
};
req.setPost(false);
req.setUrl("https://graph.facebook.com/v2.10/me");
req.addArgumentNoEncoding("access_token", token);
req.addArgumentNoEncoding("fields", "id,email,first_name,last_name,picture.width(512).height(512)");
NetworkManager.getInstance().addToQueue(req);
}
}
Let's create a doLogin() method that includes the setCallback()
void doLogin(Login lg, UserData data, boolean forceLogin) {
if (!forceLogin) {
if (lg.isUserLoggedIn()) {
//process Facebook login with "data" here
return;
}
String token = Preferences.get("token", (String) null);
if (getToolbar() != null && token != null) {
long tokenExpires = Preferences.get("tokenExpires", (long) -1);
if (tokenExpires < 0 || tokenExpires > System.currentTimeMillis()) {
data.fetchData(token, () -> {
//process Facebook login with "data" here
});
return;
}
}
}
lg.setCallback(new LoginCallback() {
#Override
public void loginFailed(String errorMessage) {
Dialog.show("Error Logging In", "There was an error logging in with Facebook: " + errorMessage, "Ok", null);
}
#Override
public void loginSuccessful() {
data.fetchData(lg.getAccessToken().getToken(), () -> {
Preferences.set("token", lg.getAccessToken().getToken());
Preferences.set("tokenExpires", tokenExpirationInMillis(lg.getAccessToken()));
//process Facebook login with "data" here
});
}
});
lg.doLogin();
}
long tokenExpirationInMillis(AccessToken token) {
String expires = token.getExpires();
if (expires != null && expires.length() > 0) {
try {
long l = (long) (Float.parseFloat(expires) * 1000);
return System.currentTimeMillis() + l;
} catch (NumberFormatException ex) {
}
}
return -1;
}
Finally, call doLogin() after fb.setClientSecret()
String clientId = "1171134366245722";
String redirectURI = "http://www.codenameone.com/";
String clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
Login fb = FacebookConnect.getInstance();
fb.setClientId(clientId);
fb.setRedirectURI(redirectURI);
fb.setClientSecret(clientSecret);
doLogin(fb, new FacebookData(), false);

JPQL query for 2 conditions with 'and' operator

I have to search among the users who are active and also with a particular keyword. I have User and User_personal classes where I don't have status in user_personal class so I used search to User_personal via User because there is a Activeusers finding function in User class as below
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// TODO Auto-generated method stub
HashMap<String,String> map = RequestToMap.getBody(request);
JsonObject output = new JsonObject();
JsonArray SearchArray = new JsonArray();
boolean validToken=true;
if(validToken == true){
EntityManager em = Entitymanager.getEntitymanager();
try{
String name = map.get("fname");
if(name!=null && !name.isEmpty()){
List<User> user = User.search(name, em);
if(user!=null && !user.isEmpty()){
for(User u :user){
if(User.ActiveUsers(em).contains(u)){
JsonObject personal_details = new JsonObject();
personal_details .addProperty("id",u.getId());
personal_details .addProperty("email", u.getUser_p().getEmail());
User current_user = User.find(u.getUser_p().getEmail(), em);
personal_details.addProperty("status",current_user.getStatus().toString());
personal_details .addProperty("first_name", u.getUser_p().getFname());
personal_details .addProperty("last_name", u.getUser_p().getLname());
personal_details .addProperty("image", u.getUser_p().getImage());
personal_details .addProperty("score",current_user.getScore());
SearchArray.add(personal_details);
}
}
if((SearchArray.size()!=0))
output.add("searched_users",SearchArray);
else
output.addProperty(Constants.MESSAGE, "ACTIVE User not found. Try typing another name");
}
else
output.addProperty(Constants.MESSAGE, "User not found.Try typing another name");
}
else
output.addProperty(Constants.MESSAGE, "Please type a name to search");
}
finally{
if(em.getTransaction().isActive())
em.getTransaction().rollback();
em.close();
}
}
response.setContentType("application/JSON");
response.getWriter().println(output);
}
my search function in User class
public static List<User> search(String name,EntityManager em) {
List<User_personal> u_p = User_personal.search(name,em);
Query p = em.createQuery("select c from User c where (c.status=:stat) and (c.user_p = :u_p)");
p.setParameter("stat",Status.ACTIVE);
p.setParameter("u_p", u_p);
#SuppressWarnings("unchecked")
List<User> result = p.getResultList();
if (!result.isEmpty()) {
return result;
}
return null;
}
my search in User_personal class
public static List<User_personal> search(String str,EntityManager em) {
Query q = em.createQuery("SELECT u FROM User_personal u WHERE lower(CONCAT(u.fname,u.lname)) LIKE lower(:name) ORDER BY LOCATE(CONCAT(u.fname,u.lname),lower(:given)), LENGTH(CONCAT(u.fname,u.lname))", User_personal.class);
q.setParameter("given",str);
q.setParameter("name", "%"+str+"%");
#SuppressWarnings("unchecked")
List<User_personal> result = q.getResultList();
if (!result.isEmpty()) {
return result;
}
return null;
}
I got an exception as
<pre>com.objectdb.o.InternalException: Unexpected internal exception
com.objectdb.o.JPE.h(JPE.java:168)
com.objectdb.o.ERR.f(ERR.java:66)
com.objectdb.o.OBC.onObjectDBError(OBC.java:1560)
com.objectdb.jpa.JpaQuery.getResultList(JpaQuery.java:728)
com.professionalVerdict.model.User.search(User.java:99)
com.professionalVerdict.servlet.SearchServlet.doPost(SearchServlet.java:53)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
<pre>java.lang.NullPointerException
com.objectdb.o.EXR$e.c(EXR.java:190)
com.objectdb.o.VAR.aB(VAR.java:887)
com.objectdb.o.VAR.aA(VAR.java:830)
com.objectdb.o.BCN.o(BCN.java:305)
com.objectdb.jpa.JpaQuery.getResultList(JpaQuery.java:719)
com.professionalVerdict.model.User.search(User.java:99)
com.professionalVerdict.servlet.SearchServlet.doPost(SearchServlet.java:53)
javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</pre>
Can anyone help me finding out the solution?

Getting NullPointerException with AndroidAnnotations & ORMLite

I am using AndroidAnnotations and SQLite with ORMLite and am trying to get the database up and running. I was able to create the table and make a test-insert of a Contact object a few days ago.
However, I did some changes and then it stopped working - unfortunately I was not able to revert my changes and now I'm stuck and can't get it working anymore.
Whenever I start the app I get this error:
02-12 23:09:39.931 11766-11766/net.gazeapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: net.gazeapp, PID: 11766
java.lang.RuntimeException: Unable to start activity ComponentInfo{net.gazeapp/net.gazeapp.MainActivity_}: java.lang.NullPointerException: Attempt to invoke virtual method 'int net.gazeapp.data.ContactDao.create(java.lang.Object)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int net.gazeapp.data.ContactDao.create(java.lang.Object)' on a null object reference
at net.gazeapp.service.ContactService.addContact(ContactService.java:55)
at net.gazeapp.MainActivity.testNewORM(MainActivity.java:171)
at net.gazeapp.MainActivity.createView(MainActivity.java:148)
at net.gazeapp.MainActivity_.onViewChanged(MainActivity_.java:111)
at org.androidannotations.api.view.OnViewChangedNotifier.notifyViewChanged(OnViewChangedNotifier.java:41)
at net.gazeapp.MainActivity_.setContentView(MainActivity_.java:57)
at net.gazeapp.MainActivity_.onCreate(MainActivity_.java:45)
at android.app.Activity.performCreate(Activity.java:6251)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
So here is my MainActivity in which I do the ORM-testing (in the testNewORM() method):
#EActivity(R.layout.activity_main_viewpagertab)
#OptionsMenu(R.menu.menu_main)
public class MainActivity extends BaseActivity implements ObservableScrollViewCallbacks {
private final String TAG = getClass().getSimpleName();
private int mBaseTranslationY;
private NavigationAdapter mPagerAdapter;
private Contact mContact;
private static String[] tabTitles = null;
#App
GazeApplication application;
#ViewById(R.id.header)
View mHeaderView;
#ViewById(R.id.toolbar)
View mToolbarView;
#ViewById(R.id.pager)
ViewPager mPager;
#ViewById(R.id.fab)
FloatingActionButton fab;
#ViewById(R.id.adview)
MoPubView mAdView;
#Bean
ContactService contactService;
#AfterViews
void createView() {
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
Tools.readJsonFile(this, "fetishes.json");
// TAB TITLES: RECENT, ALL, MY MEDIA
tabTitles = new String[]{getString(R.string.recent), getString(R.string.all), getString(R.string.my_media)};
ViewCompat.setElevation(mHeaderView, getResources().getDimension(R.dimen.toolbar_elevation));
mPagerAdapter = new NavigationAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
slidingTabLayout.setCustomTabView(R.layout.tab_indicator, android.R.id.text1);
slidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccent));
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(mPager);
// When the page is selected, other fragments' scrollY should be adjusted
// according to the toolbar status(shown/hidden)
slidingTabLayout.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
propagateToolbarState(toolbarIsShown());
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
propagateToolbarState(toolbarIsShown());
displayAdBanner();
// TESTING ORMAPPER
// TESTING ORMAPPER
testNewORM();
}
void testNewORM() {
java.util.Date date = new java.util.Date();
Timestamp timeNow = new Timestamp(date.getTime());
Timestamp birthdateTimestamp = new Timestamp(date.getTime());
Date birthdate = new Date();
try {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
birthdate = dateFormat.parse("04/07/1980");
long time = birthdate.getTime();
birthdateTimestamp = new Timestamp(time);
} catch (ParseException e) {
e.printStackTrace();
}
Contact contact = new Contact("Dominik Erbsland");
contact.setBirthdate(birthdate);
try {
mContact = contactService.addContact(contact);
} catch (ItemNotFoundException | SQLException e) {
Log.e(TAG, e.getLocalizedMessage());
e.printStackTrace();
}
}
...
}
And here the other used classes:
#EBean(scope = EBean.Scope.Singleton)
public class ContactService {
private static final String TAG = ContactService.class.getSimpleName();
#RootContext
Context ctx;
#OrmLiteDao(helper = DatabaseHelper.class)
ContactDao mContactDao;
public Contact getContact(int contactId) throws ItemNotFoundException, SQLException {
Contact contact = mContactDao.queryForId(contactId);
if (contact == null) {
Log.e(TAG, "Contact not found in database");
throw new ItemNotFoundException();
}
return contact;
}
public List<Contact> getContacts() throws ItemNotFoundException, SQLException {
List<Contact> contact = mContactDao.queryForAll();
if (contact == null) {
Log.e(TAG, "Contacts not found in database");
throw new ItemNotFoundException();
}
return contact;
}
public Contact addContact(Contact contact) throws SQLException {
int rowsAffected = 0;
try {
rowsAffected = mContactDao.create(contact);
} catch (SQLException e) {
Log.e(TAG, e.getLocalizedMessage());
e.printStackTrace();
}
Log.d(TAG, "New Contact ID: " + contact.getId());
return contact;
}
public void testOutput() {
Log.d(TAG, "THIS IS A TEST OUTPUT");
}
}
here my database helper:
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "Gaze.db";
private static final int DATABASE_VERSION = 1;
private final Context context;
// the DAO object we use to access the Person table
private Dao<Contact, Integer> contactDao = null;
private Dao<MyPreferences, Integer> preferencesDao = null;
private Dao<SecurityQuestion, Integer> securityQuestionDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
/**
* This is called when the database is first created. Usually you should call createTable statements here to create
* the tables that will store your data.
*/
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) {
try {
Log.i(DatabaseHelper.class.getName(), "onCreate");
TableUtils.createTable(connectionSource, Contact.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
}
}
/**
* This is called when your application is upgraded and it has a higher version number. This allows you to adjust
* the various data to match the new version number.
*/
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
Log.i(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, Contact.class, true);
// after we drop the old databases, we create the new ones
onCreate(db, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
throw new RuntimeException(e);
}
}
/**
* Returns the Database Access Object (DAO) for our Person class. It will create it or just give the cached
* value.
*/
public Dao<Contact, Integer> getContactDao() throws SQLException {
if (contactDao == null) {
contactDao = getDao(Contact.class);
}
return contactDao;
}
public Dao<MyPreferences, Integer> getPreferencesDao() throws SQLException {
if (preferencesDao == null) {
preferencesDao = getDao(MyPreferences.class);
}
return preferencesDao;
}
public Dao<SecurityQuestion, Integer> getSecurityQuestionDao() throws SQLException {
if (securityQuestionDao == null) {
securityQuestionDao = getDao(SecurityQuestion.class);
}
return securityQuestionDao;
}
/**
* Close the database connections and clear any cached DAOs.
*/
#Override
public void close() {
super.close();
contactDao = null;
preferencesDao = null;
securityQuestionDao = null;
}
}
and the data class:
#DatabaseTable(tableName = "Contact", daoClass = ContactDao.class)
public class Contact implements Serializable {
#DatabaseField(generatedId = true, columnName = PersistentObject.ID)
int id;
#DatabaseField(index = true)
String contactName;
#DatabaseField
String mainPic;
#DatabaseField(dataType = DataType.DATE_STRING, format = "yyyy-MM-dd HH:mm:ss.S")
Date birthdate;
#DatabaseField
boolean knowPersonally;
#DatabaseField(dataType = DataType.DATE_STRING, format = "yyyy-MM-dd HH:mm:ss.S")
Timestamp created;
#DatabaseField(dataType = DataType.DATE_STRING, format = "yyyy-MM-dd HH:mm:ss.S")
Timestamp lastMod;
public Contact() {
// needed by ormlite
}
...
}
and the ContactDao:
public class ContactDao extends BaseDaoImpl<Contact, Integer> {
public ContactDao(Class<Contact> dataClass) throws SQLException {
super(dataClass);
}
public ContactDao(ConnectionSource connectionSource, Class<Contact> dataClass) throws SQLException {
super(connectionSource, dataClass);
}
public ContactDao(ConnectionSource connectionSource, DatabaseTableConfig<Contact> tableConfig) throws SQLException {
super(connectionSource, tableConfig);
}
public List<Contact> getContacts() throws SQLException {
return queryForAll();
}
}
So in the ContactService class at "mContactDao.create(contact);" it crashed with the Exception. This is the part I don't understand because ContactService is annotated with #EBean and is being accessed in MainActivity with "#Bean
ContactService contactService;" and shouldn't be null there...
Thanks for any help or hints in advance.
The problem is the following:
The code is trying to access the mContactDao field, but it is indeed null, altough it should be injected by AndroidAnnotations. But the field cannot be injected, because the dao creation fails with an exception. This is logged by AndroidAnnotations, you can check it in LogCat.
The cause of the problem lies in the Contact class. You are using List<Something> fields, but ORMLite does not know how to persist the java.util.List object. You can either use a custom persister, or you can use foreign fields:
Contact.java:
#ForeignCollectionField
private ForeignCollection<Address> adresses;
Update:
Applying the ForestCollectionField changes and debugging again showed another problem. The DataType.DATE_STRING persister cannot be used with the java.sql.Timestamp class. But you can use DataType.TIME_STAMP instead:
#DatabaseField(dataType = DataType.TIME_STAMP, format = "yyyy-MM-dd HH:mm:ss.S")
Timestamp created;
#DatabaseField(dataType = DataType.TIME_STAMP, format = "yyyy-MM-dd HH:mm:ss.S")
Timestamp lastMod;

URL issue in Facebook in BlackBerry

I have integrated Facebook in my app and trying to share some content.When I call FaceBookMain() ,it shows error like :
"Success
SECURITY WARNINNG:Please treat the URL above as you would your password and do not share it with anyone."
Sometimes this error comes after login with Facebook in browser(Webview) otherwise it comes just after clicking on share button.
Most important thing here is ,I am not facing this problem in simulator.Sharing with Facebook is working properly in Simulator but not in Device.
I am adding some class files with it:
Here is FacebookMain.java class:
import net.rim.device.api.applicationcontrol.ApplicationPermissions;
import net.rim.device.api.applicationcontrol.ApplicationPermissionsManager;
import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import net.rim.device.api.ui.UiApplication;
public class FacebookMain implements ActionListener{// extends MainScreen implements ActionListener {
// Constants
public final static String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
public final static String APPLICATION_ID = "406758776102494";//"533918076671162" ;
private final static long persistentObjectId = 0x854d1b7fa43e3577L;
static final String ACTION_ENTER = "updateStatus";
static final String ACTION_SUCCESS = "statusUpdated";
static final String ACTION_ERROR = "error";
private ActionScreen actionScreen;
private PersistentObject store;
private LoginScreen loginScreen;
private LogoutScreen logoutScreen;
private HomeScreen homeScreen;
private UpdateStatusScreen updateStatusScreen;
private RecentUpdatesScreen recentUpdatesScreen;
private UploadPhotoScreen uploadPhotoScreen;
private FriendsListScreen friendsListScreen;
private PokeFriendScreen pokeFriendScreen;
private PostWallScreen postWallScreen;
private SendMessageScreen sendMessageScreen;
private String postMessage;
private FacebookContext fbc;
public static boolean isWallPosted=false;
public static boolean isFacebookScreen = false;
public FacebookMain(String postMessge) {
this.postMessage= postMessge;
isFacebookScreen = true;
checkPermissions();
fbc=new FacebookContext(NEXT_URL, APPLICATION_ID);
loginScreen = new LoginScreen(fbc,"KingdomConnect: "+postMessge);
loginScreen.addActionListener(this);
UiApplication.getUiApplication().pushScreen(loginScreen);
}
private void init() {
store = PersistentStore.getPersistentObject(persistentObjectId);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new FacebookContext(NEXT_URL, APPLICATION_ID));
store.commit();
}
}
fbc = (FacebookContext) store.getContents();
}
private void checkPermissions() {
ApplicationPermissionsManager apm = ApplicationPermissionsManager.getInstance();
ApplicationPermissions original = apm.getApplicationPermissions();
if ((original.getPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_INTERNET) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK) == ApplicationPermissions.VALUE_ALLOW) && (original.getPermission(ApplicationPermissions.PERMISSION_EMAIL) == ApplicationPermissions.VALUE_ALLOW)) {
return;
}
/*ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_AUTHENTICATOR_API);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_WIFI);*/
ApplicationPermissions permRequest = new ApplicationPermissions();
permRequest.addPermission(ApplicationPermissions.PERMISSION_INPUT_SIMULATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_DEVICE_SETTINGS);
permRequest.addPermission(ApplicationPermissions.PERMISSION_CROSS_APPLICATION_COMMUNICATION);
permRequest.addPermission(ApplicationPermissions.PERMISSION_INTERNET);
permRequest.addPermission(ApplicationPermissions.PERMISSION_SERVER_NETWORK);
permRequest.addPermission(ApplicationPermissions.PERMISSION_EMAIL);
boolean acceptance = ApplicationPermissionsManager.getInstance().invokePermissionsRequest(permRequest);
if (acceptance) {
// User has accepted all of the permissions.
return;
} else {
}
}
public void saveContext(FacebookContext pfbc) {
synchronized (store) {
store.setContents(pfbc);
System.out.println(pfbc);
store.commit();
}
}
public void logoutAndExit() {
saveContext(null);
logoutScreen = new LogoutScreen(fbc);
logoutScreen.addActionListener(this);
}
public void saveAndExit() {
saveContext(fbc);
exit();
}
private void exit() {
AppenderFactory.close();
System.exit(0);
}
public void onAction(Action event) {}
}
It is Facebook.java class:
public class Facebook {
protected Logger log = Logger.getLogger(getClass());
public static String API_URL = "https://graph.facebook.com";
public Facebook() {
}
public static Object read(String path, String accessToken) throws FacebookException {
return read(path, null, accessToken);
}
public static Object read(String path, Parameters params, String accessToken) throws FacebookException {
Hashtable args = new Hashtable();
args.put("access_token", accessToken);
args.put("format", "JSON");
if ((params != null) && (params.getCount() > 0)) {
Enumeration paramNamesEnum = params.getParameterNames();
while (paramNamesEnum.hasMoreElements()) {
String paramName = (String) paramNamesEnum.nextElement();
String paramValue = params.get(paramName).getValue();
args.put(paramName, paramValue);
}
}
try {
StringBuffer responseBuffer = HttpClient.getInstance().doGet(API_URL + '/' + path, args);
if (responseBuffer.length() == 0) {
throw new Exception("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Throwable t) {
t.printStackTrace();
throw new FacebookException(t.getMessage());
}
}
public static Object write(String path, Object object, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
try {
JSONObject jsonObject = (JSONObject) object;
Enumeration keysEnum = jsonObject.keys();
while (keysEnum.hasMoreElements()) {
String key = (String) keysEnum.nextElement();
Object val = jsonObject.get(key);
if (!(val instanceof JSONObject)) {
data.put(key, val.toString());
}
}
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
public static Object delete(String path, String accessToken) throws FacebookException {
Hashtable data = new Hashtable();
data.put("access_token", accessToken);
data.put("format", "JSON");
data.put("method", "delete");
try {
StringBuffer responseBuffer = HttpClient.getInstance().doPost(API_URL + '/' + path, data);
if (responseBuffer.length() == 0) {
throw new FacebookException("Empty response");
}
return new JSONObject(new JSONTokener(responseBuffer.toString()));
} catch (Exception e) {
throw new FacebookException(e.getMessage());
}
}
}
And it is BrowserScreen.class:
public class BrowserScreen extends ActionScreen {
// int[] preferredTransportTypes = { TransportInfo.TRANSPORT_TCP_CELLULAR, TransportInfo.TRANSPORT_WAP2, TransportInfo.TRANSPORT_BIS_B };
int[] preferredTransportTypes = TransportInfo.getAvailableTransportTypes();//{ TransportInfo.TRANSPORT_BIS_B };
ConnectionFactory cf;
BrowserFieldConfig bfc;
BrowserField bf;
String url;
public BrowserScreen(String pUrl) {
super();
url = pUrl;
cf = new ConnectionFactory();
cf.setPreferredTransportTypes(preferredTransportTypes);
bfc = new BrowserFieldConfig();
bfc.setProperty(BrowserFieldConfig.ALLOW_CS_XHR, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.USER_SCALABLE, Boolean.TRUE);
bfc.setProperty(BrowserFieldConfig.MDS_TRANSCODING_ENABLED, Boolean.FALSE);
bfc.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
bfc.setProperty(BrowserFieldConfig.VIEWPORT_WIDTH, new Integer(Display.getWidth()));
// bfc.setProperty(BrowserFieldConfig.CONNECTION_FACTORY, cf);
bf = new BrowserField(bfc);
}
public void browse() {
show();
fetch();
}
public void show() {
add(bf);
}
public void fetch() {
bf.requestContent(url);
}
public void hide() {
delete(bf);
}
}
If any body has any clue or want some more related code to get it,please let me know.
do not use secure connection. use http instead of https.
you can refer here
same problem is presented in stackoverflow
facebook warning

SASL Authentication failed while integrating facebook chat using Smack

I am trying to integrate facebook chat using smack API.But i get an error telling authentication failed using digest md5...
Here s the code for authentication:
SASLAuthentication.registerSASLMechanism("DIGEST-MD5", SASLDigestMD5Mechanism.class);
SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0);
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222);
connection = new XMPPConnection(config);
config.setSASLAuthenticationEnabled(true);
connection.connect();
connection.login(userName, password);
below is the error i get wen i run it:
Exception in thread "main" SASL authentication failed using mechanism DIGEST-MD5:
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:325)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:395)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at JabberSmackAPIFacebook.login(JabberSmackAPIFacebook.java:31)
at JabberSmackAPIFacebook.main(JabberSmackAPIFacebook.java:77)
I can successfully connect to gtalk but am having no success vit fb...
can sumone tel me wat s the problem
For me the solution was to not include the host part in the username when calling login() without DNS SRV and not agains the Google Talk services. This is also described in the ignite forums.
E.g.
connection.login("user#jabber.org", "password", "resource");
becomes
connection.login("user", "password", "resource");
There is a huge thread at Ignite that deals with this issue. You may want to take a look at it as there are several solutions for Java and Android given that seem to work.
I have succesfully connected using DIGEST-MD5 to facebook, the code you have posted looks good.
But still we need to check the contents of your SASLDigestMD5Mechanism class
I have used the class provided in here with success
http://community.igniterealtime.org/message/200878#200878
Also you have to notice that in the DIGEST-MD5 mechanism you have to login with your facebook username and not with the email address. By default the facebook accounts don't have a username, you have to create one fisrt, you can check that in here:
http://www.facebook.com/username/
MainActivity.java
public class MainActivity extends Activity {
XMPPConnection xmpp;
ArrayList<HashMap<String, String>> friends_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Session.openActiveSession(this, true, new StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
if ( session.isOpened()){
new testLoginTask().execute();
}
}
});
}
private class testLoginTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
testLogin();
return null;
}
}
private void testLogin(){
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
config.setDebuggerEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
config.setTruststoreType("AndroidCAStore");
config.setTruststorePassword(null);
config.setTruststorePath(null);
} else {
config.setTruststoreType("BKS");
String path = System.getProperty("javax.net.ssl.trustStore");
if (path == null)
path = System.getProperty("java.home") + File.separator + "etc"
+ File.separator + "security" + File.separator
+ "cacerts.bks";
config.setTruststorePath(path);
}
xmpp = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
try {
xmpp.connect();
Log.i("XMPPClient","Connected to " + xmpp.getHost());
} catch (XMPPException e1) {
Log.i("XMPPClient","Unable to " + xmpp.getHost());
e1.printStackTrace();
}
try {
String apiKey = Session.getActiveSession().getApplicationId();
String sessionKey = Session.getActiveSession().getAccessToken();
String sessionSecret = "replace with your app secret key";
xmpp.login(apiKey + "|" + sessionKey, sessionSecret , "Application");
Log.i("XMPPClient"," its logined ");
Log.i("Connected",""+xmpp.isConnected());
if ( xmpp.isConnected()){
Presence presence = new Presence(Presence.Type.available);
xmpp.sendPacket(presence);
}
} catch (XMPPException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
SASLXFacebookPlatformMechanism.java
public class SASLXFacebookPlatformMechanism extends SASLMechanism{
private static final String NAME = "X-FACEBOOK-PLATFORM";
private String apiKey = "";
private String accessToken = "";
/**
* Constructor.
*/
public SASLXFacebookPlatformMechanism(SASLAuthentication saslAuthentication) {
super(saslAuthentication);
}
#Override
protected void authenticate() throws IOException, XMPPException {
getSASLAuthentication().send(new AuthMechanism(NAME, ""));
}
#Override
public void authenticate(String apiKey, String host, String accessToken) throws IOException, XMPPException {
if (apiKey == null || accessToken == null) {
throw new IllegalArgumentException("Invalid parameters");
}
this.apiKey = apiKey;
this.accessToken = accessToken;
this.hostname = host;
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, this);
authenticate();
}
#Override
public void authenticate(String username, String host, CallbackHandler cbh) throws IOException, XMPPException {
String[] mechanisms = { "DIGEST-MD5" };
Map<String, String> props = new HashMap<String, String>();
this.sc = Sasl.createSaslClient(mechanisms, null, "xmpp", host, props, cbh);
authenticate();
}
#Override
protected String getName() {
return NAME;
}
#Override
public void challengeReceived(String challenge) throws IOException {
byte[] response = null;
if (challenge != null) {
String decodedChallenge = new String(Base64.decode(challenge));
Map<String, String> parameters = getQueryMap(decodedChallenge);
String version = "1.0";
String nonce = parameters.get("nonce");
String method = parameters.get("method");
long callId = new GregorianCalendar().getTimeInMillis();
String composedResponse = "api_key="
+ URLEncoder.encode(apiKey, "utf-8") + "&call_id=" + callId
+ "&method=" + URLEncoder.encode(method, "utf-8")
+ "&nonce=" + URLEncoder.encode(nonce, "utf-8")
+ "&access_token="
+ URLEncoder.encode(accessToken, "utf-8") + "&v="
+ URLEncoder.encode(version, "utf-8");
response = composedResponse.getBytes("utf-8");
}
String authenticationText = "";
if (response != null) {
authenticationText = Base64.encodeBytes(response,
Base64.DONT_BREAK_LINES);
}
// Send the authentication to the server
getSASLAuthentication().send(new Response(authenticationText));
}
private Map<String, String> getQueryMap(String query) {
Map<String, String> map = new HashMap<String, String>();
String[] params = query.split("\\&");
for (String param : params) {
String[] fields = param.split("=", 2);
map.put(fields[0], (fields.length > 1 ? fields[1] : null));
}
return map;
}
}