cannot create an instance of class - viewmodel ( java ) - java

I am trying to use android viewmodel , livedata with room database. although room database is working finely , when i try to create a instance of viewmodel class i always got following error
Cannot create an instance of class com.ceylonlinux.apwsdelivery.viewmodel.UnproductiveActivityViewModel
these are my viewmodel , activity , entity and dao classes
database class
#Database(entities = { Reason.class}, version = 1)
public abstract class APWSDatabase extends RoomDatabase {
public abstract UnproductiveVisitDao unproductiveVisitDao();
public abstract ReasonDao reasonDao();
public abstract CustomerDao customerDao();
}
entity class
#Entity
public class Reason {
#PrimaryKey
private int reasonId;
private int reasonType;
private String reasonName;
public Reason() {
}
public Reason(int reasonId, int reasonType, String reasonName) {
this.reasonId = reasonId;
this.reasonType = reasonType;
this.reasonName = reasonName;
}
public int getReasonId() {
return reasonId;
}
public void setReasonId(int reasonId) {
this.reasonId = reasonId;
}
public int getReasonType() {
return reasonType;
}
public void setReasonType(int reasonType) {
this.reasonType = reasonType;
}
public String getReasonName() {
return reasonName;
}
public void setReasonName(String reasonName) {
this.reasonName = reasonName;
}
}
Dao class
public interface ReasonDao {
#Insert
void insertAll(Reason... reasons);
#Insert
void insert(Reason reason);
#Query("SELECT * FROM reason")
List<Reason> loadAll();
#Query("SELECT * FROM reason where reasonType = (:reasonType)")
List<Reason> getReasonsByType(Integer reasonType);
#Query("SELECT * FROM reason where reasonType = (:reasonType)")
LiveData<List<Reason>> getReasonsByTypeLive(Integer reasonType);
#Delete
void delete(Reason reason);
}
viewmodel class
public class UnproductiveActivityViewModel extends ViewModel {
private LiveData<List<Reason>> unproductiveReasons;
private Application application;
private ReasonRepository repository;
public UnproductiveActivityViewModel(Application application) {
this.application = application;
try {
repository = new ReasonRepository(application);
unproductiveReasons = repository.getUnproductiveReasons();
}catch (Exception e)
{
Log.e("ERROR",e.toString());
}
}
public LiveData<List<Reason>> getUnproductiveReasons() {
return unproductiveReasons;
}
}
in my activity class i used it like as follows
viewModel = new ViewModelProvider(UnproductiveActivity.this).get(UnproductiveActivityViewModel.class);
viewModel.getUnproductiveReasons().observe(this, reasonsz -> {
reasons = (ArrayList<Reason>) reasonsz;
adapter_reason = new ArrayAdapter<Reason>(UnproductiveActivity.this, android.R.layout.simple_spinner_item, reasons);
adapter_reason.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
un_reason_spinner.setAdapter(adapter_reason);
un_reason_spinner.setPaddingSafe(0, 0, 0, 0);
});

Related

Consider defining a bean of type 'form' in your configuration

Place that is complaining the error:
#Data
public class AluguelValorForm {
#Autowired
private ValorAluguelMultaService valorAluguelMultaService;
#NotNull #NotEmpty
private String idAluguel;
#NotNull
private Double valor;
public AluguelValor converter(AluguelValorRepository aluguelValorRepository, AluguelForm form ) {
Double valorAluguel = valorAluguelMultaService.valorAluguel(form);
return new AluguelValor(idAluguel,valorAluguel);
}
public AluguelValor update(String idAluguel,Double valor) {
AluguelValor aluguelValor = new AluguelValor();
aluguelValor.setId(idAluguel);
aluguelValor.setValor(valor);
return aluguelValor;
}
Repository:
#Repository
public interface AluguelValorRepository extends MongoRepository<AluguelValor, String> {
Aluguel getReferenceById(String id);
}
Place that I call the method in AluguelValorForm:
#PostMapping
//#CacheEvict(value = "listaDeTopicos",allEntries = true)
public void cadastrar(#RequestBody AluguelForm form) {
Optional<Carro> carro = carroRepository.findByPlaca(form.getPlaca_carro());
Optional<Cliente> cliente = clienteRepository.findByCpf(form.getCpf());
if(carro.isPresent() && cliente.isPresent()) {
Aluguel aluguel2 = form.converter(aluguelRepository);
aluguelRepository.save(aluguel2);
Double valorAluguel = valorAluguelMultaService.valorAluguel(form);
AluguelValor aluguelValor = aluguelValorForm.update(aluguel2.getId(), valorAluguel);
aluguelValorRepository.save(aluguelValor);
}
}
Problem solved. Apparently, it's not possible to #Autowired a class that doesn't have any bean, like my RentValue. That's why I got this error.

Problem trying to mock more than one Java Interface

I've been writting some tests for a legacy web app on java using DeltaSpike, Weld, Hibernate and others frameworks.
I have faced some problem with my first test class that injects many Mocked interfaces on a Service.
Let me show some code:
Service to be tested
public class DistribuicaoProcessoManualServiceImpl extends DistribuicaoService implements DistribuicaoProcessoManualService {
#Inject
#WebServiceTJDBEntityManager EntityManager wstjEM;
private ForoTJComarcaMPRepository foroMPRepository;
private AssuntoTJNaturezaMPRepository naturezaMPRepository;
private VaraTJVaraMPRepository varaMPRepository;
private ClasseTJTipoMPRepository tipoMPRepository;
private ProcessoRepository processoRepository;
private UsuarioRepository usuarioRepository;
private UsuarioDaSessao usuarioDaSessao;
/**
* #deprecated CDI eyes only
*/
public DistribuicaoProcessoManualServiceImpl() {
this(null, null, null, null, null, null, null);
}
#Inject
public DistribuicaoProcessoManualServiceImpl(
ForoTJComarcaMPRepository foroMPRepository,
AssuntoTJNaturezaMPRepository naturezaMPRepository,
ClasseTJTipoMPRepository tipoMPRepository,
ProcessoRepository processoRepository,
UsuarioRepository usuarioRepository,
UsuarioDaSessao usuarioDaSessao,
VaraTJVaraMPRepository varaMPRepository) {
this.foroMPRepository = foroMPRepository;
this.naturezaMPRepository = naturezaMPRepository;
this.tipoMPRepository = tipoMPRepository;
this.processoRepository = processoRepository;
this.usuarioRepository = usuarioRepository;
this.usuarioDaSessao = usuarioDaSessao;
this.varaMPRepository = varaMPRepository;
}
#Override
#Transactional(readOnly = false, qualifier = {WebServiceTJDBEntityManager.class})
public Processo vinculaOuPreparaParaEspecializacao(Processo processo) {
//Service do some validations here with Guava's Preconditions;
Usuario usuario = usuarioRepository.procurarPorLogin(usuarioDaSessao.getUsuario().getLogin());
processo.atualizaInformacoesDeProcuradoriaEUsuario(usuario);
ProcessoDoTJMapeamentoParaMP processoDePara = compoeMapeamento(processo);
VaraTJVaraMP varaMP = varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(processoDePara);
ForoTJComarcaMP comarcaMP = foroMPRepository.procurarPorIdForoEPorProcuradoria(processoDePara);
AssuntoTJNaturezaMP naturezaMP = naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(processoDePara);
ClasseTJTipoMP tipoMP = tipoMPRepository.procurarPorCodigoEPorProcuradoria(processoDePara);
processoDePara
.comComarcaMP(comarcaMP)
.comVaraMP(varaMP)
.comNaturezaMP(naturezaMP)
.comTipoMP(tipoMP);
processoRepository.inclui(processo);
return processo;
}
}
The extended Class:
public abstract class DistribuicaoService {
public ProcessoDoTJMapeamentoParaMP compoeMapeamento(Processo processo) {
return new ProcessoDoTJMapeamentoParaMP(processo);
}
}
The mapper/builder/aggregator:
public class ProcessoDoTJMapeamentoParaMP implements Serializable {
private static final long serialVersionUID = 1L;
private final Processo processo;
public ProcessoDoTJMapeamentoParaMP(final Processo processo) {
this.processo = processo;
this.comCamaraMP( OrgaoJulgadorTJCamaraMP.semEfeito() )
.comRelatorMP( RelatorTJRelatorMP.semEfeito() )
.comOrigemMP( new OrgaoJulgadorTJOrigemMP() )
.comTipoDeRemessaMP();
}
public ProcessoDoTJMapeamentoParaMP comComarcaMP(ComarcaMP comarcaMP) {
processo.getDadosOrigem().setCodigoComarcaMP(comarcaMP.getIdComarca());
return this;
}
public ProcessoDoTJMapeamentoParaMP comVaraMP(VaraMP varaMP) {
processo.getDadosOrigem().setCodigoVaraMP(varaMP.getIdVaraMP());
return this;
}
public ProcessoDoTJMapeamentoParaMP comNaturezaMP(AssuntoTJNaturezaMP naturezaMP) {
processo.getAssuntoPrincipal().setCodigoNaturezaMP(naturezaMP.getIdNatureza());
return this;
}
public ProcessoDoTJMapeamentoParaMP comTipoMP(ClasseTJTipoMP tipoMP) {
processo.getDadosProcesso().getClasse().setCodigoTipoMP(tipoMP.getIdTipo());
return this;
}
ProcessoDoTJMapeamentoParaMP comCamaraMP(OrgaoJulgadorTJCamaraMP camaraMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoCamaraMP(camaraMP.getIdCamara());
return this;
}
ProcessoDoTJMapeamentoParaMP comRelatorMP(RelatorTJRelatorMP relatorMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoRelatorMP(relatorMP.getIdRelatorMP());
return this;
}
ProcessoDoTJMapeamentoParaMP comOrigemMP(OrgaoJulgadorTJOrigemMP origemMP) {
processo.getDadosDistribuicao().getMapeamento().setCodigoOrigemMP(origemMP.getIdOrigem());
return this;
}
ProcessoDoTJMapeamentoParaMP comTipoDeRemessaMP() {
processo.setTipoRemessa(TipoDeRemessa.fromTipoDeProcesso(this.processo.getProcessoVirtualTJ()));
return this;
}
public Procuradoria getProcuradoria() {
return processo.getProcuradoria();
}
public Integer getCodigoForoTJ() {
return processo.getDadosOrigem().getCodigoForoPrimeiraInstancia();
}
public Integer getCodigoVaraTJ() {
return processo.getDadosOrigem().getCodigoVaraPrimeiraInstancia();
}
public List<Parte> getPartes() {
return processo.getPartes();
}
public String getNomeAssuntoTJ() {
return processo.getAssuntoPrincipal().getDescricaoAssunto();
}
public Integer getCodigoClasseTJ() {
return processo.getDadosProcesso().getClasse().getCodigoClasse();
}
public String getNomeOrgaoJulgadorTJ() {
return processo.getDadosDistribuicao().getOrgaoJulgador().getNomeOrgaoJulgador();
}
public String getNomeRelatorTJ() {
return processo.getDadosDistribuicao().getRelator().getNomeRelator();
}
public Integer getIdAssuntoTJ() {
return processo.getAssuntoPrincipal().getCodigoAssunto();
}
public Movimentacao getUltimoMovimento() {
return null;
}
Class for Test:
#SuppressWarnings("deprecation")
#RunWith(MockitoJUnitRunner.class)
public class DistribuicaoProcessoManualServiceTest {
#Mock private ForoTJComarcaMPRepository foroMPRepository;
#Mock private AssuntoTJNaturezaMPRepository naturezaMPRepository;
#Mock private VaraTJVaraMPRepository varaMPRepository;
#Mock private ClasseTJTipoMPRepository tipoMPRepository;
#Mock private ProcessoRepository processoRepository;
#Mock private UsuarioRepository usuarioRepository;
#Mock private Usuario usuario;
#Mock private Procuradoria procuradoria;
#Mock private VaraTJVaraMP varaMP;
#Mock private ForoTJComarcaMP comarcaMP;
#Mock private AssuntoTJNaturezaMP naturezaMP;
#Mock private ClasseTJTipoMP tipoMP;
#Mock private UsuarioDaSessao usuarioDaSessao;
#InjectMocks
private DistribuicaoProcessoManualServiceImpl service = new DistribuicaoProcessoManualServiceImpl();
private Processo processo;
#Before
public void setUpMethod() {
initMocks(this);
//Others Builders for populate "processo" here;
processo = ProcessoBuilder()
.com(hoje)
.com(PARECER)
.com(FISICO)
.com(dadosProcesso)
.com(dadosOrigem)
.com(distribuicao)
.com(fila)
.cria();
ProcessoDoTJMapeamentoParaMP mapeamento = new ProcessoDoTJMapeamentoParaMP(processo);
when(usuario.getLogin()).thenReturn("luizrodriguesj");
when(usuario.getProcuradoria()).thenReturn(procuradoria);
when(usuarioDaSessao.getUsuario()).thenReturn(usuario);
when(usuarioRepository.procurarPorLogin(anyString())).thenReturn(usuario);
when(comarcaMP.getIdComarca()).thenReturn(1);
when(foroMPRepository.procurarPorIdForoEPorProcuradoria(mapeamento)).thenReturn(comarcaMP);
when(varaMP.getIdVaraMP()).thenReturn(1);
when(varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(mapeamento)).thenReturn(varaMP);
when(naturezaMP.getIdNatureza()).thenReturn(1);
when(naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(mapeamento)).thenReturn(naturezaMP);
when(tipoMP.getIdTipo()).thenReturn(1);
when(tipoMPRepository.procurarPorCodigoEPorProcuradoria(mapeamento)).thenReturn(tipoMP);
}
Method with problem:
#Test(expected = ApplicationException.class)
public void naoPermitirDistribuicaoDeProcessoSemUmMapeamentoDeVaraCorrespondente() {
service.vinculaOuPreparaParaEspecializacao(processo);
}
The interface that it was possible to mock:
public interface UsuarioRepository extends GenericDAO<Usuario, Long> {
boolean isAutenticavel(Usuario usuario);
Usuario procurarPorLogin(String login);
List<Usuario> lista(UsuarioPesquisa pesquisa, Paginacao paginacao);
}
One of Interfaces that not obey instruction mock and return null:
public interface ForoTJComarcaMPRepository extends GenericDAO<ForoTJComarcaMP, Long> {
ForoTJComarcaMP procurarPorIdForoEPorProcuradoria(ProcessoDoTJMapeamentoParaMP processoDePara);
List<ForoTJComarcaMP> lista(DominioMPPesquisa pesquisa, Paginacao paginacao);
ForoTJComarcaMP procuraPorForoTJ(ForoTJComarcaMP foroTJComarcaMP);
ForoTJComarcaMP procuraPorEntidade(ForoTJComarcaMP clone);
List<ForoTJComarcaMP> listaMapeamentoDistinctPor(Procuradoria procuradoria);
}
After others methods in this class that runs without any problem, this last one just fails because a NullPointerException (NPE) that occurs in:
VaraTJVaraMP varaMP = varaMPRepository.procurarPorIdVaraTJForoEPorProcuradoria(processoDePara);
AssuntoTJNaturezaMP naturezaMP = naturezaMPRepository.procurarPorAssuntoEPorProcuradoria(processoDePara);
ClasseTJTipoMP tipoMP = tipoMPRepository.procurarPorCodigoEPorProcuradoria(processoDePara);
ForoTJComarcaMP comarcaMP = foroMPRepository.procurarPorIdForoEPorProcuradoria(processoDePara);
....
// The references "comarcaMP", "varaMP", "naturezaMP", "tipoMP" are null here and next step throws a NPE.
processoDePara
.comComarcaMP(comarcaMP)
Other Mocked Interface declared work without problem, like this one:
Usuario usuario = usuarioRepository.procurarPorLogin(usuarioDaSessao.getUsuario().getLogin());
Where the "usuario" reference is setted as declared on setup method in Test Class.
Sorry for any mistake or lack of more informations.
Thanks and best regards!

Neo4j OGM not saving RelationshipEntity

I have read every single question on SO but I still can't figure out why OGM for Neo4j doesn't save my RelationshipEntities.
Here PubmedDocumentNode and PubmedAuthorNode are both saved, but not the relationships citations and authors. MeshHeadingsUI edges instead are created fine.
Code:
#NodeEntity
public class PubmedDocumentNode extends Node {
#Id
#Index(unique = true)
public int PMID;
...
#Relationship(type = "CITES")
public List<PubmedCitesRelationship> citations;
#Relationship(type = "MeSHClass")
public List<MeSHClass> MeshHeadingsUI;
#Relationship(type = "AUTHOR")
public List<PubmedDocAuthorRelationship> authors;
public PubmedDocumentNode() {
node_type = NODE_TYPE;
citations = new ArrayList<>();
MeshHeadingsUI = new ArrayList<>();
authors = new ArrayList<>();
}
}
#NodeEntity
public class PubmedAuthorNode extends Node {
...
#Id
#Index(unique = true)
public String Author_Name;
....
}
#RelationshipEntity(type = "AUTHOR")
public class PubmedDocAuthorRelationship extends FeatureEdge {
public PubmedDocAuthorRelationship() {
label = new float[]{3.0f}; //just to try
}
#Id
#GeneratedValue
public long Id;
#StartNode
public PubmedDocumentNode document;
#EndNode
public PubmedAuthorNode author;
}
Parent classes:
public abstract class FeatureEdge extends DistributedNeo4jEntity {
#Property
public float label[];
public FeatureEdge() {
}
}
public abstract class Node extends DistributedNeo4jEntity {
...
public float state[];
public float label[];
...
public Node() {
...
}
}
public abstract class DistributedNeo4jEntity extends Neo4jEntity {
...
}
public abstract class Neo4jEntity {
#Labels
public List<String> labels = new ArrayList<>(); //I already tried to comment this but no luck
}
Save code:
//s is obtained by openSession
Transaction tx = s.beginTransaction();
arts.forEach(x -> s.save(x));
//arts.forEach(x -> x.authors.forEach(y -> s.save(y))); //tried also
//arts.forEach(x -> x.citations.forEach(y -> s.save(y))); //tried also
tx.commit();
tx.close();

How best to setup Room and Retrofit

I'm currently trying to setup Room with Retrofit. I have a working implementation...
It requests an ApiItemBean, then the ApiDatabase calls its ApiItemDAO to map a databased or new ApiItem with the ApiItemBean into a Single<ApiItem>.
That single is used in the ApiRepository by the ApiRequest, and eventually subscribed to in the figurative Usage.
ApiItemBean
public class ApiItemBean {
private final int a;
private final int b;
public ApiItemBean(int a, int b) {
this.a = a;
this.b = b;
}
public int a() {
return a;
}
public int b() {
return b;
}
}
ApiItem
#Entity(tableName = "api_item") public static class ApiItem {
#PrimaryKey private final int id;
ApiItem(int id) {
this.id = id;
}
public int id() {
return id;
}
}
ApiItemDAO
#Dao public interface ApiItemDAO {
#Insert(onConflict = OnConflictStrategy.REPLACE) long insert(ApiItem apiItem);
#Query("SELECT * FROM api_item WHERE id = :id") ApiItem apiItem(int id);
}
ApiDatabase
#Database(entities = { ApiItem.class }, version = 1) abstract class ApiDatabase extends RoomDatabase {
abstract ApiItemDAO apiItemDAO();
// More...
Single<ApiItem> mapApiItem(ApiItemBean apiItemBean) {
final ApiItem apiItem = new ApiItem(apiItemBean.a());
final ApiItem apiItemDb = apiItemDAO().apiItem(apiItem.id());
if (apiItemDb == null || !apiItemDb.equals(apiItem))
Log.i(getClass().getSimpleName(), String.format("insert=%s", apiItemDAO().insert(apiItem)));
return Single.just(apiItemDAO().apiItem(apiItem.id()));
}
// More...
}
ApiRequest
public interface ApiRequest {
#GET("API_ITEM_BEAN_REQUEST") Single<ApiItemBean> getApiItemBean();
// More...
}
ApiRepository
public class ApiRepository {
private final ApiRequest apiRequest;
private final ApiDatabase apiDatabase;
ApiRepository(ApiRequest apiRequest, ApiDatabase apiDatabase) {
this.apiRequest = apiRequest;
this.apiDatabase = apiDatabase;
}
Single<ApiItem> getApiItem() {
return apiRequest.getApiItemBean().flatMap(apiDatabase::mapApiItem);
}
// More...
}
Usage
public class Usage {
private final ApiRepository apiRepository;
Usage(ApiRepository apiRepository) {
this.apiRepository = apiRepository;
}
public void onUse() {
apiRepository.getApiItem().subscribe();
}
}
I am unsure on how best to check the requests against the database. See ApiDatabase::mapApiItem for an example of how I thought to do it.
Side note: I know there is no specific question, and should possibly be moved to CodeReview, however the code example is not fully working considering it would need to depend on a specific api and I thought it best to try here first. Sorry to any mods.

Hibernate createCriteria query with annotation based composite primary key

In my project, I am having trouble writing a createCriteria query with a composite primary key. My Entity class & DAO method are given below -
#Entity
#Table(name="METRICS")
public class Metrics implements Serializable {
private static final long serialVersionUID = -2580493160757497919L;
#EmbeddedId
protected MetricsID metricsID;
#Column(name="PROJ_PERF")
private String proj_perf;
#Column(name="ANALYSIS")
private String analysis;
public String getProj_perf() {
return proj_perf;
}
public void setProj_perf(String proj_perf) {
this.proj_perf = proj_perf;
}
public String getAnalysis() {
return analysis;
}
public void setAnalysis(String analysis) {
this.analysis = analysis;
}
public MetricsID getMetricsID() {
return metricsID;
}
public void setMetricsID(MetricsID metricsID) {
this.metricsID = metricsID;
}
}
#Embeddable
public class MetricsID implements Serializable {
private static final long serialVersionUID = 4691163770334366543L;
#Column(name="PROJECT_ID")
private String project_id;
#Column(name="METRICS_NO")
private int metrics_no;
public String getProject_id() {
return project_id;
}
public void setProject_id(String project_id) {
this.project_id = project_id;
}
public int getMetrics_n0() {
return metrics_no;
}
public void setMetrics_no(int i) {
this.metrics_no = i;
}
}
#Override
#Transactional
public List<Metrics> viewMetrics(String project_id) throws Exception {
List<Metrics> metrics = (List<Metrics>)sessionFactory.getCurrentSession().
createCriteria(Metrics.class).createAlias("metricsID.project_id", "project_id_alias").
add(Restrictions.eqProperty("project_id_alias.project_id", project_id)).list();
return metrics;
}
The error I am getting is - org.hibernate.QueryException: not an association: metricsID.project_id
I searched for several similar examples, and used alias on the suggestion of one of the search results, but it's my first time using an alias. What am I doing wrong?
Why do you need to use an alias? Have you tried to access directly?
Following this example, this code should work
#Override
#Transactional
public List<Metrics> viewMetrics(String project_id) throws Exception {
List<Metrics> metrics =
(List<Metrics>) sessionFactory.getCurrentSession()
.createCriteria(Metrics.class)
.add(Restrictions.eq("metricsID.project_id", project_id))
.list();
return metrics;
}

Categories