Junit: unexpected invocation after upgrading MyBatis to 3.1.1 - java

Scenario:
final CatalogRuleExample example = new CatalogRuleExample();
example.createCriteria().andCatalogIdEqualTo(catalogId);
example.setOrderByClause("position ASC");
final List<CatalogRuleRecord> records = new ArrayList<CatalogRuleRecord>();
final CatalogRuleRecord firstRecord = new CatalogRuleRecord();
final CatalogRuleRecord secondRecord = new CatalogRuleRecord();
records.add(firstRecord);
records.add(secondRecord);
mockery.checking(new Expectations() {
{
oneOf(catalogRuleDAO).selectByExample(example);
will(returnValue(records));
...
Problem:
The final example of CatalogRuleExample is not the same in my mockery.checking by selectByExample. If i override the equals() it will work. But i wanted to know, if there is a better solution for this case. Thanks in advance
PS: this same code worked bevor i migrate from Ibatis to Mybtis
final CatalogRuleExample example = new CatalogRuleExample() {
#Override
public boolean equals(Object that) {
if (that instanceof CatalogRuleExample) {
CatalogRuleExample other = (CatalogRuleExample) that;
if (other.getOredCriteria().size() != 1) {
return false;
}
if (other.getOredCriteria().get(0).getCriteria().size() != 1) {
return false;
}
if (!other.getOredCriteria().get(0).getCriteria().get(0).getValue().equals(catalogId)) {
return false;
}
if (!other.getOrderByClause().equals("position ASC")) {
return false;
}
return true;
}
return false;
}
};
ERROR:
unexpected invocation: catalogRuleDAO.selectByExample(<com.protogo.persistence.dao.CatalogRuleExample#a6ca0ea9>)
expectations:
expected once, never invoked: catalogRuleDAO.selectByExample(<com.protogo.persistence.dao.CatalogRuleExample#66e1beb1>); returns <[com.protogo.persistence.data.CatalogRuleRecord#4f7d02c2, com.protogo.persistence.data.CatalogRuleRecord#4f7d02c2]>

Related

How to shorten the condition code ? (JAV, Check null)

I use it to check for null.DataSet has a structure of both String Integer and Bigdecimal data types.
How to shorten the condition code? Is there any way? To shorten my code. Thank you.
public void ConfrimData(DataSet data) {
if (StringUtils.isEmpty(data.getA())
|| StringUtils.isEmpty(data.getB())
|| StringUtils.isEmpty(data.getC())
|| StringUtils.isEmpty(data.getD())
|| StringUtils.isEmpty(data.getE())
|| StringUtils.isEmpty(data.getF())
){
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
return;
}
_DataSet
private String A = null;
private Integer B = null;
private String C= null;
private String D = null;
private BigDecimal E= null;
private String F= null;
Well, you could make it slightly less repeaty using streams, but it won't make it necessarily better, let alone faster:
LinkedHashMap<Supplier, String> map = new LinkedHashMap<>();
map.put(data::getA, Var.VALUE_A);
map.put(data::getB, Var.VALUE_B);
map.put(data::getC, Var.VALUE_C);
map.put(data::getD, Var.VALUE_D);
map.put(data::getE, Var.VALUE_E);
map.put(data::getF, Var.VALUE_F);
List<String> logMessages = map.entrySet().stream()
.filter(entry -> StringUtils.isEmpty(entry.getKey().get()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
if (!logMessages.isEmpty()) {
logMessages.forEach(loggerTransaction::info);
}
else {
// Remaining code
}
In your first if statement you check all the parameters to see if any of them are empty.
Then, in the inner if statements, you check them again. The first check is redundant. The return statement is also not necessary since it does not end the method early or returns any data.
Here is a shorter version that should give the same result:
public void confirmData(DataSet data) {
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
}
EDIT
Here is a slightly prettier solution with less code repetition:
public void confirmData(DataSet data) {
logIfEmpty(data.getA(), Var.VALUE_A);
logIfEmpty(data.getB(), Var.VALUE_B);
logIfEmpty(data.getC(), Var.VALUE_C);
logIfEmpty(data.getD(), Var.VALUE_D);
logIfEmpty(data.getE(), Var.VALUE_E);
logIfEmpty(data.getF(), Var.VALUE_F);
}
private void logIfEmpty(Object check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
}
}
EDIT #2
And if you have other code you want to execute if you did not find any empty values, you can do this:
public void confirmData(DataSet data) {
boolean foundEmpty;
foundEmpty = logIfEmpty(data.getA(), Var.VALUE_A);
foundEmpty = logIfEmpty(data.getB(), Var.VALUE_B) || foundEmpty;
foundEmpty = logIfEmpty(data.getC(), Var.VALUE_C) || foundEmpty;
foundEmpty = logIfEmpty(data.getD(), Var.VALUE_D) || foundEmpty;
foundEmpty = logIfEmpty(data.getE(), Var.VALUE_E) || foundEmpty;
foundEmpty = logIfEmpty(data.getF(), Var.VALUE_F) || foundEmpty;
if(foundEmpty) {
return;
}
}
private boolean logIfEmpty(String check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
return true;
}
return false;
}
Maybe assigning a flag...
public void ConfrimData(DataSet data) {
boolean flag;
if (flag = StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (flag = StringUtils.isEmpty(data.getB()) || flag) {
loggerTransaction.info(Var.VALUE_B);
}
if (flag = StringUtils.isEmpty(data.getC()) || flag) {
loggerTransaction.info(Var.VALUE_C);
}
if (flag = StringUtils.isEmpty(data.getD()) || flag) {
loggerTransaction.info(Var.VALUE_D);
}
if (flag = StringUtils.isEmpty(data.getE()) || flag) {
loggerTransaction.info(Var.VALUE_E);
}
if (flag = StringUtils.isEmpty(data.getF()) || flag) {
loggerTransaction.info(Var.VALUE_F);
}
if (flag) return;

Common method for null check

I want to create a common method which will check for null on primary keys of database tables.
I have two type of datatype
String
Date
Want to create a common function which will take parameters on the run time and check for null.
Table 1:
private boolean checkForNullEntries(Table1 table1) {
if (StringUtil.isNullOrEmpty(table1.getName())) {
return true;
} else if (table1.getLastUpdateTime() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table1 table1) {
boolean nullValueFound = checkForNullEntries(table1);
if (nullValueFound) {
//skip db operation
} else {
// save to DB
}
}
Table 2:
private boolean checkForNullEntries(Table2 table2) {
if (table2.getTimeSlot == null) {
return true;
} else if (table2.getDate() == null) {
return true;
}
return false;
}
public checkIfPrimaryKeyIsNull(Table2 table2) {
boolean nullValueFound = checkForNullEntries(table2);
if (nullValueFound){
//skip db operation
} else {
// save to DB
}
}
I want to create a common method for both the tables. Any suggestion experts
Using a Map, you should be able to pass any table to the functions, regardless of the data type you wanna test, and then establish each test case in a different 'if', as follows:
private static boolean checkForNullEntries(Map<String, Table> map) {
if(map.get("String") != null) {
if (StringUtil.isNullOrEmpty(map.get("String").getName())) {
return true;
} else if (map.get("String").getLastUpdateTime() == null) {
return true;
}
return false;
}
if(map.get("Date") != null) {
if (map.get("Date").getTimeSlot == null) {
return true;
} else if (map.get("Date").getDate() == null) {
return true;
}
return false;
}
return false;
}
Then you can call the function like this:
Map<String, Table> map = new HashMap<>();
map.put("Date", table2);
boolean result = checkForNullEntries(map);

How to export huge result set of a mybatis select query to csv?

Using MyBatis, I am getting close to 65,000 results from a select query within a mapper. I want to create a csv and send these results as a zip file to the UI call which will trigger the download dialog directly of the browser.
Upon searching, I understood that we need to use custom result handler in these scenarios. But the link to the example from ibatis seems to be removed http://code.google.com/p/mybatis/wiki/ResultHandlerExample leaving no accurate steps for me to use or implement it.
However, I have tried as below.
public class CSVExportRowHandler implements ResultHandler {
#SuppressWarnings("unchecked")
#Override
public void handleResult(ResultContext context) {
SRDContainer srdContainer = (SRDContainer) context.getResultObject();
System.out.println("Container: " + srdContainer.toString() + ", " + context.getResultCount() +", "+ context.isStopped());
for (StudentResultDetails srd : srdContainer.getStudentResultDetails()){
System.out.println("result: " + srd.getStudentName());
}
}
}
As the handleResult method must return void. On this note, I have the below queries.
I am able to print to the console only one record upon using this CSVExportRowHandler class. What happened to the rest of the records
(should have been 65k) ?
Is there any optimized way of doing this ?
How to trigger the download dialog of browser directly ? before that do I need to write the records to csv or I can stream the results to download ?
Here are my DAO and the jax-rs service for reference
DAO.java
public void exportSRD(HashMap<String, Object> params) {
SqlSession sqlSession = SessionFactory.getSession().openSession();
try {
CSVExportRowHandler handler = new CSVExportRowHandler();
sqlSession.select("getAssignmentSRDSession", params, handler);
} finally {
sqlSession.close();
}
}
Service:
#Path("/{reportType}/studentresultdetails/{function}/{sessionId}")
#GET
public void exportOrPrintUtil(#PathParam("reportType") String reportType, #PathParam("function") String function, #QueryParam("pageNum") Integer pageNum,
#QueryParam("pageSize") Integer pageSize, #QueryParam("sortOn") String sortOn, #QueryParam("sortOrder") String sortOrder,
#QueryParam("filterByName") String filterByName, #PathParam("sessionId") Integer sessionId) throws IOException {
HashMap<String, Object> params = new HashMap<String, Object>();
Object enableSort;
Object enablePrintOrExportFlag;
params.put("sessionId", sessionId);
params.put("enableSort", false);
params.put("enablePrintOrExportFlag", true);
params.put("filterByName", filterByName);
dao.exportSRD(params);
*********** WHAT TO BE RETURNED AS THE ABOVE dao.exportSRD(params) RETURNS VOID. HOW TO TRIGGER DOWNLOAD DIALOG FROM HERE. *****************
}
SRDContainer.java object
#XmlRootElement
public class SRDContainer implements Comparable<SRDContainer> {
private List<StudentResultDetails> studentResultDetails;
public SRDContainer() {}
public SRDContainer(
List<StudentResultDetails> studentResultDetails) {
super();
this.studentResultDetails = studentResultDetails;
}
public List<StudentResultDetails> getStudentResultDetails() {
return studentResultDetails;
}
public void setStudentResultDetails(
List<StudentResultDetails> studentResultDetails) {
this.studentResultDetails = studentResultDetails;
}
#Override
public int compareTo(SRDContainer o) {
return 0;
}
#Override
public String toString() {
return "SRDContainer [studentResultDetails="
+ studentResultDetails + "]";
}
public List<String[]> toStringArrayList() {
String[] array = new String[studentResultDetails.size()];
List<String[]> stringArrayListOut = new ArrayList<String[]>();
int index = 0;
for (StudentResultDetails value : this.studentResultDetails) {
array[index] = value.toFlatCSVString();
index++;
}
stringArrayListOut.add(array);
return stringArrayListOut;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((studentResultDetails == null) ? 0 : studentResultDetails
.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SRDContainer other = (SRDContainer) obj;
if (studentResultDetails == null) {
if (other.studentResultDetails != null)
return false;
} else if (!studentResultDetails.equals(other.studentResultDetails))
return false;
return true;
}
}
I am pretty new to jax-rs and mybatis.
Thanks !!!!
sessionID make your code too complicated , jackoffID as well. even with deferred loading (thanks to CGLib proxies). It gets just a little fuzzy, however, when discussing how to implement complex queries
select id, name, shortName, description
from tag

ClassCastException error

I am doing one android application, for that I used com.android.internal API's. They are Call.java, CallManger.java. For these classes I created subclass for Call.java. You can find these two classes here http://hi-android.info/src/com/android/internal/telephony/Call.java.html and http://hi-android.info/src/com/android/internal/telephony/CallManager.java.html.
Subclass of Call.java is:
public class MyCall extends Call{
1. CallManager cm = CallManager.getInstance();
2. Phone.State state;
3.
4. Phone mDefaultPhone;
5. private final ArrayList<Connection> emptyConnections = new ArrayList<Connection>();
6. List<Call> ringingCall;
7.
8. #Override
9. public List<Connection> getConnections() {
10.
11.
12. state = cm.getState();
13. ringingCall = cm.getForegroundCalls();
14. System.out.println("**inside getConnections="+state);
15. System.out.println("**inside getConnections="+ringingCall);
16. if ( ringingCall == null) {
17.
18. System.out.println("**call is null***");
19. return emptyConnections;
20. }
21. else
22. {
23. System.out.println("**call is not null***");
24. return ((Call) ringingCall).getConnections();
}
}
#Override
public Phone getPhone() {
// TODO Auto-generated method stub
return null;
}
#Override
public void hangup() throws CallStateException {
// TODO Auto-generated method stub
}
#Override
public boolean isMultiparty() {
// TODO Auto-generated method stub
return false;
}
public Connection
getEarliestConnection() {
List l;
long time = Long.MAX_VALUE;
Connection c;
Connection earliest = null;
l = getConnections();
if (l == null) {
return null;
}else if ( l.size() == 0)
{
return null;
}
for (int i = 0, s = l.size() ; i < s ; i++) {
c = (Connection) l.get(i);
long t;
t = c.getCreateTime();
if (t < time) {
earliest = c;
time = t;
}
}
return earliest;
}
}
I called instance of CallManger Like this:
CallManager cm = CallManager.getInstance();
Bcoz this is a final modifier class. My another class is CallUpdate.java.
public class CallUpdate {
Call myCall = new MyCall();
Connection myConn = new MyConnection();
CallManager cm = CallManager.getInstance();
public Object getCallFailedString(){
myConn = myCall.getEarliestConnection();
System.out.println("myConn is ******"+myConn);
System.out.println("myCall is ******"+myCall);
if(myConn == null){
System.out.println("myConn is null ******");
return null;
}
else
{
Connection.DisconnectCause cause = myConn.getDisconnectCause();
System.out.println("myconn is not null ******"+cause);
}
}
I am getting myConn value is null. For this I added some piece of code in getConnection method of MyCall class to get a non-null value of myConn. i.e
state = cm.getState();
ringingCall = cm.getForegroundCalls();
System.out.println("**inside getConnections="+state);
System.out.println("**inside getConnections="+ringingCall);
if ( ringingCall == null) {
System.out.println("**call is null***");
return emptyConnections;
}
else
{
System.out.println("**call is not null***");
return ((Call) ringingCall).getConnections();
}
But it is throwing ClassCastException error on Line No:24 and on line
l = getConnections();.
And also I need at least one outgoing call to get a value of myConn. How to resolve this error?
Thx in advance.
ringingCall is a List<Call> - not a single call. You probably want something like:
if (ringingCall != null && !ringingCall.isEmpty()) {
Call call = ringingCall.get(0);
// Use call
}
... but you should also consider what you want to do if there's more than one call.
In general, if you find yourself casting that's because you think you know better than the compiler. It should always at least make you think - and in the case where you want a Call but you've got a List<Call>, the natural approach should be to use an element from the list.
It's not clear whether you really want to be subclassing Call in the first place, to be honest.

validation function problem

Hello
I am not able to get the correct validation.I think there is some error in this code so can anyone please help me solving this problem.
public static boolean validateFee(String value) {
boolean isvalid = true;
try {
int fee = 0;
if (value != null && !value.isEmpty()) {
fee = Integer.parseInt(value);
}
} catch (NumberFormatException ne) {
// ne.printStackTrace();
isvalid = false;
return isvalid;
}
return isvalid;
}
}
I am actaully using this code for validation of fee in which i m using a regex as [0-9]+.
This code i m using it in a common function.Actually validation call is done in the servlet as follows:
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
Boolean isvalid = true;
HashMap hashMap = new LinkedHashMap();
number = ApplicationConstants.FEE_PATTERN;
if (!Validation.validateFee(number)) {
isvalid = false;
hashMap.put("time", props.getText("error.fee.invalid.type"));
}
session.setAttribute("errorMessage", hashMap);
System.out.println("Map size " + hashMap.size());
logger.info("Exit validateTIme"); return isvalid;
}
I think there is no error in that but i have a doubt in this function.I am facing a problem like if i give number to the fee also its taking validation.please help me out
Currently it allows value of null or "" to count as being valid - is that deliberate?
Note that your current code can be rewritten more simply:
public static boolean validateFee(String value) {
try {
if (value != null && !value.isEmpty()) {
Integer.parseInt(value);
}
return true;
} catch (NumberFormatException ne) {
return false;
}
}
Now if you want null/empty to count as invalid, I'd rewrite it as:
public static boolean validateFee(String value) {
if (value == null || value.isEmpty()) {
return false;
}
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException ne) {
return false;
}
}
trim your string and then pass it to.
StringUtils.isNumeric(StringUtils.trimToNull(fees));
You can directly use StringUtils.isNumeric()
I recommend you use commons-lang StringUtils class, your validate method is re-written
public static boolean validateFee(String value) {
return StringUtils.isNumeric(StringUtils.trimToNull(value));
}
And you remove ApplicationConstants.FEE_PATTERN completely. The problem you are currently facing is that your servlet overwrites its input value with ApplicationConstants.FEE_PATTERN. Your servlet method is re-written
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
final Boolean valid = Validation.validateFee(number);
if (!valid) {
final HashMap hashMap = new LinkedHashMap();
hashMap.put("time", props.getText("error.fee.invalid.type"));
session.setAttribute("errorMessage", hashMap);
}
}

Categories

Resources