Error while creating singleton in Java EE - spring

I am new to Java EE an I am trying to add a new database table and program to an existing Java EE application that uses hibernate with persistence and spring framework. I am getting an error that says symbol not found
I've created 4 classes:-
public interface ncs_userInterface extends Persistable {
public abstract int getVersion();
public abstract String getPERSONIDNO();
public abstract String getFULLNAME();
public abstract long getID();
public abstract Date getCreationDate();
public abstract int getROLEID();
public abstract int getSCHEMEID();
public abstract String getSCHEMETITLE();
public abstract String getROLENAME();
public abstract void setVersion(int version);
public abstract void setPERSONIDNO(String PERSONIDNO);
public abstract void setFULLNAME(String FULLNAME);
public abstract void setID(long ID);
public abstract void setCreationdate(Date creationdate);
public abstract void setROLEID(int ROLEID);
public abstract void setSCHEMEID(int SCHEMEID);
public abstract void setSCHEMETITLE(String SCHEMETITLE);
public abstract void setROLENAME(String ROLENAME);
}
public class ncs_user extends PersistentObject implements ncs_userInterface{
private long ID;
private int version;
private Date creationdate;
private String PERSONIDNO;
private String FULLNAME;
private int ROLEID;
private String ROLENAME;
private int SCHEMEID;
private String SCHEMETITLE;
public ncs_user() {
}
public ncs_user(String PERSONIDNO, int version){
this.PERSONIDNO=PERSONIDNO;
this.version=version;
}
// All the getters and setters follow this but haven't listed them in this code
}
public abstract class ncs_userManager extends BasicManager{
protected static ncs_userManager INSTANCE;
public static final synchronized ncs_userManager getInstance() {
return INSTANCE;
}
public abstract void createAndPersistncs_user(ncs_userInterface newNcs_user);
public abstract List findNcs_usersByIdentity(String PERSONIDNO);
public abstract void updateNcs_user(ncs_userInterface changedNcs_user);
public abstract void deleteNcs_user(ncs_userInterface deletableNcs_user);
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Hibernate;
import org.hibernate.type.Type;
import org.olat.admin.user.delete.service.UserDeletionManager;
import org.olat.core.commons.persistence.DB;
import org.olat.core.commons.persistence.DBFactory;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.id.Identity;
import org.olat.core.logging.OLog;
import org.olat.core.logging.Tracing;
import org.olat.core.util.coordinate.CoordinatorManager;
import org.olat.user.UserDataDeletable;
public class ncs_userManagerImpl extends ncs_userManager implements UserDataDeletable{
private static OLog log = Tracing.createLoggerFor(ncs_userManagerImpl.class);
public ncs_userManagerImpl(final UserDeletionManager userDeletionManager) {
userDeletionManager.registerDeletableUserData(this);
INSTANCE = this;
}
#Override
public void createAndPersistncs_user(final ncs_userInterface newNcs_user) {
final DB db = DBFactory.getInstance();
db.saveObject(newNcs_user);
if (log.isDebug()) {
log.debug("NCS_USER has been created: " + newNcs_user.getPERSONIDNO());
}
}
#Override
public List<ncs_userInterface> findNcs_usersByIdentity(final String PERSONIDNO) {
final String query = "from org.olat.ncs_user.ncs_user as b where b.PERSONIDNO = ?";
return DBFactory.getInstance().find(query, PERSONIDNO, Hibernate.LONG);
}
#Override
public void updateNcs_user(final ncs_userInterface changedNcs_user) {
DBFactory.getInstance().updateObject(changedNcs_user);
}
#Override
public void deleteNcs_user(final ncs_userInterface deletableNcs_user) {
DBFactory.getInstance().deleteObject(deletableNcs_user);
}
#Override
public void deleteUserData(final Identity identity, final String aString) {
}
}
I have also created a hibernate mapping file and a spring context file for the code above. I am trying to create a singleton using the following code:-
final ncs_userManager n;
n = new ncs_userManager.getInstance();
final ncs_userInterface newncs_user = new ncs_user(login, 0);
List l = n.findNcs_usersByIdentity(PERSONIDNO);
I am getting error in the line n = new ncs_userManager.getInstance():-
org/olat/admin/user/imp/ImportStep00.java:[205,75] error: cannot find symbol
I was wondering if someone could help me figure out what mistake I am making.

Remove the 'new' key word as its abstract class and you are calling static method of it.

Make it static and static final variable should be instantiated at the declaration time only.

Related

Getting null value from #configuration

I'm creating pojo class and store the application.properties variable but I'm getting null values
NOTE: need to access env from my Abstract class
POJO class
package mynt.xyz.c4.pushnotif.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
#Configuration("notificationEnvironment")
#ConfigurationProperties(prefix = "app.notif")
public class NotificationEnvironment {
private String key;
private String url;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
Initializing class with #autowired
public abstract class NotificationBase {
#Autowired
NotificationEnvironment notificationEnvironment;
public void getEnv(){
system.out.println(notificationEnvironment.getKey()); // null value
}
}
concrete class that extend to my NotificationBaseClass
#Component
#Qualifier("androidNotification")
public class AndroidNotification extends NotificationBase implements Notification {
public AndroidNotification(String message, String title, String datalink, List<String> instanceIds) {
super(message, title, datalink, instanceIds);
}
AndroidNotification(){
super();
}
#Override
public void send() {
this.getEnv();
}
}
application.properties
app.notif.key=jkashdkjashd
app.notif.url=https/some.url
You can auto wire #Configuration class from #Configuration class
#Configuration class may reference the instance of any other #Configuration class using #Autowired. This works because the #Configuration classes themselves are instantiated and managed as individual Spring beans.
Make your class #Component and add prefix value in #ConfigurationProperties, like this. This works for me, hope this works for you as well.
#Component
#ConfigurationProperties(prefix = "app.notif")
public class NotificationEnvironment {
private String key;
private String url;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
You can use this properties like this:
#Component
public class NotificationBase {
private static NotificationEnvironment notificationEnvironment;
#Autowired
public NotificationBase(NotificationEnvironment notificationEnvironment){
this.notificationEnvironment = notificationEnvironment;
}
public static void getEnv(){
System.out.println(notificationEnvironment.getKey()); // null value
}
}
Here is the one of the concrete class definition as OP author mentioned.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
#Component
public class ConcreteNotification extends NotificationBase {
#Autowired
public ConcreteNotification(NotificationEnvironment notificationEnvironment) {
super(notificationEnvironment);
}
}
updated NotificationBase as below
public abstract class NotificationBase {
NotificationEnvironment notificationEnvironment;
public NotificationBase(NotificationEnvironment notificationEnvironment) {
this.notificationEnvironment = notificationEnvironment;
}
public void getEnv(){
System.out.println(notificationEnvironment.getKey());
}
}
The controller class I am using to get configuration values
#RestController
public class ArticleCommentController {
#Autowired
ConcreteNotification concreteNotification;
#RequestMapping(value = "/health_check", method = RequestMethod.GET)
public void getDemo() {
concreteNotification.getEnv();
}
}
output:
jkashdkjashd

JUNIT - Null pointer Exception while calling findAll in spring Data JPA

I am new to Junits and Mockito, I am writing a Unit test class to test my service class CourseService.java which is calling findAll() method of CourseRepository.class which implements CrudRepository<Topics,Long>
Service Class
#Service
public class CourseService {
#Autowired
CourseRepository courseRepository;
public void setCourseRepository(CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
public Boolean getAllTopics() {
ArrayList<Topics> topicList=(ArrayList<Topics>) courseRepository.findAll();
if(topicList.isEmpty())
{
return false;
}
return true;
}
}
Repository class
public interface CourseRepository extends CrudRepository<Topics,Long>{
}
Domain class
#Entity
#Table(name="Book")
public class Topics {
#Id
#Column(name="Topicid")
private long topicId;
#Column(name="Topictitle",nullable=false)
private String topicTitle;
#Column(name="Topicauthor",nullable=false)
private String topicAuthor;
public long getTopicId() {
return topicId;
}
public void setTopicId(long topicId) {
this.topicId = topicId;
}
public String getTopicTitle() {
return topicTitle;
}
public void setTopicTitle(String topicTitle) {
this.topicTitle = topicTitle;
}
public String getTopicAuthor() {
return topicAuthor;
}
public void setTopicAuthor(String topicAuthor) {
this.topicAuthor = topicAuthor;
}
public Topics(long topicId, String topicTitle, String topicAuthor) {
super();
this.topicId = topicId;
this.topicTitle = topicTitle;
this.topicAuthor = topicAuthor;
}
}
Following is the Junit class I have written but courseRepository is getting initialized to NULL and hence I am getting NullPointerException.
public class CourseServiceTest {
#Mock
private CourseRepository courseRepository;
#InjectMocks
private CourseService courseService;
Topics topics;
#Mock
private Iterable<Topics> topicsList;
#Before
public void setUp() {
MockitoAnnotations.initMocks(CourseServiceTest.class);
}
#Test
public void test_Get_Topic_Details() {
List<Topics> topics = new ArrayList<Topics>();
Mockito.when(courseRepository.findAll()).thenReturn(topics);
boolean result=courseService.getAllTopics();
assertTrue(result);
}
}
Change the setUp() method to:
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
Probably you are dealing with some problem on the framework to make the mocked class be injected by the framework.
I recommend to use Constructor Injection, so you don't need to rely on the reflection and #Inject/#Mock annotations to make this work:
#Service
public class CourseService {
private final CourseRepository courseRepository;
// #Autowired annotation is optional when using constructor injection
CourseService (CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
// .... code
}
The test:
#Test
public void test_Get_Topic_Details() {
List<Topics> topics = new ArrayList<Topics>();
Mockito.when(courseRepository.findAll()).thenReturn(topics);
CourseService courseService = new CourseService(courseRepository);
boolean result = courseService.getAllTopics();
assertTrue(result);
}

Junit test for saving data with JPA

Am trying to make a junit test to save data with JPA. Below is my entity class
#Entity
#Table(name="book")
public class test {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="BOOK_REF_ID",nullable=false)
private int bookRefId;
#Column(name="BOOK_CODE",nullable=false)
private String bookCode;
#Column(name="BOOK_NAME",nullable=false)
private String bookDescription;
public int getBookRefId() {
return bookRefId;
}
public void setBookRefId(int bookRefId) {
this.bookRefId = bookRefId;
}
public String getBookCode() {
return bookCode;
}
public void setBookCode(String bookCode) {
this.bookCode = bookCode;
}
public String getBookDescription() {
return bookDescription;
}
public void setBookDescription(String bookDescription) {
this.bookDescription = bookDescription;
}
}
Service class is
public interface BookService()
{
public Book create(Book book);
}
Repository class is
public interface BookRepository extends
JpaRepository<Book,Integer>
{ }
Service Implementation class is
public BookServiceImpli implements BookService()
{
#Resource
BookRepository repository;
#Override
public Book create(Book book) {
// TODO Auto-generated method stub
return repository.save(book);
}
}
Now my test class is
#RunWith(SpringRunner.class)
#DataJpaTest
#SpringBootTest(classes= {JPAConfig.class})
#AutoConfigureTestDatabase(replace=Replace.NONE)
#TestPropertySource(
locations = "classpath:application.properties")
public class TestBook {
#Autowired
private BookService bookService ;
#Test
public void test() {
Book book = new Book();
book.setBookCode("abc");
book.setBookDescription("safd");
bookService.create(book);
}
Application properties contains password and database details and JPAConfig contain JPA configuration details such as entity scan database details. When am trying to run the test case am getting an error like
A component required a bean of type
'com.repository.sample.BookRepository' that could not be found.
I don't have main method in it.Am new to unit testing please anyone help me to solve the issue.

Spring-boot batch file read and send data to Kafka

I am having trouble sending data from CSV file to Kafka. Here is my code for writer.java for batch processing
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder.In;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import com.codenotfound.kafka.repository.*;
import java.util.*;
import com.codenotfound.kafka.Car;
import com.codenotfound.kafka.producer.Sender;
public class Writer implements ItemWriter<Car>{
private final Repository repo;
public Writer(Repository repo) {
this.repo = repo ;
}
#Override
public void write(List<? extends Car> car) throws Exception {
repo.save(car);
}
}
So instead of repo.save(car), I want this car class details to be sent to Kafka.
Here is my Car class and Repository interface respectively
#Entity
#Table(name = "Car")
public class Car {
private String make;
private String manufacturer;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
public Car() {
//super();
}
public Car(String make, String manufacturer) {
super();
this.make = make;
this.manufacturer = manufacturer;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Override
public String toString() {
return "Car [make=" + make + ", manufacturer=" + manufacturer + ", id=" + id + "]";
}
}
and Repository class
public interface Repository extends CrudRepository<Car, Long>,CustomRepository {
}
My Sender file for Kafka is:
package com.codenotfound.kafka.producer;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import com.codenotfound.kafka.Car;
public class Sender {
private static final Logger LOGGER = LoggerFactory.getLogger(Sender.class);
#Value("${topic.json}")
private String jsonTopic;
#Autowired
private KafkaTemplate<String, Car> kafkaTemplate;
public void send(Car car) {
LOGGER.info("sending car='{}'", car.toString());
kafkaTemplate.send(jsonTopic, car);
}
}
Please suggest to me a method to send data from a CSV file to my Kafka.
it seems you already have all the pieces of the puzzle laid out for you. What you need to do is change your ItemWriter using your Sender class, so you'd have something like this:
#Component
public class Writer implements ItemWriter<Car> {
#Value("${topic.json}")
private String jsonTopic;
#Autowired
private KafkaTemplate<String, Car> kafkaTemplate;
#Override
public void write(List<? extends Car> cars) throws Exception {
cars.forEach(car -> kafkaTemplate.send(jsonTopic, car));
}
}
and in your job configuration, you need to autowire it like this (the code below is simplified, just showing how to declare the writer in the step):
#Configuration
#EnableBatchProcessing
public class BatchConfiguration {
#Autowired
public StepBuilderFactory stepBuilderFactory;
#Autowired
private Writer carWriter;
#Bean
public Step myStep() {
this.stepBuilderFactory.get("myStep")
.<Car,Car> chunk(10)
.reader(reader())
.writer(carWriter) // don't use new here
.build();
}
}

Error #Autowired an interface with another project

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MiParteTrabajoDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mydomain.repository.produccion.ParteTrabajoRepository com.mydomain.dao.produccion.ParteTrabajoDaoExample.parteRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mydomain.repository.produccion.ParteTrabajoRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.inject.Inject()}
package com.mydomain.repository;
import java.io.Serializable;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
#NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends JpaRepository<T, ID> {
#Override
<S extends T> S save(S entity);
#Override
T findOne(ID primaryKey);
#Override
List<T> findAll();
#Override
long count();
#Override
void delete(T entity);
#Override
boolean exists(ID primaryKey);
}
and
package com.mydomain.repository.produccion;
public interface ParteTrabajoRepository extends CrudRepository<PParteTrabajo, PParteTrabajoPK> {
#Query(value = "select u from PParteTrabajo u where u.idParteTrabajo like %?1", nativeQuery = true)
public PParteTrabajo findByIdParteTrabajo(int idParteTrabajo);
}
and
package com.mydomain.dao.produccion;
public interface ParteTrabajoDaoI {
public List<PParteTrabajo> findAll();
}
and
package com.mydomain.dao.produccion;
#Repository("MiParteTrabajoDao")
public class ParteTrabajoDaoExample implements ParteTrabajoDaoI {
#Autowired
private ParteTrabajoRepository parteRepository;
#Override
public List<PParteTrabajo> findAll() {
final List<PParteTrabajo> lista = parteRepository.findAll();
return null;
}
}
and
package com.mydomain.services.produccion;
import com.mydomain.entities.produccion.PParteTrabajo;
import com.mydomain.util.dao.DaoException;
import com.mydomain.util.exception.FindException;
public interface ParteTrabajoServiceI<T> {
public T iniciarParteTrabajo(int idMaquina, int idEstacion, int idOperario, int idTrabajo, int idOrden)
throws FindException;
public PParteTrabajo iniciarFinalizarParteTrabajo(int idMaquina, int idEstacion, int idOperario, int idTrabajo,
int idOrden) throws FindException, DaoException;
public T iniciarParteTrabajoMaquinaTrabajoUnico(int idMaquina, int idOperario, int idOrden) throws FindException,
DaoException;
public PParteTrabajo finalizarParteTrabajo(T parteTrabajoIniciado, BigDecimal cantidad) throws DaoException,
FindException;
public List<PParteTrabajo> finalizarPartesTrabajosIniciados(int idMaquina, int idOperario) throws FindException,
DaoException;
public List<T> getPartesTrabajoIniciados(int idMaquina, int idOperario) throws FindException;
public List<T> getPartesTrabajoIniciados(int idMaquina) throws FindException;
public List<T> findAll() throws FindException;
}
and
package com.mydomain.services.produccion;
import com.mydomain.dao.produccion.ParteTrabajoDaoI;
import com.mydomain.entities.produccion.PParteTrabajo;
import com.mydomain.util.dao.DaoException;
import com.mydomain.util.exception.FindException;
#Service("parteTrabajoServicePrueba")
public class ParteTrabajoServiceExample implements
ParteTrabajoServiceI<ParteTrabajoServiceExample.ParteTrabajoIniciado> {
#Autowired
#Qualifier("MiParteTrabajoDao")
private ParteTrabajoDaoI parteTrabajoDaoI;
#Override
public List<ParteTrabajoIniciado> getPartesTrabajoIniciados(final int idMaquina, final int idOperario) {
return null;
}
public class ParteTrabajoIniciado {
private final PParteTrabajo parte;
private ParteTrabajoIniciado(final PParteTrabajo parteTrabajo) {
parte = parteTrabajo;
}
public int getIdOrdenProduccion() {
return parte.getIdOrdenProduccion();
}
}
....
}
and
package com.mydomain.iweb;
#SpringBootApplication
#Configuration
#Import(com.mydomain.services.ServicesBeanConfig.class)
#EnableTransactionManagement
#EnableAutoConfiguration
#PropertySource("file:etc/application.properties")
#EnableJpaRepositories("com.mydomain.repository,com.mydomain.dao")
public class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class.getName());
#Value("${spring.datasource.jndi-name}")
private String jndiResourceName;
#Value("${spring.datasource.name}")
private String jdbcName;
#Value("${spring.datasource.driver-class-name}")
private String jdbcDriverClassName;
#Value("${spring.datasource.url}")
private String jdbcUrl;
#Inject
ApplicationContext ctx;
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
.....
}
The value for EnableJpaRepositories is wrong.
The value is an array, so it should be
#EnableJpaRepositories(value ={"com.mydomain.repository","com.mydomain.dao"})
The way you declared it spring would try to scan only one package with the name
"com.mydomain.repository,com.mydomain.dao"
which for sure is not what you want.
You may have missed the bean implementing the ParteTrabajoRepository interface.
com.mydomain.repository.produccion.ParteTrabajoRepository is just an interface but it needs a concrete implementation in order for it to be injected with #Autowired

Resources