I'm developing a project using GAE. I'm writing an integration test with Junit which don't save the entity. I have included the JARs in classpath and I copy here the entity class, the test class and the persistence.xml file.
Persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
<persistence-unit name="transactions-optional">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
</properties>
</persistence-unit>
</persistence>
Utente.java
package it.bfm.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.google.appengine.api.datastore.Key;
#Entity
public class Utente {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Key key;
private String nome;
private String cognome;
private String username;
private String password;
private String email;
public Utente(String nome, String cognome, String user, String password,
String email){
this.nome = nome;
this.cognome = cognome;
this.username = user;
this.password = password;
this.email = email;
}
public Key getKey(){
return this.key;
}
public void setNome(String nome){
this.nome = nome;
}
public String getNome(){
return this.nome;
}
public void setCognome(String cognome){
this.cognome = cognome;
}
public String getCognome(){
return this.cognome;
}
public void setUser(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setPassword(String password){
this.password = password;
}
public String getPasswrd(){
return this.password;
}
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return this.email;
}
}
UtenteTest.java
package it.bfm.test;
import it.bfm.business.UtenteImpl;
import it.bfm.business.UtenteInterface;
import it.bfm.entity.Utente;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import junit.framework.TestCase;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
public class UtenteTest extends TestCase{
private final static LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig());
private static UtenteInterface utImpl = new UtenteImpl();
#BeforeClass
public static void setUpUtenti() {
utImpl.creaUtente("Utente1", "Test1", "test1", "test1", "test1#test.it");
utImpl.creaUtente("Utente2", "Test2", "test2", "test2", "test2#test.it");
utImpl.creaUtente("Utente3", "Test3", "test3", "test3", "test3#test.it");
}
#Before
public void setUp(){
helper.setUp();
}
#After
public void tearDown() {
helper.tearDown();
}
#Test
public void testCreaUtente() {
utImpl.creaUtente("Utente4", "Test4", "test4", "test4", "test4#test.it");
}
#Test
public void testListaUtenti() {
List<Utente> utenti = null;
utenti = utImpl.listaUtenti();
Assert.assertEquals(4, utenti.size());
}
#Test
public void testCercaUtenteByEmail() {
Utente utente;
String emailTest = "test1#test.it";
String nomeTest = "Utente1";
String cognomeTest = "Test1";
utente = utImpl.cercaUtenteByEmail(emailTest);
Assert.assertEquals(utente.getNome(), nomeTest);
Assert.assertEquals(utente.getCognome(), cognomeTest);
}
#Test
public void testLogin() {
Utente utente;
String usernameTest = "test1";
String passTest = "test1";
String nomeTest = "Utente1";
String cognomeTest = "Test1";
utente = utImpl.login(usernameTest, passTest);
Assert.assertEquals(utente.getNome(), nomeTest);
Assert.assertEquals(utente.getCognome(), cognomeTest);
}
}
The problem is that the methods setUpUtenti ad testCreaUtente don't persist the entities.
The test testListaUtenti fails because the Utenti numbers was expected 4 but is 0.
Every #Test annotated method is invoked on a freshly created instance of class. So basically you can not persist between methods. You should put this code into one method.
Related
I have just started learning and experimenting with spring-boot and hibernate and there is this problem I can't seem to figure out.
package net.codejava;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.annotation.Rollback;
#DataJpaTest
#AutoConfigureTestDatabase(replace = Replace.NONE)
#Rollback(false)
public class UserRepositoryTests {
#Autowired
private UserRepositoryTests repo;
#Autowired
private TestEntityManager entityManager;
#Test
public void testCreateUser() {
User user = new User();
user.setEmail("xyz#gmail.com");
user.setPassword("XYZ!##");
user.setFirstname("XYZ");
user.setLastname("PQR");
user.setUsername("XZY");
User savedUser = repo.save(user);
User existUser = entityManager.find(User.class, savedUser.getIdUser());
assertThat(user.getEmail()).isEqualTo(existUser.getEmail());
}
}
There is some error with line 38 (i.e,User savedUser = repo.save(user);)
is says that"The method save(User) is undefined for the type UserRepositoryTests"
User.java
package net.codejava;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idUser;
#Column(nullable = false,unique=true,length = 45)
private String email;
#Column(nullable = false,unique=true,length = 45)
private String firstname;
#Column(nullable = false,unique=true,length = 45)
private String lastname;
#Column(nullable = false,unique=true,length = 45)
private String username;
#Column(nullable = true)
private String IPaddress;
#Column(nullable = false,length = 64)
private String password;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIPaddress() {
return IPaddress;
}
public void setIPaddress(String iPaddress) {
IPaddress = iPaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserRepository.java
package net.codejava;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Please let me know what to do.
the problem was UserRepositoryTests it should have been UserRepository.
I'm trying to make a blog using spring boot java with auth.
I created User class the implements UserDetails, and Post class.
When using the path /posts I wish to see all the posts in the blog, problem is that each post contains creator (User obj) and it shows the password of the user - and this is what I'm trying to avoid.
I tried #JsonIgnor, #JsonProperty didn't work
Tried also #JsonProperty(access = Access.WRITE_ONLY) I get an error on the Access.WRITE_ONLY.
Does are the classes:
package com.example.blog.entities;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonProperty;
import javax.persistence.*;
import java.util.Collection;
import java.util.List;
#Entity
#Table(name = "users")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String username;
#JsonIgnore
private String password;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private List<Role> roles;
public User() {}
public User(String username, String password, List<Role> roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
#JsonIgnore
public String getPassword() {
return password;
}
#JsonProperty
public void setPassword(String password) {
this.password = password;
}
public Integer getId() {
return id;
}
}
import javax.persistence.*;
import java.time.LocalDate;
import java.util.Date;
#Entity
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String title;
private String body;
private LocalDate date;
#ManyToOne
private User creator;
public Post() {
}
}
import com.example.blog.entities.Post;
import com.example.blog.entities.User;
import com.example.blog.repositories.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
#Service
public class PostService {
private final PostRepository postRepository;
#Autowired
public PostService(PostRepository postRepository){
this.postRepository = postRepository;
}
public List<Post> getAllPosts(){
return postRepository.findAll();
}
public void insert(Post post) {
if(post.getBody() == null || post.getTitle() == null ){
throw new IllegalArgumentException("Missing args");
}
post.setDate(LocalDate.now());
postRepository.save(post);
}
public List<Post> getPostByUsername(User user){
return postRepository.findByCreatorId(user.getId());
}
}
The endpoint:
#GetMapping(value = "/posts")
public List<Post> posts(){
return postService.getAllPosts();
}
You should not expose your internal data model (JPA). Use transport classes. And you should remove the "#JsonProperty" from "public void setPassword(String password) ...". It is contradicting ("overriding") the "#JsonIgnore". And don't store your password as plaintext! Use for example jBCrypt.
My Setup:
public static class XUser {
private String username;
#JsonIgnore
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
//#JsonProperty
public void setPassword(String password) {
this.password = password;
}
}
#Test
public void testJson() {
XUser user = new XUser();
user.setPassword("oh shit!");
user.setUsername("name");
try {
ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(user));
} catch (Exception ex) {
ex.printStackTrace();
}
}
And the output:
{"username":"name"}
I want retrieve user email from MySql database table using spring boot.i used findByEmailAndPassword in controller but it retrieve null value for email.
Here is my Code
controller
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.JPARepository;
import com.example.demo.pojo.regisbean;
#Controller
public class registerController {
regisbean pp;
#RequestMapping(value = "/")
public String mm() {
System.out.println("I am in m1 method");
return "index";
}
#RequestMapping(value = { "/register", "home" })
public String m1() {
System.out.println("I am in mm method");
return "register";
}
#Autowired
JPARepository jpaRepository;
#PostMapping("/register")
public String regis(#ModelAttribute regisbean rb)
{
System.out.println("I m in regis method");
regisbean b=jpaRepository.save(rb);
if(b!=null)
return "index";
else
return "fail";
}
#RequestMapping(value= {"/login1","login2"})
public String m2() {
System.out.println("i m in m2()");
return "login";
}
#PostMapping("/login")
public String login(#ModelAttribute regisbean rx,Model m) {
System.out.println("I am in Login");
regisbean re=jpaRepository.findByEmailAndPassword(rx.getEmail(), rx.getPassword());
if(re!=null)
{
m.addAttribute("email",rx.getEmail());
m.addAttribute("password",rx.getPassword());
System.out.println("yes");
return "loginsuccess";
}
else
{
System.out.println(rx.getEmail());
System.out.println("failed");
return "register";
}
}
}
pojo class
package com.example.demo.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "pro")
public class regisbean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String name;
#Column
private String email;
#Column
private String phonenumber;
#Column
private String password;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Repository
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.pojo.regisbean;
public interface JPARepository extends CrudRepository<regisbean, Integer> {
public regisbean findByEmailAndPassword(String email,String password);
}
I was able to get your code to work by inserting a row in the table:
INSERT INTO pro (
id
,email
,name
,password
,phonenumber
)
VALUES (
0
,'user#domain.com'
,'Jim'
,'secret'
,'123-123-1234'
)
Then changing:
public String login(#ModelAttribute regisbean rx,Model m) {
to:
public String login(#RequestBody RegisBean rx,Model m) {
and POSTing the following request body to the /login resource:
{
"email": "user#domain.com",
"password": "secret"
}
I didn't have to make any changes to your Repo. I suspect your attempt was failing because RegisBean was never being initialized with any values and so the repo was asked to find a record with a null email and a null password.
This question already has answers here:
Spring Boot Hibernate 5 Ignoring #Table and #Column
(2 answers)
Closed 5 years ago.
I try to use CrudRepository on my work. And When the sql request appear on my log, It's just abnormal.
The real table is 'AllDatabase.AllUserInfo' but the generated sql request look like 'all_user_info alluresinf0_', which is unusable.
I have been all over the internet and nobody seems to face my problem (as far as I know). So please somebody tell me if I'm missing some configuration in my project.
I work on Intellij Idea with 'Spring Initializer' with 'Web' , 'JPA' , 'MySQL' selected. These are my code.
here is my Repository
package com.chuchurest.proj.Repository;
import com.chuchurest.proj.Entity.AllUserInfo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by slimshady23 on 6/25/2017 AD.
*/
#Transactional
#Repository
public interface UserRepository extends CrudRepository<AllUserInfo,String> {
}
here is The 'AllUserInfo' Entity
package com.chuchurest.proj.Entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
/**
* Created by slimshady23 on 6/23/2017 AD.
*/
#Entity
#Table(name = "AllUserInfo")
public class AllUserInfo {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private String Id;
#Column(name="username")
private String Username;
#Column(name="password")
private String Password;
#Column(name="email")
private String Email;
#Column(name="phone")
private String Phone;
#Column(name="rating")
private Integer Rating;
#Column(name="skill")
private Integer Skill;
#Column(name="description")
private String Description;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public Integer getRating() {
return Rating;
}
public void setRating(Integer rating) {
Rating = rating;
}
public Integer getSkill() {
return Skill;
}
public void setSkill(Integer skill) {
Skill = skill;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
And this is how I invoke the save() method
package com.chuchurest.proj.Service;
import com.chuchurest.proj.DAO.UserInfoDAO;
import com.chuchurest.proj.Entity.AllUserInfo;
import com.chuchurest.proj.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by slimshady23 on 6/24/2017 AD.
*/
#Service
public class AppService {
#Autowired
private UserRepository userRepository;
public void PerformRegister(AllUserInfo userinfo)
{
userRepository.save(userinfo);
}
}
And here is the Application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/AllDatabase
spring.datasource.username=root
spring.datasource.password= ******
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.show-sql= true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Note the dot, the difference between schema.tablename and tablename alias
The AllUserInfo_f0 is an alias for AllUserInfo. It's used in Hibernate by default for supporting query relations on the same table multiple times. It doesn't break your sql.
I am new in apache camel. And I wanna do some simple task using apache camel. I have json data available on this url http://localhost:8080/users/. There are json data from my rest service. But I wanna get this json data and unmarshal it to POJO using apache camel and write some data to txt file. But my app starts and then doesnt't stop.
Here is my JSON data available on http://localhost:8080/users/
[{"id":1,"login":"admin","password":"admin","passwordAgain":null,"email":"admin#admin.com","firstName":"Admin","lastName":"Adminovich","birthday":"2010-10-10","role":{"id":1,"name":"admin"}},
{"id":5,"login":"Snow123","password":"1111","passwordAgain":null,"email":"john#snow.com","firstName":"John","lastName":"Snow","birthday":"2010-10-10","role":{"id":2,"name":"user"}}]
spring.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:camel="http://camel.apache.org/schema/spring"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="MyRouteBuilder" class="MyRouteBuilder" init-method="restart">
</bean>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<routeBuilder ref="MyRouteBuilder"/>
</camelContext>
</beans>
MyRouteBuilder
import Mapping.User;
import Mapping.Users;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;
import org.apache.camel.component.restlet.RestletConstants;
import org.apache.camel.model.dataformat.JsonLibrary;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
public class MyRouteBuilder extends RouteBuilder {
private String routePort = null;
private String routeAnswer = null;
public void restart() {
String start = "Route Property Placeholder Example started on port" + " 8080" + "!";
System.out.println(start);
}
public void configure() throws Exception {
from("timer:foo?repeatCount=1").to("http://10.10.34.145:8080/users/").unmarshal().json(JsonLibrary.Jackson, Users.class ).log("STARTED!")
.process(new Processor() {
public void process (Exchange exchange) throws Exception {
Users usersList = exchange.getIn().getBody(Users.class);
exchange.getIn().setBody(usersList.usersList);
System.out.println(usersList.usersList.size());
}
}).to("file:///home/name/username/Desktop/camel.txt").stop();
}
}
User
package Mapping;
import com.google.gson.FieldNamingStrategy;
import java.lang.reflect.Field;
public class User {
public User() {
}
private int id;
private String login;
private String password;
private String passwordAgain;
private String email;
private String firstName;
private String lastName;
private String birthday;
public void setId(int id) {
this.id = id;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public void setPasswordAgain(String passwordAgain) {
this.passwordAgain = passwordAgain;
}
public void setEmail(String email) {
this.email = email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setRole(String role) {
this.role = role;
}
public int getId() {
return id;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getPasswordAgain() {
return passwordAgain;
}
public String getEmail() {
return email;
}
public String getFirsteName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getBirthday() {
return birthday;
}
public String getRole() {
return role;
}
private String role;
}
Users
package Mapping;
import java.util.ArrayList;
import java.util.List;
public class Users {
public List<User> usersList = new ArrayList<User>();
}
Main
import org.apache.camel.main.Main;
public class MainClass {
public static void main(String[] args) {
Main main = new Main();
main.enableHangupSupport();
MyRouteBuilder rb = new MyRouteBuilder();
main.addRouteBuilder(rb);
try {
main.run(args);
} catch (Exception e) {
e.printStackTrace();
}
}
}
In my case I converted JsonData to Java object and created a custom CSV file using following dependencies.
jackson-mapper-asl
jackson-core-asl
You can create simple text file or CSV whatever it is.
This is my route:
from("couchdb:http://localhost:5984/order")
.startupOrder(1)
.process(new JsonToCsvProcessor())
.to("file:/home/r2/Desktop/ofBizFile?fileExist=append&fileName=orders-${date:now:dd-MM-yyyy}.csv");
This is my Processor where I am passing JsonString to ObjectMapper for Pojo:
{
public void process(Exchange exchange)throws Exception{
String jsonString = exchange.getIn().getBody(String.class);
exchange.getOut().setBody(convertJsonToCSV(jsonString).toString());
}
public StringBuilder convertJsonToCSV(String jsonStringArgs){
StringBuilder csvFile = new StringBuilder();
//Here customize data format using append()
.
.
return csvFile;
}
}
If you don't know how to use ObjectMapper this link will help you out.
https://www.youtube.com/watch?v=02X6U81MdJ0&t=1s
Use one of the amounts in json's case: Jackson or Gson
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jackson</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-gson</artifactId>
<version>${camel.version}</version>
</dependency>
I recommend checking the documentation
you can do the unmarshal direct on the route:
unmarshal().json(JsonLibrary.Jackson, MyModel.class)
or you can create a processor:
#Component
public class MyModelUnMarshalProccessor implements Processor {
#Override
public void process(Exchange exchange) throws Exception {
MyModel model = exchange.getIn().getBody(MyModel.class);
exchange.getOut().setBody(model);
exchange.getOut().setHeader("id", body.getId());
}
}
#Autowired
MyModelUnMarshalProccessor myModelUnMarshalProccessor;
from("{{fromServices}}")
.log("${body}")
.process(myModelMarshalProccessor)
good luck