Here is my First Class AdminPostlCode. Contains some Strings and it's getters and Setters.
package org.sanket.zivameDataBase.adminPostalCode.model;
public class AdminPostalCode {
private String entity_id1;
private String postal_code1;
private String city1;
private String state1;
private String country1;
private String days_to_deliver1;
private String cod1;
private String pg1;
private String rpu1;
private String updated_by1;
private String updated_at1;
private String cod_couriername1;
private String pg_couriername1;
private String rto_couriername1;
public AdminPostalCode(){}
public AdminPostalCode(String entity_id1, String postal_code1,
String city1, String state1, String country1,
String days_to_deliver1, String cod1, String pg1, String rpu1,
String updated_by1, String updated_at1, String cod_couriername1,
String pg_couriername1, String rto_couriername1) {
super();
this.entity_id1 = entity_id1;
this.postal_code1 = postal_code1;
this.city1 = city1;
this.state1 = state1;
this.country1 = country1;
this.days_to_deliver1 = days_to_deliver1;
this.cod1 = cod1;
this.pg1 = pg1;
this.rpu1 = rpu1;
this.updated_by1 = updated_by1;
this.updated_at1 = updated_at1;
this.cod_couriername1 = cod_couriername1;
this.pg_couriername1 = pg_couriername1;
this.rto_couriername1 = rto_couriername1;
}
public String getEntity_id1() {
return entity_id1;
}
public void setEntity_id1(String entity_id1) {
this.entity_id1 = entity_id1;
}
public String getPostal_code1() {
return postal_code1;
}
public void setPostal_code1(String postal_code1) {
this.postal_code1 = postal_code1;
}
public String getCity1() {
return city1;
}
public void setCity1(String city1) {
this.city1 = city1;
}
public String getState1() {
return state1;
}
public void setState1(String state1) {
this.state1 = state1;
}
public String getCountry1() {
return country1;
}
public void setCountry1(String country1) {
this.country1 = country1;
}
public String getDays_to_deliver1() {
return days_to_deliver1;
}
public void setDays_to_deliver1(String days_to_deliver1) {
this.days_to_deliver1 = days_to_deliver1;
}
public String getCod1() {
return cod1;
}
public void setCod1(String cod1) {
this.cod1 = cod1;
}
public String getPg1() {
return pg1;
}
public void setPg1(String pg1) {
this.pg1 = pg1;
}
public String getRpu1() {
return rpu1;
}
public void setRpu1(String rpu1) {
this.rpu1 = rpu1;
}
public String getUpdated_by1() {
return updated_by1;
}
public void setUpdated_by1(String updated_by1) {
this.updated_by1 = updated_by1;
}
public String getUpdated_at1() {
return updated_at1;
}
public void setUpdated_at1(String updated_at1) {
this.updated_at1 = updated_at1;
}
public String getCod_couriername1() {
return cod_couriername1;
}
public void setCod_couriername1(String cod_couriername1) {
this.cod_couriername1 = cod_couriername1;
}
public String getPg_couriername1() {
return pg_couriername1;
}
public void setPg_couriername1(String pg_couriername1) {
this.pg_couriername1 = pg_couriername1;
}
public String getRto_couriername1() {
return rto_couriername1;
}
public void setRto_couriername1(String rto_couriername1) {
this.rto_couriername1 = rto_couriername1;
}
}
Here is My Database connection Class
package org.sanket.zivameDataBase.adminPostalCode.DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
public class DataBaseConnection {
public Connection getConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/zdb";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "root");
return connection;
} catch (Exception e)
{
throw e;
}
}
}
Here is my access class.
package org.sanket.zivameDataBase.adminPostalCode.DataBase;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.sanket.zivameDataBase.adminPostalCode.model.AdminPostalCode;
public class Access {
public List<AdminPostalCode> getAdminPostalCode(int code,Connection con) throws SQLException
{
List<AdminPostalCode> adminDetail = new ArrayList<AdminPostalCode>();
PreparedStatement stmt = con.prepareStatement("select * from admin_postalcode where postal_code ="+code+"");
ResultSet resultSet = stmt.executeQuery();
//System.out.println(resultSet);
try
{
while (resultSet.next())
{
AdminPostalCode adminPostalCode = new AdminPostalCode();
adminPostalCode.setEntity_id1(resultSet.getString("entity_id"));
adminPostalCode.setPostal_code1(resultSet.getString("postal_code"));
adminPostalCode.setCity1(resultSet.getString("city"));
adminPostalCode.setState1(resultSet.getString("state"));
adminPostalCode.setCountry1(resultSet.getString("country"));
adminPostalCode.setDays_to_deliver1(resultSet.getString("days_to_deliver"));
adminPostalCode.setCod1(resultSet.getString("cod"));
adminPostalCode.setPg1(resultSet.getString("pg"));
adminPostalCode.setRpu1(resultSet.getString("rpu"));
adminPostalCode.setUpdated_by1(resultSet.getString("updated_by"));
adminPostalCode.setUpdated_at1(resultSet.getString("updated_at"));
adminPostalCode.setCod_couriername1(resultSet.getString("cod_couriername"));
adminPostalCode.setPg_couriername1(resultSet.getString("pg_couriername"));
adminPostalCode.setRto_couriername1(resultSet.getString("rto_couriername"));
adminDetail.add(adminPostalCode);
}
}catch (SQLException e)
{
e.printStackTrace();
}
return adminDetail ;
}
}
Now I want to write JUnit test case for Above code. And I tried in following way. But it is not working Please Help me in writing JUnit Test case. Remaining Everything is working fine.
package adminPostalCode;
import static org.junit.Assert.*;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.sanket.zivameDataBase.adminPostalCode.DataBase.Access;
import org.sanket.zivameDataBase.adminPostalCode.DataBase.DataBaseConnection;
import org.sanket.zivameDataBase.adminPostalCode.model.AdminPostalCode;
public class SampleTest {
List<AdminPostalCode> detailsActual = new ArrayList<AdminPostalCode>();
List<AdminPostalCode> detailsExpected = new ArrayList<AdminPostalCode>();
boolean abc;
AdminPostalCode adminPoCo = new AdminPostalCode();
public SampleTest()
{
adminPoCo.setCity1("WEST CHAMPARAN");
adminPoCo.setCod1("0");
adminPoCo.setCod_couriername1("NO SERVICE");
adminPoCo.setDays_to_deliver1("11");
adminPoCo.setEntity_id1("19625");
adminPoCo.setPg1("1");
adminPoCo.setPg_couriername1("INDIA POST");
adminPoCo.setPostal_code1("845106");
adminPoCo.setRpu1("0");
adminPoCo.setRto_couriername1("NO SERVICE");
adminPoCo.setState1("BIHAR");
adminPoCo.setUpdated_by1("panindra#milastar.in");
adminPoCo.setUpdated_at1("2015-03-19 19:30:22.0");
adminPoCo.setCountry1("IN");
detailsExpected.add(adminPoCo);
}
#Test
public void test() throws Exception {
//fail("Not yet implemented");
DataBaseConnection db = new DataBaseConnection();
Connection con = db.getConnection();
Access access = new Access();
detailsActual =access.getAdminPostalCode(845106, con);
abc = (detailsActual.equals(detailsExpected)) ;
System.out.println(abc);
}
}
use assertXxx in junit instead of System.out. junit is used to automate your test and find potential problems in your code and provide useful information about them. junit will help much less if you use System.out.
if you use junit to write a unit test, you should not connect the 'real' database, you should use some mock framework such as mockito to mock an Access object.
if you want write integration test using junit, you should use some specific junit extension framework like dbunit.
You have to use assertEquals for testing
assertEquals(detailsActual,detailsExpected);
if you are comparing arrayList object, you have to convert them to array than you can use assertArrayEquals.
It seems what you are looking for is away to compare 2 objects of type ArrayList.
The answer to this is by overriding equals method.
Add the below code to your AdminPostalCode POJO class.
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final AdminPostalCode other = (AdminPostalCode) obj;
if (city1 == null) {
if (other.city1 != null)
return false;
} else if (!city1.equals(other.city1))
return false;
if (cod1 == null) {
if (other.cod1 != null)
return false;
} else if (!cod1.equals(other.cod1))
return false;
if (cod_couriername1 == null) {
if (other.cod_couriername1 != null)
return false;
} else if (!cod_couriername1.equals(other.cod_couriername1))
return false;
if (country1 == null) {
if (other.country1 != null)
return false;
} else if (!country1.equals(other.country1))
return false;
if (days_to_deliver1 == null) {
if (other.days_to_deliver1 != null)
return false;
} else if (!days_to_deliver1.equals(other.days_to_deliver1))
return false;
if (entity_id1 == null) {
if (other.entity_id1 != null)
return false;
} else if (!entity_id1.equals(other.entity_id1))
return false;
if (pg1 == null) {
if (other.pg1 != null)
return false;
} else if (!pg1.equals(other.pg1))
return false;
if (pg_couriername1 == null) {
if (other.pg_couriername1 != null)
return false;
} else if (!pg_couriername1.equals(other.pg_couriername1))
return false;
if (postal_code1 == null) {
if (other.postal_code1 != null)
return false;
} else if (!postal_code1.equals(other.postal_code1))
return false;
if (rpu1 == null) {
if (other.rpu1 != null)
return false;
} else if (!rpu1.equals(other.rpu1))
return false;
if (rto_couriername1 == null) {
if (other.rto_couriername1 != null)
return false;
} else if (!rto_couriername1.equals(other.rto_couriername1))
return false;
if (state1 == null) {
if (other.state1 != null)
return false;
} else if (!state1.equals(other.state1))
return false;
if (updated_at1 == null) {
if (other.updated_at1 != null)
return false;
} else if (!updated_at1.equals(other.updated_at1))
return false;
if (updated_by1 == null) {
if (other.updated_by1 != null)
return false;
} else if (!updated_by1.equals(other.updated_by1))
return false;
return true;
}
The above method will help you compare the 2 Actual and Expected objects.
Though, a correct JUnit will make use of assertEquals, verify, etc to validate results
Your AdminPostalCode class should implement boolean equals(Object other) and also int hashCode(). Implementing these methods will guarantee that custom objects, like your AdminPostalCode class, will be able to perform checks on certain fields. assertEquals(detailsActual, detailsExpected) f.e. invokes this method internally. By default equals(...) compares objects on their memory address instead of the content. That's why you should overwrite these two methods.
If you don't want to overwrite these methods (for whatever reason), you also have the possibility to implement custom Hamcrest matchers which will perform the equality check. You are then able to utilize this matcher like this: assertThat(detailsActual, containsAdminPostalCodes(detailsExpected)); where containsAdminPostalCodes(...) is your custom Hamcrest matcher which takes a List of AdminPostalCode as input. Inside this Hamcrest matcher you will need to compare the fields of the AdminPostalCode instances of the actual list with the one provided in the expected list.
Hamcrest comes already with quite a lot of matchers. So check if there are already any available that suits your need, though some may rely on a correct implementation of equals(...) and hashCode().
Also, as #walsh has correctly pointed out, you should not call a database in your unit-test directly but instead use mocked objects (Mockito, PowerMock, ...). If you write integration tests (our company f.e. prefers integration tests over unit-tests), try to refactor the initialization and tear-down code for your database into JUnit rules
Related
My application is Under VAPT report certification. in my application i wrote a code for detecting weather the device is root or not. the method is returning boolean values. but they Bypassed the code with Magisk or some other root application. How to disable the bypassing???? How????
public class DeviceUtils {
public static boolean isDeviceRooted() {
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3() || checkRootMethod4() || checkRootMethod5();
}
private static boolean checkRootMethod1() {
String buildTags = android.os.Build.TAGS;
return buildTags != null && buildTags.contains("test-keys");
}
private static boolean checkRootMethod2() {
String[] paths = { "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
"/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
for (String path : paths) {
if (new File(path).exists()) return true;
}
return false;
}
private static boolean checkRootMethod3() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[] { "/system/xbin/which", "su" });
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
if (in.readLine() != null) return true;
return false;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
private static boolean checkRootMethod4() {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
return false;
}
public static boolean findBinary(String binaryName)
{ boolean found = false;
if (!found) { String[] places = { "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/", "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/", "/system/app/Superuser.apk", "/sbin/su", "/sbin/su/", "/system/bin/su","/system/bin/su/", "/system/xbin/su", "/system/xbin/su/", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su", "/su/", "/data/local/xbin/", "/system/bin/.ext/", "/system/bin/failsafe/", "/system/sd/xbin/", "/su/xbin/", "/su/bin/", "/magisk/.core/bin/", "/system/usr/we-need-root/", "/system/xbin/", "/system/su","/system/bin/.ext/.su","/system/usr/we-need-root/su-backup", "/system/xbin/mu", "/system/su/","/system/bin/.ext/.su/","/system/usr/we-need-root/su-backup/", "/system/xbin/mu/"};
for (String where : places)
{
if (new File(where + binaryName).exists())
{
found = true;
break;
}
}
}
return found;
}
private static boolean checkRootMethod5()
{
return findBinary("su");
}
}
I am able to get the coverage for the second and the third condition but not able to get the coverage for the last and the first one.
#Override public boolean equals(Object obj)
{
if(this == obj) {
return true;
}
if(obj == null)
{
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
Rating other = (Rating) obj;
boolean bool= score == other.score ;
boolean bool2=Objects.equals(user, other.user);
return bool&&bool2;
}
the below one is my test function
public void equalsTest_lastcondition() {
Rating test=new Rating();
Object obj2=testwa2;
Rating other = (Rating) obj2;
boolean bool=false;
if(other.getScore()==testwa1.getScore())
{ bool=true;}
boolean bool2 =Objects.equals(test.getUser(), other.getUser());
assertEquals(true, bool && bool2);
}
this == obj is simple test.equals(test)
getClass() != obj.getClass() is test.equals("").
PS: You can use any object instead of String there.
#Test
void equalsTest() {
String score = 1;
String user = "user";
Rating rating = new Rating(score, user);
assertTrue(rating.equals(rating)); // 1. if statement
assertFalse(rating.equals(null)); // 2. if statement
assertFalse(rating.equals(score)); // 3. if statement
assertTrue(rating.equals(new Rating(score, user))); // other statements
}
Updated:
String score = 1;
String user = "user";
Rating rating = new Rating(score, user);
#Test
void equalsShouldReturnTrueWhenComparingTheSameInstance() {
assertTrue(rating.equals(rating)); // 1. if statement
}
#Test
void equalsShouldReturnFalseWhenComparingTheNullValue() {
assertFalse(rating.equals(null)); // 2. if statement
}
#Test
void equalsShouldReturnFalseWhenComparingTheWrongType() {
assertFalse(rating.equals(score)); // 3. if statement
}
#Test
void equalsShouldReturnTrueWhenComparingNewInstanceWithSameValues() {
assertTrue(rating.equals(new Rating(score, user))); // other statements
}
This code:
#Override
public List<FactCodeDto> getAllFactsWithoutParentsAsFactDto() {
String completeQuery = FactCodeQueries.SELECT_DTO_FROM_FACT_WITH_NO_PARENTS;
Query query = createHibernateQueryForUnmappedTypeFactDto(completeQuery);
List<FactCodeDto> factDtoList = query.list(); //line 133
return factDtoList;
}
calling this method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
gives me a ClassCastException -> part of the trace:
Caused by: java.lang.ClassCastException: org.bamboomy.cjr.dto.FactCodeDto cannot be cast to java.util.Map
at org.hibernate.property.access.internal.PropertyAccessMapImpl$SetterImpl.set(PropertyAccessMapImpl.java:102)
at org.hibernate.transform.AliasToBeanResultTransformer.transformTuple(AliasToBeanResultTransformer.java:78)
at org.hibernate.hql.internal.HolderInstantiator.instantiate(HolderInstantiator.java:75)
at org.hibernate.loader.custom.CustomLoader.getResultList(CustomLoader.java:435)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
at org.hibernate.loader.Loader.list(Loader.java:2418)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1898)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:318)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at org.bamboomy.cjr.dao.factcode.FactCodeDAOImpl.getAllFactsWithoutParentsAsFactDto(FactCodeDAOImpl.java:133)
Which is pretty strange because, indeed, if you look up the source code of Hibernate it tries to do this:
#Override
#SuppressWarnings("unchecked")
public void set(Object target, Object value, SessionFactoryImplementor factory) {
( (Map) target ).put( propertyName, value ); //line 102
}
Which doesn't make any sense...
target is of type Class and this code tries to cast it to Map,
why does it try to do that???
any pointers are more than welcome...
I'm using Hibernate 5 (and am upgrading from 3)...
edit: I also use Spring (4.2.1.RELEASE; also upgrading) which calls these methods upon deploy, any debugging pointers are most welcome as well...
edit 2: (the whole FactCodeDto class, as requested)
package org.bamboomy.cjr.dto;
import org.bamboomy.cjr.model.FactCode;
import org.bamboomy.cjr.model.FactCodeType;
import org.bamboomy.cjr.utility.FullDateUtil;
import org.bamboomy.cjr.utility.Locales;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.util.Assert;
import java.util.*;
#Getter
#Setter
#ToString
public class FactCodeDto extends TreeNodeValue {
private String cdFact;
private String cdFactSuffix;
private Boolean isSupplementCode;
private Boolean isTitleCode;
private Boolean mustBeFollowed;
private Date activeFrom;
private Date activeTo;
private Boolean isCode;
private Long idFact;
private Long idParent;
private String type;
Map<Locale, String> description = new HashMap<Locale, String>(3);
public FactCodeDto() {
}
public FactCodeDto(String prefix, String suffix) {
super();
this.cdFact = prefix;
this.cdFactSuffix = suffix;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
}
public FactCodeDto(String cdFact, String cdFactSuffix, Boolean isSupplementCode, Boolean mustBeFollowed, Long idFact, Long idParent, Boolean isCode, Boolean isTitleCode, Date from, Date to, Map<Locale, String> descriptions,String type) {
super();
this.cdFact = cdFact;
this.cdFactSuffix = cdFactSuffix;
this.isSupplementCode = isSupplementCode;
this.mustBeFollowed = mustBeFollowed;
this.idFact = idFact;
this.idParent = idParent;
this.isCode = isCode;
this.isTitleCode = isTitleCode;
this.activeFrom = from;
this.activeTo = to;
if (descriptions != null) {
this.description = descriptions;
}
this.type = type;
}
public FactCodeDto(FactCode fc) {
this(fc.getPrefix(), fc.getSuffix(), fc.isSupplementCode(), fc.isHasMandatorySupplCodes(), fc.getId(), fc.getParent(), fc.isActualCode(), fc.isTitleCode(), fc.getActiveFrom(), fc.getActiveTo(), fc.getAllDesc(),fc.getType().getCode());
}
public String formatCode() {
return FactCode.formatCode(cdFact, cdFactSuffix);
}
public boolean isActive() {
Date now = new Date(System.currentTimeMillis());
return FullDateUtil.isBetweenDates(now, this.activeFrom, this.activeTo);
}
public void setDescFr(String s) {
description.put(Locales.FRENCH, s);
}
public void setDescNl(String s) {
description.put(Locales.DUTCH, s);
}
public void setDescDe(String s) {
description.put(Locales.GERMAN, s);
}
/**
* public String toString() {
* StringBuilder sb = new StringBuilder();
* sb.append(getIdFact() + ": ")
* .append(getIdParent() + ": ")
* .append(" " + cdFact + cdFactSuffix + ": " + (isSupplementCode ? "NO Principal " : " Principal "))
* .append((mustBeFollowed ? " Must Be Followed " : "NOT Must Be Followed "));
* return sb.toString();
* }
*/
public Map<Locale, String> getDescription() {
return description;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
String fullCode = formatCode();
result = prime * result + ((fullCode == null) ? 0 : fullCode.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;
}
FactCodeDto other = (FactCodeDto) obj;
return formatCode().equals(other.formatCode());
}
#Override
public boolean isChildOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isChild = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isChild = this.getIdParent().equals(((FactCodeDto) value).getIdFact());
}
}
return isChild;
}
#Override
public boolean isBrotherOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isBrother = false;
if (value instanceof FactCodeDto) {
if (this.getIdParent() != null) {
isBrother = this.getIdParent().equals(((FactCodeDto) value).getIdParent());
}
}
return isBrother;
}
#Override
public boolean isParentOf(TreeNodeValue value) {
Assert.notNull(value);
boolean isParent = false;
if (value instanceof FactCodeDto) {
isParent = this.getIdFact().equals(((FactCodeDto) value).getIdParent());
}
return isParent;
}
#Override
public int compareTo(TreeNodeValue to) {
if (to instanceof FactCodeDto) {
return formatCode().compareTo(((FactCodeDto) to).formatCode());
} else return 1;
}
public String getCode() {
return formatCode();
}
}
I found that AliasToBean has changed in Hibernate 5. For me adding getter for my field fixed the problem.
This exception occurs when the setters and getters are not mapped correctly to the column names.
Make sure you have the correct getters and setters for the query(Correct names and correct datatypes).
Read more about it here:
http://javahonk.com/java-lang-classcastexception-com-wfs-otc-datamodels-imagineexpirymodel-cannot-cast-java-util-map/
I do some investigation on this question. The problem is that Hibernate converts aliases for column names to upper case — cdFact becomesCDFACT.
Read for a more deeply explanation and workaround here:
mapping Hibernate query results to custom class?
In the end it wasn't so hard to find a solution,
I just created my own (custom) ResultTransformer and specified that in the setResultTransformer method:
private Query createHibernateQueryForUnmappedTypeFactDto(String sqlQuery) throws HibernateException {
return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(new FactCodeDtoResultTransformer());
//return FactCodeQueries.addScalars(createSQLQuery(sqlQuery)).setResultTransformer(Transformers.aliasToBean(FactCodeDto.class));
}
the code of the custom result transformer:
package org.bamboomy.cjr.dao.factcode;
import org.bamboomy.cjr.dto.FactCodeDto;
import java.util.Date;
import java.util.List;
/**
* Created by a162299 on 3-11-2015.
*/
public class FactCodeDtoResultTransformer implements org.hibernate.transform.ResultTransformer {
#Override
public Object transformTuple(Object[] objects, String[] strings) {
FactCodeDto result = new FactCodeDto();
for (int i = 0; i < objects.length; i++) {
setField(result, strings[i], objects[i]);
}
return result;
}
private void setField(FactCodeDto result, String string, Object object) {
if (string.equalsIgnoreCase("cdFact")) {
result.setCdFact((String) object);
} else if (string.equalsIgnoreCase("cdFactSuffix")) {
result.setCdFactSuffix((String) object);
} else if (string.equalsIgnoreCase("isSupplementCode")) {
result.setIsSupplementCode((Boolean) object);
} else if (string.equalsIgnoreCase("isTitleCode")) {
result.setIsTitleCode((Boolean) object);
} else if (string.equalsIgnoreCase("mustBeFollowed")) {
result.setMustBeFollowed((Boolean) object);
} else if (string.equalsIgnoreCase("activeFrom")) {
result.setActiveFrom((Date) object);
} else if (string.equalsIgnoreCase("activeTo")) {
result.setActiveTo((Date) object);
} else if (string.equalsIgnoreCase("descFr")) {
result.setDescFr((String) object);
} else if (string.equalsIgnoreCase("descNl")) {
result.setDescNl((String) object);
} else if (string.equalsIgnoreCase("descDe")) {
result.setDescDe((String) object);
} else if (string.equalsIgnoreCase("type")) {
result.setType((String) object);
} else if (string.equalsIgnoreCase("idFact")) {
result.setIdFact((Long) object);
} else if (string.equalsIgnoreCase("idParent")) {
result.setIdParent((Long) object);
} else if (string.equalsIgnoreCase("isCode")) {
result.setIsCode((Boolean) object);
} else {
throw new RuntimeException("unknown field");
}
}
#Override
public List transformList(List list) {
return list;
}
}
in hibernate 3 you could set Aliasses to queries but you can't do that anymore in hibernate 5 (correct me if I'm wrong) hence the aliasToBean is something you only can use when actually using aliasses; which I didn't, hence the exception.
Im my case :
=> write sql query and try to map result to Class List
=> Use "Transformers.aliasToBean"
=> get Error "cannot be cast to java.util.Map"
Solution :
=> just put \" before and after query aliases
ex:
"select first_name as \"firstName\" from test"
The problem is that Hibernate converts aliases for column names to upper case or lower case
I solved it by defining my own custom transformer as given below -
import org.hibernate.transform.BasicTransformerAdapter;
public class FluentHibernateResultTransformer extends BasicTransformerAdapter {
private static final long serialVersionUID = 6825154815776629666L;
private final Class<?> resultClass;
private NestedSetter[] setters;
public FluentHibernateResultTransformer(Class<?> resultClass) {
this.resultClass = resultClass;
}
#Override
public Object transformTuple(Object[] tuple, String[] aliases) {
createCachedSetters(resultClass, aliases);
Object result = ClassUtils.newInstance(resultClass);
for (int i = 0; i < aliases.length; i++) {
setters[i].set(result, tuple[i]);
}
return result;
}
private void createCachedSetters(Class<?> resultClass, String[] aliases) {
if (setters == null) {
setters = createSetters(resultClass, aliases);
}
}
private static NestedSetter[] createSetters(Class<?> resultClass, String[] aliases) {
NestedSetter[] result = new NestedSetter[aliases.length];
for (int i = 0; i < aliases.length; i++) {
result[i] = NestedSetter.create(resultClass, aliases[i]);
}
return result;
}
}
And used this way inside the repository method -
#Override
public List<WalletVO> getWalletRelatedData(WalletRequest walletRequest,
Set<String> requiredVariablesSet) throws GenericBusinessException {
String query = getWalletQuery(requiredVariablesSet);
try {
if (query != null && !query.isEmpty()) {
SQLQuery sqlQuery = mEntityManager.unwrap(Session.class).createSQLQuery(query);
return sqlQuery.setResultTransformer(new FluentHibernateResultTransformer(WalletVO.class))
.list();
}
} catch (Exception ex) {
exceptionThrower.throwDatabaseException(null, false);
}
return Collections.emptyList();
}
It worked perfectly !!!
Try putting Column names and field names both in capital letters.
This exception occurs when the class that you specified in the AliasToBeanResultTransformer does not have getter for the corresponding columns. Although the exception details from the hibernate are misleading.
I am trying to test a controller of mine which returns me a List of Objects on the get method to populate a dropdown on my page.
I am trying to write a JUnit test using MockMvc and Hamcrest to test the same.
I want to compare the List of objects and test if it fails or not.
I have created a static List of objects in my Test.java and I am getting a List of objects from the model.attribute method.
To Test: if both the List of Objects are equal and don't contain any other objects.
My object is called Option which has 3 properties. Key, Value and Selected. I have to check if the all the keys exists in the List or not.
I am unable to create a matcher to do the same. I am trying to create a matcher to compare my List.
So far I have done the following:
#Before
public void setup() throws Exception {
// This would build a MockMvc with only the following controller
this.mockMvc = MockMvcBuilders.standaloneSetup(openAccountController)
.build();
}
#Test
public void testOpenAccount() {
try {
setAllLegislations();
this.mockMvc
.perform(get("/open_account.htm"))
// This method is used to print out the actual httprequest
// and httpresponse on the console.
.andDo(print())
// Checking if status is 200
.andExpect(status().isOk())
.andExpect(
model().attributeExists("appFormAccountPlans",
"appFormLiraLegislations",
"appFormLrspLegislations",
"appFormRlspLegislations"))
.andExpect(
model().attribute("appFormAccountPlans", hasSize(5)))
.andExpect(
model().attribute("appFormLiraLegislations",
hasSize(8)))
.andExpect(
model().attribute("appFormLrspLegislations",
hasSize(2)))
.andExpect(
model().attribute("appFormRlspLegislations",
hasSize(1)))
.andExpect(
model().attribute(
"appFormLiraLegislations",
hasKeyFeatureMatcher(getLiraLegislations(allLegislations))));
private Matcher<List<Option>> hasKeyFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "was") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (actualOptions.size() == expectedOptions.size()) {
for (Option expectedOption : expectedOptions) {
for (Option actualOption : actualOptions) {
if (expectedOption.getKey().equals(
actualOption.getKey())) {
flag = true;
} else {
flag = false;
break;
}
}
}
}
if (flag)
return actualOptions;
else
return null;
}
};
}
private List<Option> getLiraLegislations(List<Option> legislation) {
List<Option> liraLegislations = new ArrayList<Option>();
Iterator<Option> iterator = legislation.iterator();
while (iterator.hasNext()) {
Option option = iterator.next();
if (LIRA_LEGISLATIONS.contains(option.getKey())) {
liraLegislations.add(option);
}
}
return liraLegislations;
}
private List<Option> allLegislations;
public List<Option> getAllLegislations() {
return allLegislations;
}
public void setAllLegislations() {
allLegislations = new ArrayList<Option>();
for (String key : ALL_LEGISLATIONS) {
Option option = new Option();
option.setKey(key);
allLegislations.add(option);
}
}
private static final Set<String> ALL_LEGISLATIONS = new HashSet<String>(
Arrays.asList(AccountLegislationEnum.AB.toString(),
AccountLegislationEnum.MB.toString(),
AccountLegislationEnum.NB.toString(),
AccountLegislationEnum.NL.toString(),
AccountLegislationEnum.NS.toString(),
AccountLegislationEnum.ON.toString(),
AccountLegislationEnum.QC.toString(),
AccountLegislationEnum.SK.toString(),
AccountLegislationEnum.BC.toString(),
AccountLegislationEnum.FE.toString(),
AccountLegislationEnum.NT.toString(),
AccountLegislationEnum.PE.toString(),
AccountLegislationEnum.YT.toString(),
AccountLegislationEnum.NU.toString(),
AccountLegislationEnum.UNKNOWN.toString()));
This is how I am getting my model attribute as:
Attribute = appFormLiraLegislations
value = [com.abc.arch.core.gui.eform.gui.Option#199d1739, com.abc.arch.core.gui.eform.gui.Option#185fac52, com.abc.arch.core.gui.eform.gui.Option#312a47fe, com.abc.arch.core.gui.eform.gui.Option#4edc8de9, com.abc.arch.core.gui.eform.gui.Option#71e8e471, com.abc.arch.core.gui.eform.gui.Option#70edf123, com.abc.arch.core.gui.eform.gui.Option#15726ac1, com.abc.arch.core.gui.eform.gui.Option#abeafe7]
Thanks in advance.
You can make your life definitely easier when you correctly implement Option object hashCode() and equals() methods using key attribute; then you can simply write:
model().attribute("appFormLiraLegislations",getLiraLegislations(allLegislations)))
and rely on list1.equals(list2) method to do the work for you.
Option hashCode and equals implementation:
public class Option {
private String key;
private String label;
...
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.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;
Option other = (Option) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
return true;
}
}
Methods above are generated by my IDE. I also don't know exactly what is structure of your Option class, so I add label property for example in addition to key property.
I created a custom Hamcrest matcher to compare the List of Option by checking the size and the keys.
private Matcher<List<Option>> hasOptionsFeatureMatcher(
final List<Option> expectedOptions) {
return new FeatureMatcher<List<Option>, List<Option>>(
equalTo(expectedOptions), "Options are", "Options were") {
#Override
protected List<Option> featureValueOf(List<Option> actualOptions) {
boolean flag = false;
if (expectedOptions.size() == actualOptions.size()) {
for (Option expected : expectedOptions) {
for (Option actual : actualOptions) {
if (expected.getKey().equals(actual.getKey())) {
flag = true;
break;
} else {
flag = false;
}
}
}
} else
flag = false;
if (flag)
return expectedOptions;
else
return null;
}
};
Implementation would be as follows:
private static final ImmutableBiMap<String, String> LIRA = new ImmutableBiMap.Builder<String, String>()
.put(AccountLegislationEnum.AB.toString(), "ALBERTA")
.put(AccountLegislationEnum.MB.toString(), "MANITTOBA")
.put(AccountLegislationEnum.NB.toString(), "NEW BRUNSWICK")
.put(AccountLegislationEnum.NL.toString(), "NEWFOUNDLAND")
.put(AccountLegislationEnum.NS.toString(), "NOVA SCOTIA")
.put(AccountLegislationEnum.ON.toString(), "ONTARIO")
.put(AccountLegislationEnum.QC.toString(), "QUEBEC")
.put(AccountLegislationEnum.SK.toString(), "SASKATCHEWAN")
.put(AccountLegislationEnum.UNKNOWN.toString(), "UNKNOWN").build();
private List<Option> prepareOptions(ImmutableBiMap<String, String> map) {
List<Option> legislations = new ArrayList<Option>();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
Option option = new Option();
option.setKey(key);
option.setValue(value);
legislations.add(option);
}
return legislations;
}
.andExpect(model().attribute("appFormLiraLegislations",hasOptionsFeatureMatcher(prepareOptions(LIRA))))
I need to create a class library which enables me to read different files (.dat-files with different data representations inside them) and create objects with their content (for every line one object).
I also have to create a unit test which starts the reading of the file, so I dont have to read to whole file first and save the content in an array. I want to use the factory pattern.
Here is my implementation of the class that implements the Iterator-Interface
package klassenbibliothek;
public class MyReader implements Iterator<Object>
{
BufferedReader reader;
MyReader(BufferedReader myReader)
{
reader = myReader;
}
#Override
public boolean hasNext() // aus Stackoverflow, von mir abgeändert
{
try {
return reader.ready();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
throw new NoSuchElementException();
}
}
#Override
public String next()
{
//return SubstancesFileObjectCreator(reader.readLine());
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
// return null;
throw new NoSuchElementException();
}
}
}
My question is: why do I get this error message "finally block does not complete normally"? I am not returning something, I am just throwing an exception.
I want to use the methods hasNext() and next() in my unit test, so that the unit test can controll when it starts to read the file. The unit test is in a different package.
Here are my other classes:
class AbstractFileObjectCreator
package klassenbibliothek;
public abstract class AbstractFileObjectCreator
{
public abstract AbstractFileObject createFileObject(String line);
}
class SubstancesFileObjectCreator
package klassenbibliothek;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SubstancesFileObjectCreator extends AbstractFileObjectCreator
{
MyReader myReader;
public void makeReader() throws IOException
{
String dataFileName = "C:/temp/Substances.dat";
BufferedReader bReader = new BufferedReader(new FileReader(dataFileName));
myReader = new MyReader(bReader);
}
#SuppressWarnings("null")
public AbstractFileObject createFileObject(String line)
{
AbstractFileObject mySubstance = null;
String lineValues[] = myReader.next().split("\t");
if(lineValues[0].equals("R"))
{
boolean dutyToDeclare_local;
boolean isUnwanted_local;
boolean isProhibited_local;
boolean isReach_local;
boolean isDeleted_local;
boolean isHidden_local;
String nodeidRaw = lineValues[1];
float nodeid = Float.parseFloat(nodeidRaw);
String casNrRaw = lineValues[2];
String euIndexCodeRaw = lineValues[3];
String einecsCodeRaw = lineValues[4];
String dutyToDeclareRaw = lineValues[5];
if(dutyToDeclareRaw.equals(1))
{
dutyToDeclare_local = true;
}
else
{
dutyToDeclare_local = false;
}
String isUnwantedRaw = lineValues[6];
if(isUnwantedRaw.equals("1"))
{
isUnwanted_local = true;
}
else
{
isUnwanted_local = false;
}
String isProhibitedRaw = lineValues[7];
if(isProhibitedRaw.equals("1"))
{
isProhibited_local = true;
}
else
{
isProhibited_local = false;
}
String isReachRaw = lineValues[8];
if(isReachRaw.equals("1"))
{
isReach_local = true;
}
else
{
isReach_local = false;
}
String isDeletedRaw = lineValues[9];
if(isDeletedRaw.equals("1"))
{
isDeleted_local = true;
}
else
{
isDeleted_local = false;
}
String isHiddenRaw = lineValues[10];
if(isHiddenRaw.equals("1"))
{
isHidden_local = true;
}
else
{
isHidden_local = false;
}
mySubstance = new Substance(nodeid, casNrRaw, euIndexCodeRaw, einecsCodeRaw, dutyToDeclare_local, isUnwanted_local, isProhibited_local, isReach_local, isDeleted_local, isHidden_local);
// und weiter...
}
else
{
String languageCode = lineValues[1];
String name = lineValues[2];
// Synonym-Objekt erzeugen und zu Substance-Objekt hinzufügen
Synonym newSynonym = new Synonym(languageCode, name);
mySubstance.addAppendix(newSynonym);
while(myReader.hasNext())
{
String lineValues_synonyms[] = myReader.next().split("\t");
String lineValuesZero = lineValues_synonyms[0];
if(lineValuesZero.equals("R"))
{
break; // nicht so gut glaube ich!!!
}
String languageCode_next = lineValues_synonyms[1];
String name_next = lineValues_synonyms[2];
Synonym newSynonym_next = new Synonym(languageCode_next, name_next);
mySubstance.addAppendix(newSynonym_next);
}
}
return mySubstance;
}
}
class AbstractFileObject
package klassenbibliothek;
public abstract class AbstractFileObject
{
boolean isDeleted;
public AbstractFileObject(boolean isDeleted)
{
this.isDeleted = isDeleted;
}
public boolean getIsDeleted()
{
return isDeleted;
}
public abstract void addAppendix(Object newAppendix);
}
class Substance
public class Substance extends AbstractFileObject
{
private float nodeid;
private String casNr;
private String euIndexCode;
private String einecsCode;
private boolean dutyToDeclare;
private boolean isUnwanted;
private boolean isProhibited;
private boolean isReach;
private boolean isDeleted;
private boolean isHidden;
private ArrayList<Synonym> synonymList;
public Substance(float nodeid, String casNr, String euIndexCode, String einecsCode,
boolean dutyToDeclare, boolean isUnwanted, boolean isProhibited, boolean isReach,
boolean isDeleted, boolean isHidden)
{
super(isDeleted);
this.nodeid = nodeid;
this.casNr = casNr;
this.euIndexCode = euIndexCode;
this.einecsCode = einecsCode;
this.dutyToDeclare = dutyToDeclare;
this.isUnwanted = isUnwanted;
this.isProhibited = isProhibited;
this.isReach = isReach;
//this.isDeleted = isDeleted;
this.isHidden = isHidden;
}
// getter and setter
}
class Synonym
package klassenbibliothek;
public class Synonym
{
private String languageCode;
private String name;
public Synonym(String languageCode, String name)
{
this.languageCode = languageCode;
this.name = name;
}
public String getLanguageCode()
{
return languageCode;
}
public String getName()
{
return name;
}
}
unit test
package klassenbibliothek.test;
import static org.junit.Assert.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class SubstancesTest {
#Test
public void test() {
//fail("Not yet implemented");
long startTimeNanos = System.nanoTime();
/*
* While... iterator over data file
*/
}
}
Am I using the factory pattern in the right way? I'm very confused.
A finally block always executes if there is a try-block before it. So yours always throws a NoSuchElementException().
finally
{
// return null;
throw new NoSuchElementException();
}
You should do something in it and not throw an Exception.
Finally blocks are for cleanup. They should not specifically throw exceptions like that. Move the exception throwing out of the finally block.
Remove the throw exception from the finally block and put it in catch block or some other place. Finally block is to release resources that you might be using in your program.