cors in spring boot app - javascript

I have a table called student with column name, password, domain.
I have a method in my controller that provides token to student for getting some resources.
#CrossOrigin(origins = "*")
#RequestMapping(value = "/getToken")
public String provideToken() {
return "tokenvalue"
}
In the database, there are multiple students and multiple student have different domain that calls the above method. E.g.
something.com/provideToken?username="user"&password="pass"
In different domain there is a page that calls the above url.
Now, How do i make sure that only those domain that are in the database can access above provideToken function.
public static void main(String[] args) throws InterruptedException {
SpringApplication.run(Application.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
List<User> allUsers = userDao.findAll();
List<String> originList = new ArrayList<>();
for(User user: allUsers) {
originList.add(user.getDomainName());
}
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = new String[originList.size()];
origins = originList.toArray(origins);
registry.addMapping("/getToken").allowedOrigins(origins);
}
};
}

You can use a WebMvcConfigurer for programmatic configuration of origins per mapping:
#SpringBootApplication
#RestController
public class MySpringBootApplication {
#Autowired
private MyDatabase myDatabase;
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
String[] origins = myDatabase.getAllowedOriginsForGetToken(); // example
registry.addMapping("/getToken").allowedOrigins(origins);
}
};
}
...
As you can see, it allows you to go to the database (or any other source) for getting the origins information.

Related

How to change the property of a specific object when buttonclick occurs, using a PUT-method (JSON) in react and springboot

I have made some code inside of the spring boot back-end application which allows me to change a property of a specific object, this property which needs to be changed is the "status" property:
#Entity
public class Pakketje {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int code;
private String status = "In magazijn";
public Pakketje() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
To change the property of that object, i will need to state the ID of that object (i think) inside of the react frontend application, and then fetch the PUT-method.
I will show you the method to change the property inside of my spring boot back-end application, this method can be found in the 'Service' class. 'bestaandPakketje' means existing pakketje.
#Override
public Pakketje getPakketjeById(int id) {
return pakketjeRepository.findById(id).orElse(null);
}
#Override
public Pakketje statusOnderweg(Pakketje pakketje) {
Pakketje bestaandPakketje = pakketjeRepository.findById(pakketje.getId()).orElse(null);
bestaandPakketje.setStatus(pakketje.getStatus());
return pakketjeRepository.save(bestaandPakketje);
}
}
And here is the controller:
public class PakketjeController {
#SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
#Autowired
private PakketjeService pakketjeService;
#PostMapping("/add")
public String add(#RequestBody Pakketje pakketje) {
pakketjeService.pakketjeOpslaan(pakketje);
return "Pakketje opgeslagen!";
}
#GetMapping("/getAll")
public List<Pakketje> getAllePakketjes(){
return pakketjeService.getAllePakketjes();
}
#GetMapping("/getById/{id}")
public Pakketje findPakketjeById(int id) {
return pakketjeService.getPakketjeById(id);
}
#PutMapping("/updateOnderweg")
public Pakketje statusIsOnderweg(#RequestBody Pakketje pakketje) {
return pakketjeService.statusOnderweg(pakketje);
}
}
Now the next step is verry hard for me. Each 'pakketje' has his own button which can be clicked to change the property (I will upload the picture so please check it). When that button is clicked the property automatically should change from "In magazijn "to "onderweg".
I would appreciate some help!

Getting null values in postman while fetching data from database using springboot although data is present in database, through userId/categoryId

I am trying to create a blog apis but Getting null values in postman while fetching data from database although data is present in database using springboot, when i am trying to get data by userId or categoryId. it's giving me null value as shown.
{ "postTitle": null, "postContent": null, "postImageName": null,
"postAddedDate": null, "category": null, "user": null }
// Controller Class
#RestController
#RequestMapping("/api/")
public class PostController {
#Autowired
private PostService postService;
// create
#PostMapping("/user/{userId}/category/{categoryId}/posts")
public ResponseEntity<PostDto> createPost(#RequestBody PostDto postDto, #PathVariable Integer userId,
#PathVariable Integer categoryId) {
PostDto createdPost = this.postService.createPost(postDto, userId, categoryId);
return new ResponseEntity<PostDto>(createdPost, HttpStatus.CREATED);
}
// get post by user
#GetMapping("/user/{userId}/posts")
public ResponseEntity<List<PostDto>> getPostByUser(#PathVariable Integer userId) {
List<PostDto> posts = this.postService.getPostByUser(userId);
return new ResponseEntity<List<PostDto>>(posts, HttpStatus.OK);
}
// get post by category
#GetMapping("/category/{categoryId}/posts")
public ResponseEntity<Set<PostDto>> getPostByCategory(#PathVariable Integer categoryId) {
Set<PostDto> posts = this.postService.getPostByCategory(categoryId);
return new ResponseEntity<Set<PostDto>>(posts, HttpStatus.OK);
}
}
//Post Entity Class
#Entity
#Table(name = "post")
#Getter
#Setter
#NoArgsConstructor
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer postId;
private String postTitle;
#Column(length = 10000)
private String postContent;
private String postImageName;
private Date postAddedDtae;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
#ManyToOne
private User user;
}
//Post Dto Class
#Getter
#Setter
#NoArgsConstructor
public class PostDto {
private String postTitle;
private String postContent;
private String postImageName;
private Date postAddedDate;
private CategoryDto category;
private UserDto user;
}
//Post Repo class
public interface PostRepo extends JpaRepository<Post, Integer> {
List<Post> findByUser(User user);
Set<Post> findByCategory(Category category);
}
//Post Service Class
public interface PostService {
// create
PostDto createPost(PostDto postDto, Integer userId, Integer categoryId);
// update
Post updatePost(PostDto postDto, Integer posId);
// getAll
List<PostDto> getAllPost();
// getSinglepost
Post getPostByid(Integer PostId);
// Delete
void deletePost(Integer postId);
// getPOstByCategory
Set<PostDto> getPostByCategory(Integer categoryId);
// getAllPostByUser
List<PostDto> getPostByUser(Integer userId);
// Search Post
List<PostDto> searchPosts(String keyword);
}
//Post ServiceImplmentation class
#Service
public class PostServiceImpl implements PostService {
#Autowired
private PostRepo postRepo;
#Autowired
private ModelMapper modelMapper;
#Autowired
private UserRepo userRepo;
#Autowired
private CategoryRepo categoryRepo;
#Override
public PostDto createPost(PostDto postDto, Integer userId, Integer categoryId) {
User user = this.userRepo.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User", "User Id", userId));
Category category = this.categoryRepo.findById(categoryId)
.orElseThrow(() -> new ResourceNotFoundException("Category", "Category Id", categoryId));
Post post = this.modelMapper.map(postDto, Post.class);
post.setPostImageName("Default.png");
post.setPostAddedDtae(new Date());
post.setUser(user);
post.setCategory(category);
Post newPost = this.postRepo.save(post);
return this.modelMapper.map(newPost, PostDto.class);
}
#Override
public Post updatePost(PostDto postDto, Integer posId) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<PostDto> getAllPost() {
// TODO Auto-generated method stub
return null;
}
#Override
public Post getPostByid(Integer PostId) {
// TODO Auto-generated method stub
return null;
}
#Override
public void deletePost(Integer postId) {
// TODO Auto-generated method stub
}
#Override
public Set<PostDto> getPostByCategory(Integer categoryId) {
Category cat = this.categoryRepo.findById(categoryId)
.orElseThrow(() -> new ResourceNotFoundException("Category", "Category Id", categoryId));
Set<Post> posts = this.postRepo.findByCategory(cat);
Set<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(posts, PostDto.class))
.collect(Collectors.toSet());
return postDtos;
}
#Override
public List<PostDto> getPostByUser(Integer userId) {
User user = this.userRepo.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User", "User Id", userId));
List<Post> posts = this.postRepo.findByUser(user);
List<PostDto> postDtos = posts.stream().map((post) -> this.modelMapper.map(posts, PostDto.class))
.collect(Collectors.toList());
return postDtos;
}
#Override
public List<PostDto> searchPosts(String keyword) {
// TODO Auto-generated method stub
return null;
}
}
Please check and let me know where i am going wrong...

test class is unable to read consul config

I have test code in which I want to read configurations from consul.The application.properties (src/main/resources) enables the consul config. And I have one POJO class name DBConfig (in src/main/java) which gets the configuration from consul. I have autowired the DBConfig in test class and when I'm running the unit test it is giving me nullpointerexception as it is not getting the values from consul.
How to handle the situation. Please help.
#Configuration
#ConfigurationProperties(prefix="db")
#RefreshScope
public class DBConfig {
private String jdbcURL;
private String username;
private String password;
private String driverClass;
...getter setters.
}
Test Class---
#RunWith(MockitoJUnitRunner.class)
#Transactional(propagation=Propagation.REQUIRED,readOnly=false,rollbackFor=Exception.class)
#SpringBootTest(classes={DBConfig.class})
public class TestUserDao extends DBTestCase {
#Autowired
private DBConfig dbConfig;
protected final Resource res = new ClassPathResource("actualDataSet.xml");
#Bean
#Profile("test")
#RefreshScope
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbConfig.getDriverClass());
dataSource.setUrl(dbConfig.getJdbcURL());
dataSource.setUsername(dbConfig.getUsername());
dataSource.setPassword(dbConfig.getPassword());
return dataSource;
}
#Bean
#Autowired
public NamedParameterJdbcTemplate jdbcTemplate(DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
#Autowired
public UserDAO userDAO(NamedParameterJdbcTemplate jdbcTemplate) {
return new UserDAO(jdbcTemplate);
}
#Override
protected IDataSet getDataSet() throws Exception {
ClassLoader classLoader = getClass().getClassLoader();
String file = classLoader.getResource("actualDataSet.xml").getFile();
return new FlatXmlDataSetBuilder().build(new FileInputStream(file));
}
protected DatabaseOperation getSetUpOperation() throws Exception {
return DatabaseOperation.REFRESH;
}
#Test
public void insertTodo() throws Exception {
}
protected DatabaseOperation getTearDownOperation() throws Exception {
return DatabaseOperation.DELETE;
}
It may be caused by usage of MockitoJUnitRunner class, which will not load ApplicationContext at startup, which means, your beans won't be accessible.
Once you will use SpringRunner class in #RunWith() annotation, Spring should be able to inject DBConfig bean.

Problems with React when using SignalR

I have the following code that I am implementing with SignalR:
Startup:
[assembly: OwinStartupAttribute("StartupConfiguration", typeof(AGENDA.Startup))]
namespace AGENDA
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var hubConfiguration = new HubConfiguration();
hubConfiguration.EnableDetailedErrors = true;
hubConfiguration.EnableJavaScriptProxies = true;
app.MapSignalR();
}
}
}
Server:
It is where I create the various methods for capturing the server and can receive the information without any problem, however when I send the information from the client, it arrives empty.
public class MensajesHub : Hub
{
private EventModel _model;
private bool _modelUpdated = false;
public void UpdateModel(EventModel clientModel)
{
clientModel.LastUpdatedBy = Context.ConnectionId;
Clients.AllExcept(clientModel.LastUpdatedBy).UpdateMensaje(clientModel);
UpdateMensaje(clientModel);
}
public void UpdateMensaje(EventModel clientModel)
{
_model = clientModel;
_modelUpdated = true;
}
[HubMethodName("EnviarMensajes")]
public static void EnviarMensajes()
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<MensajesHub>();
context.Clients.All.updateMessages();
}
}
It is where I create the various methods for capturing the server and can receive the information without any problem, however when I send the information from the client, it arrives empty.
public class EventModel
{
[JsonProperty("id_cita")]
public long Id_Cita { get; set; }
[JsonProperty("descripcion_cita")]
public string Descripcion_Cita { get; set; }
[JsonProperty("start")]
public DateTime Start { get; set; }
[JsonProperty("end")]
public DateTime End { get; set; }
[JsonProperty("id_recurso")]
public long Id_Recurso { get; set; }
[JsonProperty("recurso_nombre")]
public string Recurso_Nombre { get; set; }
[JsonProperty("categoria")]
public int Categoria { get; set; }
[JsonIgnore]
public string LastUpdatedBy { get; set; }
}
Client:
I establish the connection with SignalR in this way, which is successful.
//SignalR Code
let mensajes = $.hubConnection();
//let mensajes = connection;
console.log(mensajes);
conexion = this.props.mensajes;
console.log(conexion);
conexion.start()
.done(function (model) {
conexion.logging = true;
console.log(conexion);
console.log('Now connected, connection ID=' + conexion.id);
updateServerModel();
})
.fail(function () {
conexion.hub.logging = false;
console.log(conexion);
console.log('Could not connect');
});
This is where I have the conflict, at first, it brings me the methods of the server, but I can not make the client to pass to the server.
function updateServerModel() {
console.log(conexion);
conexion.server.updateMensaje();
console.log(conexion);
conexion.server.updateModel();
console.log(conexion);
console.log(conexion.server);
console.log(conexion);
}
console.log(conexion);
//-------------------------------------
But the lines that say Server, never reaches anything, since it says that they are not a function
Any idea that this may happen ... ??? Could anyone help me with this ... ???
Thanks since now....!!!!

GWT Cannot read property 'example' of undefined

I'm learning GWT and currently I'm struggeling with RPC. I have a simple Project: a Label, a Textbox, an outputLabel and a Button.
I want when the user enters his Name in the TextBox and press the "send" Button he will get a Message from the Server "Hello "+name+"Here speaks the Server" - stupid example.
However in my CLient I have a package GUI and a Package Service and my entrypoint class
public class TestGwt270 implements EntryPoint {
public void onModuleLoad()
{
TestGwt270ClientImpl clientImpls = new TestGwt270ClientImpl("/TestGwt270/testgwt270service");
GWT.log("Main "+GWT.getModuleBaseURL() );
RootPanel.get().add(clientImpls.getMainGUI());
}
MyGui:
public class MainGUI extends Composite
{
private TestGwt270ClientImpl serviceImpl;
private VerticalPanel vPanel;
private TextBox inputTB;
private Label outputLbl;
public MainGUI(TestGwt270ClientImpl serviceImpl)
{
this.vPanel = new VerticalPanel();
initWidget(vPanel);
this.inputTB = new TextBox();
this.inputTB.setText("Gib deinen Namen ein");
this.outputLbl = new Label("Hier kommt der output");
this.vPanel.add(this.inputTB);
this.vPanel.add(this.outputLbl);
Button sendBtn = new Button("send");
sendBtn.addClickHandler(new MyClickhandler());
this.vPanel.add(sendBtn);
}
public void updateOutputLbl(String output)
{
this.outputLbl.setText(output);
}
private class MyClickhandler implements ClickHandler
{
#Override
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
serviceImpl.sayHello(inputTB.getText());
}
}
}
TheService:
#RemoteServiceRelativePath("testgwt270service")
public interface TestGwt270Service extends RemoteService
{
String sayHello(String name);
}
AsyncService:
public interface TestGwt270ServiceAsync
{
void sayHello(String name, AsyncCallback<String> callback);
}
ClientInterface:
public interface TestGwt270ServiceClientInt
{
void sayHello(String name);
}
Client Implementation:
public class TestGwt270ClientImpl implements TestGwt270ServiceClientInt
{
private TestGwt270ServiceAsync service;
private MainGUI maingui;
public TestGwt270ClientImpl(String url)
{
GWT.log(url);
// TODO Auto-generated constructor stub
this.service = GWT.create(TestGwt270Service.class);
ServiceDefTarget endpoint = (ServiceDefTarget) this.service;
endpoint.setServiceEntryPoint(url);
this.maingui = new MainGUI(this);
}
public MainGUI getMainGUI()
{
return this.maingui;
}
#Override
public void sayHello(String name) {
// TODO Auto-generated method stub
this.service.sayHello(name, new MyCallback());
}
private class MyCallback implements AsyncCallback<String>
{
#Override
public void onFailure(Throwable arg0) {
// TODO Auto-generated method stub
GWT.log("Failure");
maingui.updateOutputLbl("An Error has occured");
}
#Override
public void onSuccess(String arg0) {
// TODO Auto-generated method stub
GWT.log("Success");
maingui.updateOutputLbl(arg0);
}
}
}
ServerSideCode:
public class TestGwt270ServiceImpl extends RemoteServiceServlet implements TestGwt270Service
{
#Override
public String sayHello(String name) {
// TODO Auto-generated method stub
GWT.log("Hello " + name + "\nHier spricht der Server mit dir");
return "Hello " + name + "\nHier spricht der Server mit dir";
}
}
My Problem is, when I press the Button to send my Name to the server I get following Error:
HandlerManager.java:129 Uncaught com.google.gwt.event.shared.UmbrellaException: Exception caught: (TypeError) : Cannot read property 'sayHello_2_g$' of undefined
I don't know where this Error comes from and I hope you can help me.
I found the answer myself - I made a simple mistake:
In the class MyGUI I got this:
public class MainGUI extends Composite
{
private TestGwt270ClientImpl serviceImpl;
...
public MainGUI(TestGwt270ClientImpl serviceImpl)
{
...
I forgot to assign the serviceImpl
the Fix:
public class MainGUI extends Composite
{
private TestGwt270ClientImpl serviceImpl;
...
public MainGUI(TestGwt270ClientImpl serviceImpl)
{
this.serviceImpl = serviceImpl; //this line is the solution to my problem
...

Categories

Resources