How to integrate wicket framework with mongoDB? - spring

I have using spring-data-mongodb 1.2.1-RELEASE in quick start application. it is working fine,
i can connect to mongo db i can create,update and delete collection now i want to integrate wicket-framework with this application.
Domain class
#Document
public class Student
{
#Id
private String id;
private String firstName;
private int age;
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
Student repository class
#Repository
public class StudentService
{
#Autowired
MongoTemplate mongoTemplate;
#Override
public void create(Student student)
{
mongoTemplate.insert(student);
}
#Override
public void update(Query query, Update update)
{
mongoTemplate.updateFirst(query, update, Student.class);
}
#Override
public List<Student> findAll()
{
List<Student> students = mongoTemplate.findAll(Student.class);
logger.debug("Student: {}", students);
return students;
}
#Override
public void delete(Student student)
{
mongoTemplate.remove(student);
}
#Override
public void deleteAll()
{
Query searchUserQuery = new Query(Criteria.where("age").gt(0));
mongoTemplate.remove(searchUserQuery, Student.class);
}
}
Mongo configuration class
#Configuration
#EnableMongoRepositories
#ComponentScan(basePackageClasses = {MongoDBApp.class})
#PropertySource("classpath:application.properties")
public class MongoConfiguration extends AbstractMongoConfiguration
{
#Override
protected String getDatabaseName()
{
return "demo";
}
#Override
public Mongo mongo() throws Exception
{
return new Mongo("localhost", 27017);
}
#Override
protected String getMappingBasePackage()
{
return "mypackage";
}
}
Mongo Db main class
public class MongoDBApp
{
static final Logger logger = LoggerFactory.getLogger(MongoDBApp.class);
public static void main(String[] args)
{
logger.info("Demo application");
ApplicationContext context = new AnnotationConfigApplicationContext(MongoConfiguration.class);
StudentService studentService = context.getBean(StudentService.class);
Student student = new Student();
student.setFirstName("foo");
student.setAge(24);
studentService.create(student);
List<Student> students = studentService.findAll();
logger.info("No. of students: {}", students.size());
studentService.delete(student);
logger.info("Deleted student: {}", student);
}
}
Dependencies in pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
For this code i want to integrate with wicket framework.
Please help me how to do that?

if your Spring/MongoDb works well you just need to integrate it into Wicket with module wicket-spring. You can find and example of this integration here:
http://wicketguide.comsysto.com/guide/chapter18.html#chapter18_2
The source is available here:
https://github.com/bitstorm/Wicket-tutorial-examples/tree/master/SpringInjectionExample

Thanks Andrea del bence,
I did like this in MyWicketApplication
#Override
public void init()
{
super.init();
getComponentInstantiationListeners().add(new SpringComponentInjector(this, getSpringContext()));
// add your configuration here
}
public ApplicationContext getSpringContext()
{
return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
}

Related

Parameter 0 of constructor required a bean of type 'javax.persistence.EntityManager' that could not be found

Hi I am working on spring boot and I have tried a lot of methods I keep getting this error but it did not happen and some code shows red can you helpenter image description here
enter image description here
enter image description here
you need to configure the entity manager with username, password, and host. hibernate need entitymanager to connect database. you can add the configuration like this
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.password=root
spring.datasource.username=root
Also you need
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId> // your db connector
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
public City(int id, String name, String countryCode, String district, int population) {
super();
this.id = id;
this.name = name;
this.countryCode = countryCode;
this.district = district;
this.population = population;
}
public City() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
#Repository
public class HibernateCityDal implements ICityDal {
private EntityManager entityManager;
#Autowired
public HibernateCityDal(EntityManager entityManager) {
this.entityManager = entityManager;
}
#Override
#Transactional
public List<City> getAll() {
Session session = entityManager.unwrap(Session.class);
List<City> cities = session.createQuery("from City",City.class).getResultList();
return cities;
}
#Override
public void add(City city) {
// TODO Auto-generated method stub
}
#Override
public void update(City city) {
// TODO Auto-generated method stub
}
#Override
public void delete(City city) {
// TODO Auto-generated method stub
}
}
#Service
public class CityManager implements ICityService {
private ICityDal cityDal;
#Autowired
public CityManager(ICityDal cityDal) {
this.cityDal = cityDal;
}
#Override
#Transactional
public List<City> getAll() {
return this.cityDal.getAll();
}
#Override
#Transactional
public void add(City city) {
}
#Override
#Transactional
public void update(City city) {
}
#Override
#Transactional
public void delete(City city) {
}
}
#RestController
#RequestMapping("/api")
public class CityController {
private ICityService cityService;
#Autowired
public CityController(ICityService cityService) {
this.cityService = cityService;
}
#GetMapping("/cities")
public List<City> get(){
return cityService.getAll();
}
}

Tables not created in Cassandra db using springboot

I tried to create tables in cassandra db on start-up of spring boot application but it doesn't seem to be able to create tables. Below is my configuration. I have the #EnableCassandraRepositories in my Application class. I already created my keyspace by default. So its just the tables that I'm looking to create.
Configuration
#Configuration
public class CassandraConfig extends AbstractCassandraConfiguration {
#Value("${cassandra.contactpoints}")
private String contactPoints;
#Value("${cassandra.port}")
private int port;
#Value("${cassandra.keyspace}")
private String keySpace;
#Value("${cassandra.basePackages}")
private String basePackages;
#Autowired
private Environment environment;
#Override
protected String getKeyspaceName() {
return keySpace;
}
#Override
#Bean
public CassandraClusterFactoryBean cluster() {
final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(contactPoints);
cluster.setPort(port);
return cluster;
}
#Override
#Bean
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
return new BasicCassandraMappingContext();
}
}
Entity
#Table
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
public class AssessmentAttemptDetailsEntity implements Serializable {
#PrimaryKeyColumn(type = PrimaryKeyType.PARTITIONED)
private String assessmentId;
#PrimaryKeyColumn(type = PrimaryKeyType.CLUSTERED)
private String attempid;
}
Application
#SpringBootApplication
#ComponentScan(basePackages = {"com.lte.assessmentanalytics.service","com.lte.assessmentanalytics.config", "com.lte.assessmentanalytics.model", "com.lte.assessmentanalytics.listener"})
#EnableCassandraRepositories("com.lte.assessmentanalytics.model")
public class AssessmentanalyticsApplication {
#Autowired
private AssessmentAttemptRepository assessmentAttemptRepository;
public static void main(String[] args) {
SpringApplication.run(AssessmentanalyticsApplication.class, args);
}
}
Repository
#Repository
public interface AssessmentAttemptRepository extends CassandraRepository<AssessmentAttemptDetailsEntity, Long> {
}
I was able to fix this by modifying my CassandraConfig class to.
#Configuration
#EnableCassandraRepositories("com.lte.assessmentanalytics.model")
public class CassandraConfig extends AbstractCassandraConfiguration {
#Value("${cassandra.contactpoints}")
private String contactPoints;
#Value("${cassandra.port}")
private int port;
#Value("${cassandra.keyspace}")
private String keySpace;
#Value("${cassandra.basePackages}")
private String basePackages;
#Override
protected String getKeyspaceName() {
return keySpace;
}
#Override
protected String getContactPoints() {
return contactPoints;
}
#Override
protected int getPort() {
return port;
}
#Override
public SchemaAction getSchemaAction() {
return SchemaAction.CREATE_IF_NOT_EXISTS;
}
#Override
public String[] getEntityBasePackages() {
return new String[] {basePackages};
}
}

Return IDs in JSON response from Spring Data REST

I've got an entity
#Entity
#Table(name = "books")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I initialize it like this
#PostConstruct
public void init() {
List<String> newFiles = this.listFiles();
newFiles.forEach(filename -> {
Book book = new Book();
book.setName(filename);
dbRepository.save(book);
});
}
If I set the result of save to an instance of Book, I can get the id and it is not null—so id is created fine.
I defined a repository
#RepositoryRestResource
public interface IBooksRepository extends CrudRepository<Book, Long> {
}
which I'd like to use to get and set data into the books table in the database.
When I try to access my repository rest using curl localhost:8080/books, I get this response
{
"_embedded":{
"books":[
{
"name":"simple-file.txt",
"_links":{
"self":{
"href":"http://localhost:8080/books/1"
},
"book":{
"href":"http://localhost:8080/books/1"
}
}
}
]
},
"_links":{
"self":{
"href":"http://localhost:8080/books"
},
"profile":{
"href":"http://localhost:8080/profile/books"
}
}
}
The books element returns name only. How can I make it return id too, on the same level as name?
Spring Data Rest hides the ID by default, in order to have it in the JSON you have to manually configure that for your entity. Depending on your spring version you can either provide your own configuration (old):
#Configuration
public class ExposeEntityIdRestConfiguration extends RepositoryRestMvcConfiguration {
#Override
protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Book.class);
}
}
...or register a RepositoryRestConfigurer (current):
#Component
public class ExposeEntityIdRestMvcConfiguration extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Book.class);
}
}
See the Spring Data Rest documentation for more details.
The accepted answer overrides a deprecated method. Here's the updated version:
#Component
public class RestConfig implements RepositoryRestConfigurer {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
config.exposeIdsFor(Book.class);
}
}
An alternative approach is to implement RepositoryRestConfigurer in your #SpringBootApplication annotated class:
#SpringBootApplication
public class MyApplication implements RepositoryRestConfigurer {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config, CorsRegistry cors) {
config.exposeIdsFor(Book.class);
}
}
There is now a static method RepositoryRestConfigurer.withConfig that does the same thing as above. See javadoc:
Convenience method to easily create simple {#link RepositoryRestConfigurer} instances that solely want to tweak the {#link RepositoryRestConfiguration}.
I found the usage in one of their integration tests
So the following approach would be more up to date as of now:
#Bean
public RepositoryRestConfigurer repositoryRestConfigurer()
{
return RepositoryRestConfigurer.withConfig(config -> {
config.exposeIdsFor(Book.class);
});
}
#Component
public class RestConfig implements RepositoryRestConfigurer {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.exposeIdsFor(Book.class);
//config.exposeIdsFor(Library.class);
}
}
This is a solution which works for all entities
#Autowired
private EntityManager entityManager;
#Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {
return RepositoryRestConfigurer.withConfig(config -> config.exposeIdsFor(entityManager.getMetamodel().getEntities().stream().map(Type::getJavaType).toArray(Class[]::new)));
}
This is a good way to go.
#Projection(name = "customBook", types = { Book.class })
public interface CustomBook {
#Value("#{target.id}")
long getId();
}
credit: https://www.baeldung.com/spring-data-rest-projections-excerpts

Why i get java.lang.IllegalArgumentException: error at ::0 can't find referenced pointcut getLogging

I get this exception on the title. I give some code following:
#Component("student")
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void printSomething() {
// get logging with aop
System.out.println("student printed something");
// get logging with aop
}
}
#Aspect
#Component
public class StudentLogging {
private final static Logger logger = Logger.getLogger(StudentLogging.class.getName());
#Pointcut("execution(* aspectorientedprog.aopexample.Student.printSomething(..))")
private void getLogging() {
}
#Around("getLogging()")
public String aroundPrintSomething(ProceedingJoinPoint joinPoint) throws Throwable {
logger.info("before printing something");
Object o = joinPoint.proceed();
logger.info("after printing something");
return o.toString();
}
}
public class AspectStudentTest {
#Test
public void aspect_student_test() {
ApplicationContext context = new ClassPathXmlApplicationContext("aspect/aspect-conf.xml");
Student student = context.getBean("student", Student.class);
student.printSomething();
System.out.println();
}
}
my configuration file:
<context:annotation-config/>
<context:component-scan base-package="aspectorientedprog"/>
<aop:aspectj-autoproxy/>
I research something about this error, but all solutions are not worked, it was about AOP version. if i use only
#Around(execution("class"))
it is working truly but if i use the #Pointcut and #Around like above i got this problem...
thanks for your answers
Try with:
#Pointcut("execution(* aspectorientedprog.aopexample.Student.printSomething(..))")
public void getLogging() {
}

GWT + Spring + Hiberante. With no reason at all

I'm learning how to integrate Spring with GWT and RequestFactory by doing this following example. I got a NullPointerException and I don't know why. Can anyone help me?
Here is my code:
#Repository
public class EmployeeDAO implements IEmployeeDAO {
#PersistenceContext
private EntityManager entity;
#Override
public Employee findById(Long id) {
Query query = entity.createQuery("from Employee where id = :param");
query.setParameter("param", id);
query.setMaxResults(1);
return (Employee) query.getSingleResult();
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public void save(Employee employee) {
entity.merge(employee);
}
#Override
public void remove(Employee employee) {
entity.remove(employee);
}
#SuppressWarnings("unchecked")
#Override
public List<Employee> getAllEmployee() {
Query query = entity.createQuery("from Employee");
return query.getResultList();
}
// ...
}
and:
#Service(value = IEmployeeDAO.class, locator = DaoLocator.class)
public interface EmployeeRequestContext extends RequestContext {
Request<EmployeeProxy> findById(Long id);
Request<Void> save(EmployeeProxy employee);
Request<Void> remove(EmployeeProxy employee);
Request<List<EmployeeProxy>> getAllEmployee();
Request<EmployeeProxy> findOneByName(String name);
}
and:
#ProxyFor(Employee.class)
public interface EmployeeProxy extends EntityProxy {
Long getId();
String getName();
String getSurname();
void setId(Long id);
void setName(String name);
void setSurname(String surname);
Long getVersion();
void setVersion(Long version);
}
The NullPointerException is throw in GWT Entry Point in method:
protected void refresh() {
context = createFactory().employeeRequest();
final EmployeeProxy ep = context.create(EmployeeProxy.class);
ep.setName("Jan");
ep.setSurname("Kowalski");
ep.setVersion(new Long(0));
context.save(ep).fire(new Receiver<Void>() {
#Override
public void onSuccess(Void response) {
employeeList.add(ep);
}
#Override
public void onFailure(ServerFailure error) {
System.out.println("error podczas zapisu");
}
});
context = createFactory().employeeRequest();
context.getAllEmployee().fire(new Receiver<List<EmployeeProxy>>() {
#Override
public void onSuccess(List<EmployeeProxy> response) {
System.out.println(" " + response); // NULL
}
#Override
public void onFailure(ServerFailure error) {
}
});
System.out.println("Bedziemy wyswietlac dane!");
updateTable(employeeList);
}
the last one: method which create Factory:
private static EmployeeRequestFactory createFactory() {
EmployeeRequestFactory factory = GWT.create(EmployeeRequestFactory.class);
factory.initialize(new SimpleEventBus());
return factory;
}
Please help me...
Please print the stacktrace for the NullPointerException. Only then can we analyze the cause for the exception.

Resources