How to dynamic cast an object from a parameter input - casting

I've a class Employee here
public class Employee
{
property1;
property2;
property3;
property4;
}
and class EmployeeEntity
public class EmployeeEntity
{
property1;
property2;
property5;
property6;
}
2 these class don't inherit from another one class
I have the service like this
EmployeeService
public Employee getEmployee(Long employeeId)
{
Employee employee = new Employee();
EmployeeInDatabase employeeInDatabase = employeeDao.findEmployeeById(employeeId);
employee.setProperty1(employeeInDatabase .getProperty1());
employee.setProperty2(employeeInDatabase .getProperty2());
employee.setProperty3(employeeInDatabase .getProperty3());
employee.setProperty4(employeeInDatabase .getProperty4());
return employee;
}
public EmployeeEntity getEmployee(Long employeeId)
{
EmployeeEntity employeeEntity = new EmployeeEntity();
EmployeeInDatabase employeeInDatabase = employeeDao.findEmployeeById(employeeId);
employeeEntity .setProperty1(employeeInDatabase .getProperty1());
employeeEntity .setProperty2(employeeInDatabase .getProperty2());
employeeEntity .setProperty5(employeeInDatabase .getProperty5());
employeeEntity .setProperty6(employeeInDatabase .getProperty6());
return employeeEntity;
}
As you see that I have many dupplicated implementation for setProperty1(), setProperty2()
How could I try by this way?
EmployeeConverter
public Object setProperty1AndProperty2(Object employee, EmployeeInDatabase employeeInDatabase)
{
Object response;
if(employee instanceof Employee)
{
response = (Employee) employee;
}
if(employee instanceof EmployeeInDatabase)
{
response = (EmployeeInDatabase) employee;
}
response.setPropery1(employee.getProperty1());
response.setPropery2(employee.getProperty2());
}
From there we could use setProperty1AndProperty2 with 2 object Employee, EmployeeEntity.
Is there anyone have some solution? Thanks :)

Related

Validation of the application resource model has failed during application initialization

I'm trying to create a simple get request using jersey
but got exception
can someone tell me where I got it wrong?
The excption is - "Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
"
VersionResource.java
#Path("/versions")
public class VersionResource extends BaseResource<VersionDao, VersionTable>
{
public VersionResource(VersionDao objectDao)
{
super(objectDao);
}
#Override
#Path("/getAppVersions")
#GET
#UnitOfWork
public String getAllRecords(#Context HttpServletRequest req, #QueryParam("callback") String callback) throws JsonProcessingException
{
return super.getAllRecords(req, callback);
}
}
VersionTable.java
#Entity(name = "Versions")
#Table(name = "Versions")
#NamedQueries({ #NamedQuery(name = QueryNames.QUERY_VERSION_GET_ALL, query = "select c from Versions c"), })
public class VersionTable extends baseDataBase implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "VersionId")
private short versionId;
#Column(name = "VersionPlatform")
#JsonProperty
#NotEmpty
private String versionPlatform;
#Column(name = "VersionNumber")
#JsonProperty
#NotEmpty
private String versionNumber;
#Column(name = "VersionDescription")
#JsonProperty
#NotEmpty
private String versionDescription;
public short getVersionId()
{
return versionId;
}
public void setVersionId(short versionId)
{
this.versionId = versionId;
}
public String VersionPlatformEnum()
{
return versionPlatform;
}
public void setVersionPlatform(String versionPlatform)
{
this.versionPlatform = versionPlatform;
}
public String getVersionNumber()
{
return versionNumber;
}
public void setVersionNumber(String versionNumber)
{
this.versionNumber = versionNumber;
}
public String getVersionDescription()
{
return versionDescription;
}
public void setVersionDescription(String versionDescription)
{
this.versionDescription = versionDescription;
}
}
VersionDao.java
public class VersionDao extends baseAbstractDao<VersionTable> implements IDatabaseActions<VersionTable>
{
public VersionDao(SessionFactory sessionFactory)
{
super(sessionFactory);
}
#Override
public ObjectDaoResponse getAllTableRecords() throws JsonProcessingException
{
List<VersionTable> list = list(namedQuery(QueryNames.QUERY_VERSION_GET_ALL));
return ObjectDaoResponse.getAnOkResponse(list);
}
}
I think you need a no arg constructor for your VersionResource class, but if you really need an argument the value should be passed by injection (see: https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/jaxrs-resources.html#d0e2692)

spring-data-neo4j: Can't create two relationship properties with same label

Using spring-data-neo4j, I am not able to set up two relationship properties in the same class with the same label.
The following code can be found in my branch https://github.com/spencerhrob/gs-accessing-data-neo4j/tree/same-name-relationships.
Person.java:
#NodeEntity
public class Person {
#GraphId Long id;
public String name;
public Person() {}
public Person(String name) { this.name = name; }
#RelatedTo(type="MEMBER_OF", direction=Direction.OUTGOING)
Dojo dojo;
#RelatedTo(type="MEMBER_OF", direction=Direction.OUTGOING)
MailingList mailingList;
public void setDojo(Dojo dojo) {
this.dojo = dojo;
}
public void setMailingList(MailingList mailingList) {
this.mailingList = mailingList;
}
#Override
public String toString() {
return "Person [name=" + name + "]";
}
}
Dojo.java:
#NodeEntity
public class Dojo {
#GraphId Long id;
public String name;
public Dojo() { }
public Dojo(String name) { this.name = name; }
#Override
public String toString() {
return "Dojo [name=" + name + "]";
}
}
MailingList.java:
#NodeEntity
public class MailingList {
#GraphId Long id;
public String name;
public MailingList() { }
public MailingList(String name) { this.name = name; }
#Override
public String toString() {
return "MailingList [name=" + name + "]";
}
}
Application.java:
#Configuration
#EnableNeo4jRepositories(basePackages = "hello")
public class Application extends Neo4jConfiguration implements CommandLineRunner {
public Application() {
setBasePackage("hello");
}
#Bean
GraphDatabaseService graphDatabaseService() {
return new GraphDatabaseFactory().newEmbeddedDatabase("accessingdataneo4j.db");
}
#Autowired
PersonRepository personRepository;
#Autowired
GraphDatabase graphDatabase;
public void run(String... args) throws Exception {
Transaction tx = graphDatabase.beginTx();
try {
Person linus = new Person("Linus");
linus.setDojo(new Dojo("Coding Dojo"));
linus.setMailingList(new MailingList("Kernel Mailing List"));
personRepository.save(linus);
tx.success();
} finally {
tx.close();
}
}
public static void main(String[] args) throws Exception {
FileUtils.deleteRecursively(new File("accessingdataneo4j.db"));
SpringApplication.run(Application.class, args);
}
}
When I run this code, I get the following exception:
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at
org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:680)
at
org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:695)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:952)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:941)
at hello.Application.main(Application.java:56) Caused by:
org.springframework.data.mapping.model.MappingException: Setting
property mailingList to Dojo [name=null] on Person [name=Linus] at
org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.setProperty(SourceStateTransmitter.java:85)
at
org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyEntityStatePropertyValue(SourceStateTransmitter.java:91)
at
org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.access$000(SourceStateTransmitter.java:40)
at
org.springframework.data.neo4j.support.mapping.SourceStateTransmitter$2.doWithAssociation(SourceStateTransmitter.java:61)
at
org.springframework.data.mapping.model.BasicPersistentEntity.doWithAssociations(BasicPersistentEntity.java:324)
at
org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.copyPropertiesFrom(SourceStateTransmitter.java:57)
at
org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.loadEntity(Neo4jEntityConverterImpl.java:112)
at
org.springframework.data.neo4j.support.mapping.Neo4jEntityConverterImpl.read(Neo4jEntityConverterImpl.java:104)
at
org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister$CachedConverter.read(Neo4jEntityPersister.java:170)
at
org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.createEntityFromState(Neo4jEntityPersister.java:189)
at
org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:244)
at
org.springframework.data.neo4j.support.mapping.Neo4jEntityPersister.persist(Neo4jEntityPersister.java:231)
at
org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:356)
at
org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:350)
at
org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405)
at
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390)
at
org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy43.save(Unknown Source) at
hello.Application.run(Application.java:44) at
org.springframework.boot.SpringApplication.runCommandLineRunners(SpringApplication.java:677)
... 5 common frames omitted Caused by:
org.springframework.core.convert.ConverterNotFoundException: No
converter found capable of converting from type hello.Dojo to type
hello.MailingList at
org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:291)
at
org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:177)
at
org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:158)
at
org.springframework.data.mapping.model.BeanWrapper.getPotentiallyConvertedValue(BeanWrapper.java:155)
at
org.springframework.data.mapping.model.BeanWrapper.setProperty(BeanWrapper.java:75)
at
org.springframework.data.neo4j.support.mapping.SourceStateTransmitter.setProperty(SourceStateTransmitter.java:83)
... 37 common frames omitted
There's a lot there but the real error is that Spring is trying to convert a Dojo into a MailingList.
Meanwhile, this code works if I name the relationships with different names (as in my branch https://github.com/spencerhrob/gs-accessing-data-neo4j/tree/different-name-relationships). Person.java:
#NodeEntity
public class Person {
#GraphId Long id;
public String name;
public Person() {}
public Person(String name) { this.name = name; }
#RelatedTo(type="MEMBER_OF_DOJO", direction=Direction.OUTGOING)
Dojo dojo;
#RelatedTo(type="MEMBER_OF_LIST", direction=Direction.OUTGOING)
MailingList mailingList;
public void setDojo(Dojo dojo) {
this.dojo = dojo;
}
public void setMailingList(MailingList mailingList) {
this.mailingList = mailingList;
}
#Override
public String toString() {
return "Person [name=" + name + "]";
}
}
Without any changes to Application.java (or to Dojo.java or MailingList.java), this code executes successfully.
My understanding from this example is that spring-data-neo4j will not allow a class to have two properties that have the same label. In certain cases different relationships need to have the same label--for example, to conform to modeling standards. Is it possible to set up more than one relationship with the same name in spring-data-neo4j? If so, how?
I've found the answer to this question. What I was looking for is the "enforceTargetType" attribute as described in the documentation.
I've made a branch of the repository that uses this fix. It is found at https://github.com/spencerhrob/gs-accessing-data-neo4j/tree/same-name-enforce-target.
Person.java:
#NodeEntity
public class Person {
#GraphId Long id;
public String name;
public Person() {}
public Person(String name) { this.name = name; }
#RelatedTo(type="MEMBER_OF", direction=Direction.OUTGOING, enforceTargetType=true)
Dojo dojo;
#RelatedTo(type="MEMBER_OF", direction=Direction.OUTGOING, enforceTargetType=true)
MailingList mailingList;
public void setDojo(Dojo dojo) {
this.dojo = dojo;
}
public void setMailingList(MailingList mailingList) {
this.mailingList = mailingList;
}
#Override
public String toString() {
return "Person [name=" + name + "]";
}
}
With no other changes to the repository, this code runs without any errors, and inspecting the created Neo4j database shows that it is behaving as expected.

Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value:

Hi here is Bussinss object class where pwdId and userId are notnull in db
#Entity
#Table(name="CLOUD_SVR_PASSWORDS_HISTORY")
#NamedQuery(name="CloudSvrPasswordsHistory.findAll", query="SELECT c FROM CloudSvrPasswordsHistory c")
public class CloudSvrPasswordsHistory implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name="PWD_ID",nullable=false)
private long pwdId;
#Column(name="OLD_PASSWORD")
private String oldPassword;
#Column(name="CURRENT_PASSWORD")
private String currentPassword;
#Column(name="PWD_CHANGE_TYPE")
private String pwdChangeType;
#Column(name="CREATED_DATE")
private Timestamp createdDate;
#ManyToOne
#JoinColumn(name="USER_ID",nullable=false)
private CloudSvrUser user;
public long getPwdId() {
return pwdId;
}
public void setPwdId(long pwdId) {
this.pwdId = pwdId;
}
public String getOldPassword() {
return oldPassword;
}
public void setOldPassword(String oldPassword) {
this.oldPassword = oldPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getPwdChangeType() {
return pwdChangeType;
}
public void setPwdChangeType(String pwdChangeType) {
this.pwdChangeType = pwdChangeType;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
public CloudSvrUser getUser() {
return user;
}
public void setUser(CloudSvrUser user) {
this.user = user;
}
here is my service implementation class only one method I am specifyng
#Transactional
public void changePassword(CloudSvrPasswordsHistory pwdInfo)throws BusinessException
{
//String password=null;
try{
System.out.println("servcimpl----------");
CloudSvrUser dbUser =getUser(pwdInfo);
if(dbUser != null){
List<CloudSvrPasswordsHistory> newPwdList = new ArrayList<CloudSvrPasswordsHistory>();
CloudSvrPasswordsHistory changedPwd = new CloudSvrPasswordsHistory();
changedPwd.setOldPassword(pwdInfo.getOldPassword());
changedPwd.setCurrentPassword(pwdInfo.getCurrentPassword());
newPwdList.add(changedPwd);
dbUser.setPassCode(changedPwd.getCurrentPassword());
//set childs to parent
pwdInfo.setUser(dbUser);
dbUser.setUserPwdList(newPwdList);
//password=
changedPwd(dbUser);
System.out.println("serviceimplend---------");
}
}
catch(DaoException daoexception)
{
throw new BusinessException(daoexception.getMessage());
}
//return password;
}
here is my DAOImpl class
#Repository("passwordDao")
public class PasswordDaoImpl extends BaseDaoImpl implements PasswordDao
{
PasswordDaoImpl()
{}
public void ChangedPwd(CloudSvrUser user)
{
//String password=null;
List<CloudSvrPasswordsHistory> pwdinfo = user.getUserPwdList();
for(CloudSvrPasswordsHistory changedPwd:pwdinfo)
{
//changedPwd.setPwdId((new Long(1)));
changedPwd.setCreatedDate(new Timestamp(System.currentTimeMillis()));
changedPwd.setPwdChangeType("ByUser");
}
try{
super.getHibernateTemplate().update(user);
//this.userDao.updateUser(dbUser);
}
catch(DataAccessException accessException){
throw new DaoException("Internal DB error occured.");
}
//return password ;
}
when giving request getting exception in console
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.omnypay.dao.bo.CloudSvrPasswordsHistory.user
please help me
The error says the user property of CloudSvrPasswordsHistory entity is null, where as hibernate is expecting it to be not-null, this is because you told hibernate that nullable=false for user property using this mapping:
#ManyToOne
#JoinColumn(name="USER_ID",nullable=false)
private CloudSvrUser user;
So to fix the issue you have to set the user property for your CloudSvrPasswordsHistory entity as:
changedPwd.setUser(dbUser);

JAXB Object won't marshal/unmarshal List property

With the following:
#XmlRootElement(name = "purchase")
#XmlType(propOrder = {"memberId", "propertyA", "propertyB", "propertyC", "listProps"})
public class ClassA {
private Long memberId;
private Integer propertyA;
private String propertyB;
private Integer propertyC;
private List<ClassB> listProps;
public ClassA() {
}
#XmlElement(name = "memberId")
public Long getMemberId() {
return memberId;
}
public void setMemberId(Long memberId) {
this.memberId = memberId;
}
#XmlElement(name = "propertyA")
public Integer getPropertyA() {
return propertyA;
}
public void setPropertyA(Integer propertyA) {
this.propertyA = propertyA;
}
#XmlElement(name = "propertyB")
public String getPropertyB() {
return propertyB;
}
public void setPropertyB(String propertyB) {
this.propertyB = propertyB;
}
#XmlElement(name = "propertyC")
public Integer getPropertyC() {
return propertyC;
}
public void setPropertyC(Integer propertyC) {
this.propertyC = propertyC;
}
#XmlElement(name = "listProps")
public List<ClassB> getListProps() {
return listProps;
}
public void setListProps(List<ClassB> listProps) {
this.listProps = listProps;
}
}
#XmlRootElement(name = "listProp")
#XmlType(propOrder = {"countA", "countB"})
public class ClassB {
private int countA;
private int countB;
public ClassB() {
}
public int getCountA() {
return countA;
}
public int getCountB() {
return countB;
}
#XmlElement(name = "countA")
public void setCountA(int countA) {
this.countA = countA;
}
#XmlElement(name = "countB")
public void setCountB(int countB) {
this.countB = countB;
}
}
When I try and marshal / unmarshal objects of type ClassA, the listProps is always empty regardless of how many objects I have put in it. Can anyone tell me what I am doing wrong?
When I marshal your model classes as follows:
import java.util.*;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(ClassA.class);
List<ClassB> classBs = new ArrayList<ClassB>();
classBs.add(new ClassB());
classBs.add(new ClassB());
ClassA classA = new ClassA();
classA.setListProps(classBs);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(classA, System.out);
}
}
I get the following output, so there is no problem with your list property:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<purchase>
<listProps>
<countA>0</countA>
<countB>0</countB>
</listProps>
<listProps>
<countA>0</countA>
<countB>0</countB>
</listProps>
</purchase>
As I understand your problem is to unmarshal list of values which you have marshaled. The same problem I faced with jaxb-impl lib +2.2.x when unmarshaling results into empty list while XML contains at least 1 element. Try to instantiate list if it is null in method getListProps so JAXB could populate it. I feel like the problem is in List + XmlAccessorType.PROPERTY as it does not create list by default and tries to use existing one, because it is null setListProps is called with empty collection.

How to set value of list<String> in DynamicJasper

I need to generate dynamic count of columns in me report. So I set to my JasperPrint the massive of Object:
Object[] obj = new Object[selectedUsers.size()];
//fill the massive
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), new JRBeanArrayDataSource(obj));
My obj is a class:
public class ResultsDTO {
private String login;
private Integer id;
private List<String> list;
private Object[] results;
public Object[] getResults() {
return results;
}
public void setResults(Object[] results) {
this.results = results;
}
public ResultsDTO(){
}
public ResultsDTO(Integer id,String login) {
super();
this.login = login;
this.id = id;
}
public ResultsDTO(String login, Integer id, List<String> list) {
super();
this.login = login;
this.id = id;
this.list = list;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public void addToList(String day_result){
this.list.add(day_result);
}
}
and then I try to create columns:
FastReportBuilder firstReport = new FastReportBuilder();
List<AbstractColumn> column_list = new ArrayList<AbstractColumn>();
AbstractColumn columnId = getColumn("id", Integer.class,"№", 30, headerStyle, detailStyle);
AbstractColumn columnLogin = getColumn("login", String.class,"ФИО", 150, headerStyle, detailStyle);
for (int i = 0; i < header.size(); i++){
AbstractColumn column = getColumn("results", Object.class, header.get(i), 80, headerStyle, detailStyle);
column_list.add(column);
}
Eventually I have an exception:
net.sf.jasperreports.engine.design.JRValidationException: Report
design not valid :
1. Class "java.lang.Object" not supported for text field expression.
Please, help! I don' know how to use jasper and list or array
Jasper Reports does not allow Object as a valid type for its elements. I has to be one of the following:
String
Number (or any subclass of it)
Date
Boolean
You should ask each element in the form for its class and pass proper class to the column builder.