Java NullPointerException on MongoDb Collection findAll() - java

I am getting a NullPointerException on AlertService#findAll() method:
java.lang.NullPointerException
com.t2.claims.services.AlertService.findAll(AlertService.java:24)
com.t2.claims.controllers.AlertIndexController.doAfterCompose(AlertIndexController.java:28)
This is the findAll() method:
public List<Alert> findAll() {
Query query = new Query(where("id").exists(true));
return mongoTemplate.find(query, Alert.class);
}
The whole AlertService is as such:
package com.t2.claims.services;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.t2.claims.models.Alert;
import static org.springframework.data.mongodb.core.query.Criteria.where;
#Service("alertService")
#Transactional
public class AlertService {
#Resource(name="mongoTemplate")
private MongoTemplate mongoTemplate;
public List<Alert> findAll() {
Query query = new Query(where("id").exists(true));
return mongoTemplate.find(query, Alert.class);
}
public void add(Alert alert) {
try {
mongoTemplate.insert(alert);
} catch(Exception e) {}
}
public void update(Alert alert) {
Query query = new Query(where("id").is(alert.getId()));
try {
Update update = new Update();
update.set("assignedUser", alert.getAssignedUser());
update.set("status", alert.getStatus());
update.set("category", alert.getCategory());
update.set("vehicleStatus", alert.getVehicleStatus());
update.set("brand", alert.getBrand());
mongoTemplate.updateMulti(query, update, Alert.class);
} catch(Exception e) {}
}
public void delete(Alert alert) {
try {
Query query = new Query(where("id").is(alert.getId()));
// Run the query and delete the entry
mongoTemplate.remove(query, Alert.class);
} catch(Exception e) {}
}
}
It may be easier to check out my IntegrateMongo branch on Github to have at look in more detail. https://github.com/georgeotoole/T2ClaimsPortal/tree/IntegrateMongo
I can't understand if there is an issue with my code or perhaps mongo on my machine .. ?
Thanks

I'm pretty certain it's a case of... :
#Resource(name="mongoTemplate")
private MongoTemplate mongoTemplate;
...not being injected.
What about adding a null check in the methods that use mongoTemplate to make sure that it has been injected?
public List<Alert> findAll() {
Query query = new Query(where("id").exists(true));
if (mongoTemplate == null) {
throw new IllegalStateException("mongoTemplate is null");
}
return mongoTemplate.find(query, Alert.class);
}

Related

Create Custom Exception Not Working in Java

I'm trying to create custom exception using java, i got error when try to throw this exception
I had follow the tutor inside this https://www.baeldung.com/java-new-custom-exception
here is my custom exception
package projectdemo.exception;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
#ResponseStatus(code = HttpStatus.NOT_FOUND)
public class RecordNotFoundException extends Exception {
public RecordNotFoundException(String errorMessage) {
super(errorMessage);
}
}
and here is how i throw the exception
package projectdemo.service;
import projectdemo.model.MasterUser;
import projectdemo.classes.Response;
import projectdemo.repository.Repository;
import projectdemo.exception.RecordNotFoundException; //i had try to import this to
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.http.ResponseEntity;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
#Service
public class MasterUserService {
#Autowired
private Repository repository;
#Transactional(rollbackFor = Exception.class)
public ResponseEntity<Response<MasterUser>> method(Long id) {
MasterUser userExitsing = repository.findById(id).orElse(null);
if(userExitsing == null) throw new RecordNotFoundException("User not found"); //error in this line
Response<MasterUser> apiRes = new Response<userExitsing );
return new ResponseEntity<Response<MasterUser>>(apiRes, apiRes.status);
}
}
and this the error i got :
Am I missing something??
I would be glad for any help.
RecordNotFoundException extends Exception and, therefore, is a checked exception.
You have to declare the exception in the method signature:
#Transactional(rollbackFor = Exception.class)
public ResponseEntity<Response<MasterUser>> method(Long id) throws RecordNotFoundException {
MasterUser userExitsing = repository.findById(id).orElse(null);
if(userExitsing == null) throw new RecordNotFoundException("User not found"); //error in this line
Response<MasterUser> apiRes = new Response<userExitsing );
return new ResponseEntity<Response<MasterUser>>(apiRes, apiRes.status);
}
Alternatively, you could make it a RuntimeExcpetion. Then you don't have to declare it, plus you can remove the rollbackFor attribute in the Transactional annotation.

how can use GetListSomething() with stream

package com.eukolos.restaurant.dto;
import com.eukolos.restaurant.model.Table;
import org.springframework.stereotype.Component;
#Component
public class AllTableResponseConverter {
public AllTableResponse convert(Table table ) {
AllTableResponse allTableResponse = new AllTableResponse();
allTableResponse.setId(table.getId());
allTableResponse.setNumber(table.getNumber());
allTableResponse.setAccountList(table.getAccountList().stream().map(AccountIdResponseConverter::convert).collect(Collectors.toList()));//
return allTableResponse;
}
}`
getAccountList() cant use with stream
how can i handle?
Can you test this code below? Is this what you want to achieve?
#Component
public class AllTableResponseConverter {
public AllTableResponse convert(Table table ) {
List<AccountIdResponseConverter> convertedAccounts = new ArrayList<>();
AllTableResponse allTableResponse = new AllTableResponse();
allTableResponse.setId(table.getId());
allTableResponse.setNumber(table.getNumber());
for(Table t : table.getAccountList()) {
AccountIdResponseConverter converter = new AccountIdResponseConverter();
convertedAccounts.add(converter.convert(t));
}
allTableResponse.setAccountList(convertedAccounts);
return allTableResponse;
}
}

MongoDB Reactive Streams hangs when performing a query

I'm using the MongoDB Reactive Streams Java API which I implemented following this example, but I'm encountering a serious problem: sometimes, when I try to query a collection, the await methods doesn't work, and it hangs until the timeout is reached.
The onSubscribe methods gets called correctly, but then neither onNext, nor onError nor onComplete get called.
There doesn't seem to be a specific circumstance causing this issue.
This is my code
MongoDatabase database = MongoDBConnector.getClient().getDatabase("myDb");
MongoCollection<Document> collection = database.getCollection("myCollection");
FindPublisher<Document> finder = collection.find(Filters.exists("myField"));
SettingSubscriber tagSub = new SettingSubscriber(finder);
//SettingsSubscriber is a subclass of ObservableSubscriber which calls publisher.subscribe(this)
tagSub.await(); //this is where it hangs
return tagSub.getWrappedData();
I wrote a simple implementation of what I assumed the SettingSubscriber looked like and tried to recreate the problem using a groovy script. I couldn't - my code runs without hanging, prints each output record and exits. Code for reference below:
#Grab(group = 'org.mongodb', module = 'mongodb-driver-reactivestreams', version = '4.3.3')
#Grab(group = 'org.slf4j', module = 'slf4j-api', version = '1.7.32')
#Grab(group = 'ch.qos.logback', module = 'logback-classic', version = '1.2.6')
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoDatabase;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.FindPublisher;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.CountDownLatch;
MongoClientSettings.Builder clientSettingsBuilder = MongoClientSettings.builder()
.applyToClusterSettings { clusterSettingsBuilder ->
clusterSettingsBuilder.hosts( Arrays.asList(new ServerAddress("localhost", 27017)))
};
MongoClient mongoClient = MongoClients.create(clientSettingsBuilder.build());
MongoDatabase database = mongoClient.getDatabase("myDb");
MongoCollection<Document> collection = database.getCollection("myCollection");
FindPublisher<Document> finder = collection.find(Filters.exists("myField"));
SettingSubscriber tagSub = new SettingSubscriber(finder);
tagSub.await();
class SettingSubscriber implements Subscriber<Document> {
private final CountDownLatch latch = new CountDownLatch(1);
private Subscription subscription;
private List<Document> data = new ArrayList<>();
public SettingSubscriber(FindPublisher<Document> finder) {
finder.subscribe(this);
}
#Override
public void onSubscribe(final Subscription subscription) {
this.subscription = subscription;
subscription.request(1);
}
#Override
public void onNext(final Document document) {
System.out.println("Received: " + document);
data.add(document);
subscription.request(1);
}
#Override
public void onError(final Throwable throwable) {
throwable.printStackTrace();
latch.countDown();
}
#Override
public void onComplete() {
System.out.println("Completed");
latch.countDown();
}
public List<Document> getWrappedData() {
return data;
}
public void await() throws Throwable {
await(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
public void await(final long timeout, final TimeUnit unit) throws Throwable {
if (!latch.await(timeout, unit)) {
System.out.println("Publish timed out");
}
}
}
Can you compare this implementation of the SettingSubscriber with yours to see if something is missed?

queryRunner insert adds a parameter

I'm trying to make an insert and get the auto generated id returned. This is an Oracle database. For that i am using org.apache.commons.dbutils.QueryRunner insert which returns the first column.
The problem is i don't know for which reason i am getting added a parameter in the query and it won't let it work.
I have this code:
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Optional;
#Singleton
public class ConceptToBonusRepository extends GenericSQLRepository{
private static final String QUERY_SAVE_CONCEPT_TO_BONUS = "INSERT INTO concept_to_bonus (ID, CONCEPT_ID, CONCEPT_TYPE)" +
" VALUES (SEQ_CONCEPT_TO_BONUS_ID.NEXTVAL,?,?)";
#Inject
public ConceptToBonusRepository(#Named("OracleDataSource") #Nonnull DataSource dataSource) {
super(dataSource);
}
public Optional<Long> saveConceptToBonus(ConceptToBonus conceptToBonus)
try {
return Optional.ofNullable(
runInsert(
QUERY_SAVE_CONCEPT_TO_BONUS, conceptToBonus.getConceptId(), conceptToBonus.getConceptType()
)
);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
and my GenericlSQLRepository
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
import java.sql.SQLException;
public abstract class GenericSQLRepository {
private QueryRunner queryRunner;
private ScalarHandler<Long> autogeneratedIdHandler = new ScalarHandler<>();
protected GenericSQLRepository(#Nonnull final DataSource dataSource) {
this.queryRunner = new QueryRunner(dataSource);
}
protected Long runInsert(#Nonnull final String sql,
Object... args) throws SQLException {
return queryRunner.insert(sql, this.autogeneratedIdHandler, args);
}
}
When i try to run this i get this error
"java.sql.SQLException: Wrong number of parameters: expected 3, was given 2 Query: INSERT INTO concept_to_bonus (ID, CONCEPT_ID, CONCEPT_TYPE) VALUES (SEQ_CONCEPT_TO_BONUS_ID.NEXTVAL,?,?) Parameters: [1731472066, ORDER]"
I really don't understand why is it adding a parameter in the parameter count. When i run this insert with a simple execute, it works just fine

Testing Java code and previewing the SQL statement

The following is a Java (Hibernate) Method. How can I write a test for it? I want the test method to return a SQL statement.The code reference a lot of other classes and packages which already exist. Ignore these and just show me how to integrate them in my test program.
#Override
public AppTacticalSubUnit returnByCode(String code) throws MyOwnDAOException {
Session session = getSession();
UnitOfWork unitOfWork = new UnitOfWork();
try {
unitOfWork.beginTransaction(session);
Criteria criteria = session.createCriteria(AppTacticalSubUnit.class);
criteriaAppTacticalSubUnit.add(Restrictions.eq("code", code));
criteriaAppTacticalSubUnit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
setJoinFetches(criteria);
AppTacticalSubUnit ret = (AppTacticalUnit) criteria.uniqueResult();
unitOfWork.commit();
return ret;
} catch (HibernateException e) {
unitOfWork.rollback();
throw new ObelixxDAOException(e.getMessage(), e);
}
}
private void setJoinFetches(Criteria criteria) {
criteria.setFetchMode("appTacticalUnit.spaceOpsAreaServiceType", FetchMode.JOIN);
criteria.setFetchMode("appTacticalSubUnit.spaceOpsAreaServiceType.assExternalServiceType", FetchMode.JOIN);
criteria.setFetchMode("appTacticalSubUnit.spaceOpsAreaServiceType.assExternalServiceType.lookupServiceType", FetchMode.JOIN);
criteria.setFetchMode("appTacticalSubUnit.spaceOpsAreaServiceType.assExternalServiceType.lookupExternalServiceType", FetchMode.JOIN);
criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
criteria.addOrder(Order.asc("name"));
I have started something like this:
package na.co.sab.vitalix.db.dao;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hsqldb.Session;
import na.co.sab.datashare.util.UnitOfWork;
import na.co.sab.vitalix.db.exception.MyOwnDAOException;
import na.co.sab.vitalix.db.util.HibernateOltpSessionUtil;
public class AppTacticalSubUnitTest {
//protected static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(AppOTacticalSubUnitTest.class);
static protected HibernateOltpSessionUtil dataShareInstance;
public static void initializeVitalixOnHsql() throws Exception {
initializeVitalixOnHsql(true);
Have a look at this article http://java.dzone.com/articles/how-get-jpqlsql-string seems like it describes what you want.
The idea is to use org.hibernate.Query#getQueryString() method.

Categories