JPQL query for 2 conditions with 'and' operator - jpa

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?

Related

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;

Sling Forward with SyntheticResource

I'm trying to build a Sling servlet that returns a modified value of a resource from the JCR. I dont want to change the original resource, so I create a SyntheticResource and make my manipulations. I then return it back using the RequestDispatcher.
The following code doesn't return the Modified content as expected and I don't see any errors in the log either. Can you tell me what I'm doing wrong here
#SlingServlet(methods = "GET", resourceTypes = "sling/components/test", selectors = "test")
public class TestServlet extends SlingSafeMethodsServlet {
/**
*
*/
private static final long serialVersionUID = 4078524820231933974L;
private final Logger log = LoggerFactory.getLogger(getClass());
#Reference
ResourceResolverFactory resolverFactory;
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
Map<String, Object> param = new HashMap<String, Object>();
ResourceResolver resolver = null;
response.setContentType("text/html");
StringWriterResponse writerResponse = new StringWriterResponse(response);
PrintWriter writer = response.getWriter();
try {
param.put(ResourceResolverFactory.SUBSERVICE, "testService");
final String path = request.getRequestPathInfo().getResourcePath();
resolver = resolverFactory.getServiceResourceResolver(param);
final Resource resource = resolver.getResource(path);
String resourceType = resource.getResourceType();
Resource testResource = new SyntheticResource(resolver,
path, resourceType) {
public <T> T adaptTo(Class<T> type) {
if (type == ValueMap.class) {
ModifiableValueMap map = resource
.adaptTo(ModifiableValueMap.class);
map.put("jcr:title", "Modified Title");
return (T)map;
}
return super.adaptTo(type);
}
};
RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions();
requestDispatcherOptions.setReplaceSelectors("");
final RequestDispatcher requestDispatcher = request.getRequestDispatcher(testResource, requestDispatcherOptions);
requestDispatcher.forward(request, writerResponse);
// log.debug( writerResponse.getString() );
writer.println(writerResponse.getString());
response.setStatus(HttpServletResponse.SC_OK );
} catch (Exception e) {
log.error("Exception: ", e);
} finally {
if( resolver != null) {
resolver.close();
}
if( writer != null ){
writer.close();
}
if (writerResponse != null) {
writerResponse.clearWriter();
}
}
}
}
Using a ResourceDecorator would be simpler, it can return a ResourceWrapper that implements the required changes. Just be careful to keep the decorator's decorate method efficient when it's called for a Resource that it doesn't want to decorate, as it will be called for all Resources.

MongoUserDetailsService in java config returns null

Anybody can see why I get null when returning Customer?
I'm using java config and are able to connect to DB by my mongoConfig.
But when wants to login it seems the problem is my mongouserdtailsservice.
Thanks
public class MongoUserDetailsService implements UserDetailsService
{
#Override
public UserDetails loadUserByUsername(String username) throws AuthenticationServiceException
{
MongoOperations mongoOperations = null;
try
{
mongoOperations = new MongoTemplate(new MongoClient(), "booking");
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (MongoException e)
{
e.printStackTrace();
}
try
{
Query query = new Query(Criteria.where("email").is(username));
System.out.println("query ready to go");
Customer customer = mongoOperations.findOne(query, Customer.class);
System.out.println("query done");
System.out.println("user: "+customer);
if (customer == null)
{
throw new AuthenticationServiceException("Authentication failed for user " + username);
}
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
return new User(customer.getUsername(), customer.getPassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
getAuthorities(2));
}
catch (Exception e)
{
System.out.println("query failed");
throw new RuntimeException(e);
}
}
public Collection<? extends GrantedAuthority> getAuthorities(Integer role)
{
List<GrantedAuthority> authList = getGrantedAuthorities(getRoles(role));
return authList;
}
public List<String> getRoles(Integer role)
{
List<String> roles = new ArrayList<String>();
if (role.intValue() == 1)
{
roles.add("ROLE_USER");
roles.add("ROLE_ADMIN");
}
else if (role.intValue() == 2)
{
roles.add("ROLE_USER");
}
return roles;
}
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles)
{
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for (String role : roles)
{
authorities.add(new SimpleGrantedAuthority(role));
}
return authorities;
}
}
Solved
It was a conflict in my MongoUserDetailsService.
Here is the new one which is working well!(OBS! The new log in is with email)
#Component
public class MongoUserDetailsService implements UserDetailsService
{
public MongoOperations mongoOperations;
private User userDetails;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException
{
boolean enabled = true;
boolean accountNonLocked = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
try
{
mongoOperations = new MongoTemplate(new MongoClient(), "booking");
Customer user = getUserByEmail(email);
userDetails = new User(user.getEmail(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
getAuthorities(user.getRoleAsInt()));
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
return userDetails;
}
public List getAuthorities(Integer role)
{
List authList = new ArrayList();
if (role.intValue() == 2)
{
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
}
if (role.intValue() == 1)
{
authList.add(new SimpleGrantedAuthority("ROLE_USER"));
}
return authList;
}
public Customer getUserByEmail(String email)
{
Query query = new Query();
query.addCriteria(Criteria.where("email").is(email));
Customer customer = mongoOperations.findOne(query, Customer.class);
return customer;
}
}

The column name ... was not found in this ResultSet

We are using java jdk 1.7.0_45, postgresql jdbc connector postgresql-9.3-1100.jdbc41.jar.
Here is a synopsis of our problem, as much as possible of code pasted below.
This code:
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("d.deptId"));
Produces the error:
org.postgresql.util.PSQLException: The column name d.deptId was not found in this ResultSet.
This code:
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("deptId"));
Produces no error.
Is there a way, besides removing the "d." from the first query, to make the first code snippet not throw the error message?
Here is the source code:
public class JoinTest {
#Test
public void test(){
boolean pass = false;
try {
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
String label = rs.getMetaData().getColumnLabel(1); // What do you get?
System.out.println("label = " + label);
while (rs.next()){
System.out.println(rs.getInt("d.deptId"));
pass = true;
}
} catch (SQLException e) {
e.printStackTrace();
pass=false;
}
assertTrue(pass);
}
#Test
public void test2(){
boolean pass = false;
try {
ResultSet rs = DbConn.getInstance().doQuery("Select d.deptId from Depts d");
while (rs.next()){
System.out.println(rs.getInt("deptId"));
pass = true;
}
} catch (SQLException e) {
e.printStackTrace();
pass=false;
}
assertTrue(pass);
}
}
public class DbConn {
private static String url = "jdbc:postgresql://server:port/schema";
private static Properties props = new Properties(); {
props.setProperty("user","userid");
props.setProperty("password","passwprd");
}
private Connection conn;
private DbConn(){}
private static DbConn instance;
public static DbConn getInstance() throws SQLException{
if (instance == null){
instance = new DbConn();
instance.conn = DriverManager.getConnection(url, props);
}
return instance;
}
public ResultSet doQuery(String query) throws SQLException{
Logger.log("DbConn.doQuery: " + query);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
}
}
}
The query:
select d.deptId from Depts d
produces a single-column resultset with the result-alias "deptId". There is no "d.deptId" column. If you want one, you can request that as the column alias instead:
select d.deptId AS "d.deptId" from Depts d
PgJDBC can't do anything about this because it has no idea that the resultset column "deptId" is related to the "d.deptId" in the select-list. Teaching it about that would force it to understand way more about the SQL it processes than would be desirable, and lead to maintenance and performance challenges.
The second one works - why isn't that acceptable?
You can also do this:
System.out.println(rs.getInt(1));
If you change the query you have to change the code, too.

Spring MVC: NullReferenceException when generating form

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());
}