entity can not be null? - java

I wanted to retrieve found object or a null from a database.
In my ProjectFollowerImpl, for a method useFollowingProject I return a single instance that matches the query, or null if the query returns no results.
#Override
public ProjectFollower userFollowingProject(Integer userId, Integer projectId) {
return (ProjectFollower) session.createCriteria(classType)
.add(Restrictions.eq("user.id", userId))
.add(Restrictions.eq("project.id", projectId))
.uniqueResult();
}
Then in a tapestry page, I have following methods:
public ProjectFollower getUserFollowingProject() {
return projectFollowerDao.userFollowingProject(loggedInUser.getId(), project.getId());
}
#CommitAfter
void onActionFromFollowProject() {
ProjectFollower pf = getUserFollowingProject();
if (pf != null) {
projectFollowerDao.delete(pf.getId());
} else {
pf = new ProjectFollower();
pf.setProjectId(project);
pf.setUserId(loggedInUser);
projectFollowerDao.merge(pf);
}
}
However, tapestry throws null pointer exception, stack trace:
com.rile.issuetracker.pages.Tracker getUserFollowingProject() Tracker.java 75
com.rile.issuetracker.pages.Tracker advised$onActionFromFollowProject_6d8b9673baf() Tracker.java 80
So why is it a problem to return a null value for a object? What am I doing wrong ?
UPDATE:
public class Tracker {
#Property
#SessionState
private User loggedInUser;
#Property
#Inject
private ProjectDao projectDao;
#Property
private Project projectP1, project;
#Property
private List<Project> projectList;
#Property
#Inject
private ProjectFollowerDao projectFollowerDao;
#Property
#Inject
private TicketDao ticketDao;
#Property
private List<Ticket> ticketList;
#Property
private Ticket ticketP1;
#Property
#Inject
private TicketFollowerDao ticketFollowerDao;
#Property
private Util util = new Util();
public boolean getLoggedIn() {
return loggedInUser.getEmail() != null;
}
#PageLoaded
void onPageLoad() {
projectList = projectDao.loadAll();
ticketList = ticketDao.loadAll();
}
void onActivate(Integer contextValue) {
if (contextValue != null) {
project = projectDao.getByID(contextValue);
}
if (project != null) {
List ticketListByProjectID = ticketDao.getTicketsByProjectID(project.getId());
if (!ticketListByProjectID.isEmpty()) {
ticketList = ticketListByProjectID;
} else {
ticketList = null;
}
}
}
public ProjectFollower getUserFollowingProject() {
return projectFollowerDao.userFollowingProject(loggedInUser.getId(), project.getId());
}
#CommitAfter
void onActionFromFollowProject() {
ProjectFollower pf = getUserFollowingProject();
if (pf != null) {
projectFollowerDao.delete(pf.getId());
} else {
pf = new ProjectFollower();
pf.setProjectId(project);
pf.setUserId(loggedInUser);
projectFollowerDao.merge(pf);
}
}
public boolean getIsUserFollowingTicket() {
return ticketFollowerDao.isUserFollowingTicket(loggedInUser.getId(), ticketP1.getId());
}
#CommitAfter
void onActionFromFollowTicket() {}
public String getActiveFor(String parameter) {
if (parameter == null || parameter.isEmpty()) {
return null;
}
switch (parameter) {
case "userFollowingProject":
return getUserFollowingProject() != null ? "active" : "null";
case "userFollowingTicket":
return getIsUserFollowingTicket() ? "anchor-active" : "anchor-inactive";
default:
return null;
}
}
}

From the complete code, it looks like the best bet is that project is null, after checking complete class, we see that its not injected, and its value is only set in onActivate function, if contextValue is not null and projectDao.getByID(contextValue) returns a non-null value.
Could you please confirm that is happenning correctly before the call to onActionFromFollowProject

Related

JPA Attribute Converter

I have some problem when I input value like this [] or [""] to insert data base.
It will infinity loop not stop.
I don't know why.
Example source code below.
#Entity("student")
class Student {
......
#Column(name = "something")
#Convert(converter = CustomConverter.class)
private List<String> something;
}
#Converter
public class CustomConverter implements AttributeConverter<List<String>, String> {
#Override
public String convertToDatabaseColumn(final List<String> param) {
if (param == null) {
return null;
} else if (param.isEmpty()) {
return null;
} else {
return String.join(",", param);
}
}
#Override
public List<String> convertToEntityAttribute(final String param) {
if (param == null) {
return null;
} else if (param.isEmpty()) {
return null;
} else {
return Arrays.asList(param.split(","));
}
}
But when I use value valid is working fine like this value ["vanda","nico"]
Question how to solve it and why this process loop forever ?
Thank you.

design patterns (command pattern) to avoid the multiple if conditions

This is the request that been sent to service layer
public class UserRequest {
private String id;
private String link;
private String searchText;
}
Created class for "user response creator" -> to have different transformations
#Component
public class UserResponseCreator {
#Autowired
private UserInfoServiceClient userInfoServiceClient;
public List<UserResponse> getUserResponse() {
//transformation one
}
public List<UserResponse> getUserResponse(UserRequest request) {
//transformation two
}
}
The service class:
#Service
public class UserService {
#Autowired
private UserResponseCreator UserResponseCreator;
public List<UserResponse> sendEntries(UserRequest request) {
String node = request.getnode();
String link = request.getLinkedTo();
String searchText = request.getSearchText();
List<UserResponse> UserResponses = new ArrayList<>();
if ( node == null && link == null && searchText == null ) {
UserResponses = UserResponseCreator.getUserResponse();
} else if (node != null && link != null) {
UserResponses = UserResponseCreator.getUserResponse(request);
} else if (searchText!=null) {
UserResponses = UserResponseCreator.getUserResponse();
} else {
throw new InvalidRequestBodyException("Please check the request body");
}
return UserResponses;
}
}
Now I have following issues:
How to avoid the multiple if and repeated null checks
Have to use command pattern and create a method to pass parameter , check null values
For the null check i prepared a method:
public boolean checkFieldsIsNull(Object... varArgs) {
return Stream.of(varArgs)
.allMatch(Objects::isNull);
}

BeanPropertyRowMapper cache problem on Tomcat

I am using my custom row mapper extended from BeanPropertyRowMapper to override underscoreName method. It was working well. I added new fields to DTO class and deployed to Tomcat again. But it couldn't map new fields. In BeanPropertyRowMapper's initialize method it is using BeanUtils.getPropertyDescriptors(mappedClass). I think the problem is due to not updated cache on deploy.
I tried to restart tomcat but it didn't work.
#Slf4j
public class ColumnRowMapper<T> extends BeanPropertyRowMapper<T> {
private ColumnRowMapper(final Class<T> mappedClass) {
super(mappedClass);
}
#Override
protected String underscoreName(final String name) {
Field declaredField = getField(getMappedClass(), name);
String columnName = getColumnName(declaredField);
return columnName == null ? super.underscoreName(name) : columnName.toLowerCase();
}
private Field getField(Class<?> clazz, String name) {
if (clazz == null) {
return null;
}
Field field = null;
try {
field = clazz.getDeclaredField(name);
} catch (Exception e) {
field = getField(clazz.getSuperclass(), name);
}
if (field == null) {
log.warn("Ups, field «{}» not found in «{}».", name, clazz);
}
return field;
}
private String getColumnName(Field declaredField) {
Column annotation;
String columnName;
if (declaredField == null || (annotation = declaredField.getAnnotation(Column.class)) == null
|| StringUtils.isEmpty(columnName = annotation.name())) {
return null;
}
return columnName;
}
public static <T> BeanPropertyRowMapper<T> newInstance(final Class<T> mappedClass) {
return new ColumnRowMapper<>(mappedClass);
}
}

Binding DatePicker

I want to bindBiderectional() DatePicker. Here is what I did
#FXMLController("title.fxml")
public class Controller {
#FXML
private DatePicker dp_date_from;
#Inject
private Model model;
...
#PostConstruct
public void init(){
...
dp_date_from.valueProperty().bindBidirectional(model.dateFromProperty());
...
}
Model Class
#FlowScoped
public class Model {
private ObjectProperty<LocalDate> dateFrom;
public ObjectProperty<LocalDate> dateFromProperty() {
return dateFrom;
}
...
}
It throws an error:
io.datafx.controller.FxmlLoaderException:java.lang.reflect.InvocationTargetException
What can be the reason for that?
Error, is thrown in application itself, it doesn't write anything in a console. I've debegged the code, and when it comes to line dp_date_from.valueProperty... it goes here for throwing an exception:
public <T> ViewContext<T> createByController(Class<T> controllerClass, String fxmlName, ViewConfiguration viewConfiguration, Object... viewContextResources) throws FxmlLoadException {
try {
Object e = controllerClass.newInstance();
ViewMetadata metadata = new ViewMetadata();
FXMLController controllerAnnotation = (FXMLController)controllerClass.getAnnotation(FXMLController.class);
if(controllerAnnotation != null && !controllerAnnotation.title().isEmpty()) {
metadata.setTitle(controllerAnnotation.title());
}
if(controllerAnnotation != null && !controllerAnnotation.iconPath().isEmpty()) {
metadata.setGraphic(new ImageView(controllerClass.getResource(controllerAnnotation.iconPath()).toExternalForm()));
}
FXMLLoader loader = this.createLoader(e, fxmlName, viewConfiguration);
Node viewNode = (Node)loader.load();
ViewContext context = new ViewContext(viewNode, e, metadata, viewConfiguration, viewContextResources);
context.register(e);
context.register("controller", e);
this.injectFXMLNodes(context);
context.getResolver().injectResources(e);
Method[] var11 = e.getClass().getMethods();
int var12 = var11.length;
for(int var13 = 0; var13 < var12; ++var13) {
Method method = var11[var13];
if(method.isAnnotationPresent(PostConstruct.class)) {
method.invoke(e, new Object[0]);
}
}
return context;
} catch (Exception var15) {
throw new FxmlLoadException(var15);
}
}
Thanks, the error is due to I didn't initialized dateFrom. I've just added this part into Model class
public ObjectProperty<LocalDate> dateFromProperty() {
if(dateFrom == null){
dateFrom = new SimpleObjectProperty<>();
}
return dateFrom;
}
Thanks to everybody

I cannot show returned java class data in AdvanedDataGridColumn of Flex AdvanedDataGrid

all guys
I am developing with Flex + java + hibernate in one project.
I am trying to add one more advanceddatagridcolumn in flex AdavanedDataGrid control.
Actually it work very well but only except I added column’s data.
I have no idea what should I do to make it out
I am telling work flow.
At first call select method in DeliveryService.class through the RemoteObject and then call
DeliveryMgr.class for call business work. After get return list type return value it pass to presentation class to setting all of the selected return value.
I can print trace log what I added column’s data in DeliveryPt.class but it cannot return to flex area.
Strange thing is I can check out value of what I want to show data in DeliveryPt.class but it does not show up in AdvanedDataGridColumn of Flex.
Thank you for reading in Advance.
DeliverService.java
public DeliveryService() {
}public List<DeliveryPt> selectMaterialForReReceiptDelivery(String referenceNo,String team,String buyerCode,Integer kind,String sessionId){
List<DeliveryPt> rtnList = new ArrayList<DeliveryPt>();
List<Delivery> tmpList = new ArrayList<Delivery>();
ApplicationContext ac = CommonResource.getAppcontext();
DeliveryMgr dmgr = (DeliveryMgr)ac.getBean("DeliveryMgr");
tmpList = dmgr.selectMaterialForReReceiptDelivery(referenceNo,team,buyerCode,kind,sessionId);
for (int i=0; i<tmpList.size(); i++){
DeliveryPt dp = new DeliveryPt(tmpList.get(i));
rtnList.add(dp);
}
return rtnList;
}
}
DeliveryPt.java
public class DeliveryPt {
//2011.02.23 New Added DeliverySlipNo to show in flex
public String DeliverySlipSlipNo;
public DeliveryPt(Delivery delivery) {
this.setDeliveryNo(delivery.getDeliveryNo());
this.ReIncomeFlag = delivery.getReIncomeFlag();
ApplicationContext ac = CommonResource.getAppcontext();
StockMgr smgr = (StockMgr)ac.getBean("StockMgr");
Stock stock = smgr.getStock(delivery.getStock_Id());
if (delivery.getBooking() != null){
this.setOrderType(delivery.getOrderType());
this.setSalesOrderNo(delivery.getSalesOrderNo());
this.setRemark(delivery.getRemark());
this.setReferenceNo(stock.getReferenceNo());
// 유저 참조값 시작.
if(delivery.getDeliveryUser() != null){
this.setDeliveryUserName(delivery.getDeliveryUser().getName());
}
if(delivery.getInsertUser() != null){
this.setInsertUserName(delivery.getInsertUser().getName());
}
if(delivery.getUpdateUser() != null){
this.setUpdateUserName(delivery.getUpdateUser().getName());
}
if(delivery.getExpiredUser() != null){
this.setExpiredUserName(delivery.getExpiredUser().getName());
}
if (delivery.getBooking() != null){
if(delivery.getBooking().getInsertUser() != null){
this.setBookingUserName(delivery.getBooking().getInsertUser().getName());
}
}
// 유저 참조값 끝.
// 각종 날짜 입력.
if (delivery.getDeliveryDate() != null){
this.setDeliveryDate(delivery.getDeliveryDate());
}
if (delivery.getExpiredDate() != null){
this.setExpiredDate(delivery.getExpiredDate());
}
if (delivery.getInsertDate() != null){
this.setInsertDate(delivery.getInsertDate());
}
if (delivery.getUpdateDate() != null){
this.setUpdateDate(delivery.getUpdateDate());
}
if (stock.getSizeLabel() != null){
this.SizeLabelId = stock.getSizeLabel().getId();
}
this.Kind_id = stock.getKind_id();
this.StockId = delivery.getStock_Id();
// assigned value to varilable
this.DeliverySlipSlipNo = delivery.getDeliverySlip_SlipNo();
if (stock.getColorMst() != null){
this.ColorCode = stock.getColorMst().getColorCode();
this.ColorName = stock.getColorMst().getColorName();
}
this.Color_Name = stock.getColor_Name();
if (stock.getBuyer() != null){
this.BuyerCode = stock.getBuyer().getCode();
this.BuyerName = stock.getBuyer().getCode();
}
this.Team = stock.getTeam();
this.CancelFlag = delivery.getCancelFlag();
}
public String getBookingUserId() {
return BookingUserId;
}
public void setBookingUserId(String bookingUserId) {
BookingUserId = bookingUserId;
}
public String getDeliveryUserId() {
return DeliveryUserId;
}
public void setDeliveryUserId(String deliveryUserId) {
DeliveryUserId = deliveryUserId;
}
public String getInsertUserId() {
return InsertUserId;
}
public void setInsertUserId(String insertUserId) {
InsertUserId = insertUserId;
}
public String getUpdateUserId() {
return UpdateUserId;
}
public void setUpdateUserId(String updateUserId) {
UpdateUserId = updateUserId;
}
public Integer getSizeLabelId() {
return SizeLabelId;
}
public void setSizeLabelId(Integer sizeLabelId) {
SizeLabelId = sizeLabelId;
}
public Integer getKind_id() {
return Kind_id;
}
public void setKind_id(Integer kind_id) {
Kind_id = kind_id;
}
public Integer getStockId() {
return StockId;
}
public void setStockId(Integer stockId) {
StockId = stockId;
}
//Getter and Setter
public String getDeliverySlipSlipNo() {
return DeliverySlipSlipNo;
}
public void setDeliverySlipSlipNo(String deliverySlipSlipNo) {
DeliverySlipSlipNo = deliverySlipSlipNo;
}
}
Delivery.java
#Entity
#Table(name="Delivery")
public class Delivery {
public Delivery(){} // Default Constructor
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="DeliveryNo")
private Integer DeliveryNo;//2011.02.25 Added
#Column(name="DeliverySlip_SlipNo",length=20)
private String DeliverySlip_SlipNo;
//Getters an Setters for DeliverySlip_SlipNo
public String getDeliverySlip_SlipNo() {
return DeliverySlip_SlipNo;
}
public void setDeliverySlip_SlipNo(String deliverySlip_SlipNo) {
DeliverySlip_SlipNo = deliverySlip_SlipNo;
}
Have you added the new column to the equivalent action script object mapped to the Java object?

Categories

Resources