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

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

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.

Changing value of an object parameter in Java

I have a code that I repeat on every Rest Service like this:
user = getUserByToken(request.getToken());
if (user == null) {
response = this.buidResponse(Response.status(Status.UNAUTHORIZED));
}else{
do things...
}
return response;
I want to create a method to avoid repeating the first 4 lines, something like:
bool validateUser(String token, User userOut, Response responseOut){
userOut = getUserByToken(token);
if (userOut == null) {
responseOut = this.buidResponse(Response.status(Status.UNAUTHORIZED));
return false;
}
return true;
}
But as in Java parameters are passed by value-ref, the parameters does not maintain its values outside the method...
What alternative do I have?
You can make a wrapper class MyDTO and keep the parameteres as fields.
Please refer below code:
class MyDTO{
String token;
User userOut;
Response responseOut;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getUserOut() {
return userOut;
}
public void setUserOut(String userOut) {
this.userOut = userOut;
}
public Response getResponseOut() {
return responseOut;
}
public void setResponseOut(Response responseOut) {
this.responseOut = responseOut;
}
}
bool validateUser(MyDTO dto){
dto.setUserOut(getUserByToken(dto.getToken()));
if (dto.getUserOut() == null) {
dto.setResponseOut(this.buidResponse(Response.status(Status.UNAUTHORIZED)));
return false;
}
return true;
}

entity can not be null?

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

jsp checkbox value not binding

I have a problem in getting checkbox's value from JSP.
I used SpringMVC, and my related class as follows:
Form:
#Getter #Setter
public class Sample3Form extends AbstractForm {<
private List<Sample1Bean> sampleList; //all data
private ValidPagedListHolder<Sample1Bean> samplePagedList;//1 page data
}
the class to control changing page:
ValidPagedListHolder:
#SuppressWarnings("serial")
public class ValidPagedListHolder<E> extends PagedListHolder<E> implements
Serializable {
...
...
/**
* Return a sub-list representing the current page.
*/
#Override
#Valid
public List<E> getPageList() {
return super.getPageList();
}
/**
* コンストラクタ生成時の初期化処理を行うメソッド
*/
protected void init() {
setPageSize(DEFAULT_PAGE_SIZE);
}
}
Sample1Bean:
#Getter #Setter
public class Sample1Bean extends AbstractOnlineDataBean {
private String keiyakuno;
private String keiyakunm;
private String torisakino;
}
Parent Bean Class:
#Getter
#Setter
public abstract class AbstractOnlineDataBean extends AbstractDataBean {
private Integer selectedIndex;
private String maskPattern;
}
Controller:
#Controller
#RequestMapping(value = "app/sample3")
#SessionAttributes(value = "sample3Form")
#NotCheckToken
public class SampleController3 extends AbstractController {
private static Logger logger = LoggerFactory.getLogger(UserUtil.class);
#ModelAttribute(value = "sample3Form")
public Sample3Form getForm() {
return new Sample3Form();
}
......
......
#RequestMapping(value = "delete")
public String delete(Model model, #Validated Sample3Form form, BindingResult result, HttpServletRequest request) throws GdcSystemException {
List<Sample1Bean> list = new ArrayList<Sample1Bean>();
int size = form.getSampleList().size();
ValidPagedListHolder<Sample1Bean> plist = form.getSamplePagedList();
list = plist.getPageList();
for (int i = 0 ; i < size; i ++) {
if (form.getSampleList().get(i).getSelectedIndex() == null ) {
} else {
//I cannot arrive here even though I checked in JSP
list.add(form.getSampleList().get(i));
}
}
...
...
}
JSP:
<ab:form id="sample3" action="submit" modelAttribute="sample3Form">
<table width="100%" class="tableborder" cellpadding="0" cellspacing="0">
...
...
<ab:tr index="${row.index}">
<td width="2%" class="data_list_area">
<ab:checkbox path="${sample3Form.samplePagedList.pageList[row.index].selectedIndex}" fwformat='NONE'
value="${sample3Form.samplePagedList.page * sample3Form.samplePagedList.pageSize + row.index }" name="checkedids"/>
</td>
<td width="5%" class="data_list_area">
<!--ab:out value="${sample3Form.samplePagedList.pageList[row.index].keiyakuno}" /-->
<ab:label path="" fwformat='NONE'>${sample3Form.samplePagedList.pageList[row.index].keiyakuno}</ab:label>
</td>
...
...
In above JSP, I set checkboxes and bind the checkboxes to selectedIndex property for for every row data.but i cannot get selected row in controller as follows:
form.getSampleList().get(i).getSelectedIndex()
The return value is always null.
why? Could who please tell me how i can get the selectedIndex in controller?
By the way, I can get checked row in controller like below:
String[] arr = request.getParameterValues("checkedids");
Remarks: in JSP, These added checkboxes is defined by name "checkedids".
and <ab:checkbox> is a tag class extends AbstractSingleCheckedElementTag.
the src for CheckboxTagImpl is here:
public class CheckboxTagImpl extends AbstractSingleCheckedElementTag {
private String maskPatterns = null;
private boolean escapeMaskFlg = false;
/**
*
* #return
*/
public String getMaskPatterns() {
return maskPatterns;
}
/**
*
* #param maskPatterns
*/
public void setMaskPatterns(String maskPatterns) {
this.maskPatterns = maskPatterns;
}
/**
* #return
*/
public Boolean isEscapeMaskFlg() {
return escapeMaskFlg;
}
/**
* #param escapeMaskFlg
*/
public void setEscapeMaskFlg (Boolean escapeMaskFlg) {
this.escapeMaskFlg = escapeMaskFlg;
}
#Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
if (maskPatterns != null) {
FormTagImpl formTag = TagUtil.getFormTag(this);
String formClassName = formTag.getModelAttribute();
String maskPattern = TagUtil.getMaskPattern(formClassName, pageContext);
if (maskPattern != null) {
String[] maskPatternArray = maskPatterns.split(",");
for (int i = 0; i < maskPatternArray.length; i++) {
if (maskPattern.equals(maskPatternArray[i])) {
setDisabled(true);
break;
}
}
}
}
FormTagImpl formTag = TagUtil.getFormTag(this);
String formClassName = formTag.getModelAttribute();
Boolean maskFlg = TagUtil.getMaskFlg(formClassName, pageContext);
if (maskFlg == true && escapeMaskFlg == false) {
setDisabled(true);
}
if (!isDisabled()) {
// Write out the 'field was present' marker.
tagWriter.startTag("input");
tagWriter.writeAttribute("type", "hidden");
String name = WebDataBinder.DEFAULT_FIELD_MARKER_PREFIX + getName();
tagWriter.writeAttribute("id", getId());
tagWriter.writeAttribute("name", name);
tagWriter.writeAttribute("value", processFieldValue(name, SystemConstant.FLAG_OFF, getInputType()));
tagWriter.endTag();
}
super.writeTagContent(tagWriter);
return SKIP_BODY;
}
#Override
protected void writeTagDetails(TagWriter tagWriter) throws JspException {
tagWriter.writeAttribute("type", getInputType());
Object boundValue = getBoundValue();
Class<?> valueType = getBindStatus().getValueType();
if (Boolean.class.equals(valueType) || boolean.class.equals(valueType)) {
// the concrete type may not be a Boolean - can be String
if (boundValue instanceof String) {
boundValue = Boolean.valueOf((String) boundValue);
}
Boolean booleanValue = (boundValue != null ? (Boolean) boundValue : Boolean.FALSE);
renderFromBoolean(booleanValue, tagWriter);
} else if (String.class.equals(valueType) && getValue() == null) {
renderFromValue(SystemConstant.FLAG_ON, tagWriter);
}
else {
Object value = getValue();
if (value == null) {
throw new IllegalArgumentException("Attribute 'value' is required when binding to non-boolean values");
}
Object resolvedValue = (value instanceof String ? evaluate("value", value) : value);
renderFromValue(resolvedValue, tagWriter);
}
}
#Override
public void doFinally() {
if (PropertiesUtil.getProperty("cleanAtDoFinally").equals("true")) {
super.doFinally();
this.maskPatterns = null;
this.escapeMaskFlg = false;
setDisabled(false);
}
}
#Override
protected String getInputType() {
return "checkbox";
}
#Override
protected String getName() throws JspException {
if (getPath()==null) {
return super.getName();
} else {
return getPath();
}
}
#Override
protected BindStatus getBindStatus() throws JspException {
BindStatus bindStatus = null;
if (bindStatus == null) {
// HTML escaping in tags is performed by the ValueFormatter class.
String nestedPath = getNestedPath();
String pathToUse = (nestedPath != null ? nestedPath + getPath() : getPath());
if (pathToUse.endsWith(PropertyAccessor.NESTED_PROPERTY_SEPARATOR)) {
pathToUse = pathToUse.substring(0, pathToUse.length() - 1);
}
bindStatus = new BindStatus(getRequestContext(), pathToUse, false);
}
return bindStatus;
}
}
Thanks.

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