How to dynamically update the attributes of a model in Spring MVC? - java

so I'm pretty new to Spring and used the Spring Initializr to create a new project. I do not have any configuration .XMLs or similiar configuration files. I followed this tutorial to get things going.
My controller class basically looks like the following:
#Controller
#Configuration
#EnableScheduling
public class IndexController {
#GetMapping("/")
public String index(Model m) {
m.addAttribute("Title", "New Website");
m.addAttribute("MenuOne", InformationProvider.getMenuOneLink());
m.addAttribute("MenuTwo", InformationProvider.getMenuTwoLink());
m.addAttribute("StaffNumber", InformationProvider.getNumberOfStaff());
m.addAttribute("Birthdays", InformationProvider.getBirthdaysOfToday());
return "dashboard";
}
}
This works fine and everything is doing what it is supposed to be. Unfortunately the attributes which are getting their data by the InformationProvider class need to be updated at run time. The InformationProvider is approaching different APIs on the web and my idea either was to pull data from these APIs every 10 hours for example or to pull the data again on a site refresh.
From my understanding my method is supposed to be called each time someone would enter the URL localhost:8080/. My first idea basically was to refresh the site after 10 hours. The method is called when the site is refreshed and it is returning "dashboard" each time but the values are not updated. To update my attributes I have to restart my application. I was looking at the #scheduled annotation but this does not really help me since it is only working for methods which have void as return time and do not have object parameters. So scheduling my method index doesn't work and is probably the wrong way to go anyway.
I was googling a lot regarding this topic but I couldn't really find a solution for this specific problem where you only have a model as parameter in your controller method and want to update it afterwards.
What is the best approach for this problematic? I was checking the JavaDoc of the model class but it does not contain a remove or update method. Do I need to approach the HashMap behind the model directly and overwrite an attribute by an existing key to update it?
Edit:
To be more specific about the InformationProvider class, it is basically returning a String received by a cURL method called from Java. Nothing more.
Thanks in advance

InformationProvider class need to be updated at run time
If you tried to Schedule this exact method, its possible that due to InformationProvider class being a static class, it serves the data when it was first initialized. It's hard to tell without seeing what happens in that class. I would rather #Schedule a Service that populates this Object, or rather from a storage, where you can read the cached data.
Regarding your real problem, fetching from different sources.
#Schedule is good for running jobs, but I would avoid, unless you need to cache the data in your server. If it's possible, you can do it live, always fresh data, and easier.
In general for the problem.
I would fetch the data (cache is speed is crucial), with a service that you can Schedule, but have other controls over it for e.g. force refresh from another endpoint, do transformation on server side, and stream it to your page via the model. That should be the basic flow.

The solution for this problem was pretty simple, I just had to refresh the page for example by javascript. Might be as well be able to do this by scheduling.

Related

Is it a good idea to call PUT from POST method

I have to automate certain operations of PUT/POST operation in my case, I have those endpoints already-in-place which will do their part.
My planning is to have another method which will drive this whole automation, consider this method as new POST endpoint which would gonna call each either POST and PUT endpoint from the same service which I already mentioned.
I will gonna call those existing PUT and POST based on input, if consider the input is new I will call existing POST and if given input exists in database I will going to call PUT.
Till I am good, But I have a question in my mind, Which is bugging me a lot that my new endpoint which is of POST is calling PUT as well as POST, I each method type has to do its type of operations only but here I am calling PUT as well as POST whereas my parent calling method type is POST.
I am not sure if I am working in right direction to achieve my use-case.
Please correct me in a different way.
Note - I am having Spring Boot application which would always need some endpoint to trigger any logic which I am talking about.
Update my question for better understanding.
I dont really know what you mean exactly. The HTTP methods are considered to do a specific task, but yet again its ok to use POST to update something - might be not best practice, but works. If you want to seperate the concerns (adding, updating), then just implement two different endpoints, one handling the creation the other one the update. The client (whether its a web-app or desktop app or whatever) has to handle this issue.

List of all mapped RequestMapping values

Does Spring 4 keep an internal record of the mappings that are specified with #RequestParam? I am looking for a list of these mappings.
For example, if I annotate a method with:
#RequestMapping(value = "/myname", method = RequestMethod.POST)
I would want a list with myname.
I looked around a bit and I know about the Spring MVC Router project but I am simply looking for a method call that would return the mappings. Or alternatively, a list of all the paths registered with <mvc:view-controller/> would work too.
Background:
We have a business requirement to create public areas on our web application, similar to the tumblr model where you can have myname.domain.com and access an area created by that user. However, our method is using domain.com/myname since programmatically creating the former was not simple (would need to monkey with DNS/web server config files).
We extended GenericFilterBean to do this, but I want to make sure that when searching for 'myname,' the application can ignore actual pages (or more specifically, views) on the site. We want the front-end validation to disallow existing page names.
I think your question was already answered in here. This is a very good answer.

How to approach JMX Client polling

recently I dove into the world of JMX, trying to instrument our applications, and expose some operations through a custom JMXClient. The work of figuring out how to instrument the classes without having to change much about our existing code is already done. I accomplished this using a DynamicMBean implementation. Specifically, I created a set of annotations, which we decorate our classes with. Then, when objects are created (or initialized if they are used as static classes), we register them with our MBeanServer through a static class, that builds a dynamicMBean for the class and registers it. This has worked out beautifully when we just use JConsole or VisualVM. We can execute operations and view the state of fields all like we should be able to. My question is more geared toward creating a semi-realtime JMXClient like JConsole.
The biggest problem I'm facing here is how to make the JMXClient report the state of fields in as close to realtime as I can reasonably get, without having to modify the instrumented libraries to push notifications (eg. in a setter method of some class, set the field, then fire off a JMX notification). We want the classes to be all but entirely unaware they are being instrumented. If you check out JConsole while inspecting an attribute, there is a refresh button at the bottom of the the screen that refreshes the attribute values. The value it displays to you is the value retrieved when that attribute was loaded into the view, and wont ever change without using the refresh button. I want this to happen on its own.
I have written a small UI which shows some data about connection states, and a few field on some instrumented classes. In order to make those values reflect the current state, I have a Thread which spins in the background. Every second or so the thread attempts to get the current values of the fields I'm interested in, then the UI gets updated as a result. I don't really like this solution very much, as its tricky to write the logic that updates the underlying models. And even trickier to update the UI in a way that doesn't cause strange bugs (using Swing).
I could also write an additional section of the JMXAgent in our application side, with a single thread that runs through the list of DynamicMBeans that have been registered, determines if the values of their attributes have change, then pushes a notification(s). This would move the notification logic out of the instrumented libraries, but still puts more load on the applications :(.
I'm just wondering if any of you have been in this position with JMX, or something else, and can guide me in the right direction for a design methodology for the JMXClient or really any other advice that could make this solution more elegant than the one I have.
Any suggestions you guys have would be appreciated.
If you don't want to change the entities then something is going to have to poll them. Either your JMXAgent or the JMX client is going to have to request the beans every so often. There is no way for you to get around this performance hit although since you are calling a bunch of gets, I don't think it's going to be very expensive. Certainly your JMXAgent would be better than the JMX client polling all of the time. But if the client is polling all of the beans anyway then the cost may be exactly the same.
You would not need to do the polling if the objects could call the agent to say that they have been changed or if they supported some sort of isDirty() method.
In our systems, we have a metrics system that the various components used. Each of the classes incremented their own metric and it was the metrics that were wired into a persister. You could request the metric values using JMX or persist them to disk or the wire. By using a Metric type, then there was separation between the entity that was doing the counting and the entities that needed access to all of the metric values.
By going to a registered Metric object type model, your GUI could then query the MetricRegistrar for all of the metrics and display them via JMX, HTML, or whatever. So your entities would just do metric.increment() or metric.set(...) and the GUI would query the metric whenever it needed the value.
Hope something here helps.
Being efficient here means staying inside the mbean server that contains the beans you're looking at. What you want is a way to convert the mbeans that don't know how to issue notifications into mbeans that do.
For watching numeric and string attributes, you can use the standard mbeans in the monitor package. Instantiate those in the mbean server that contains the beans you actually want to watch, and then set the properties appropriately. You can do this without adding code to the target because the monitor package is standard in the JVM. The monitor beans will watch the objects you select for changes and will emit change notifications only when actual changes are observed. Use setGranularityPeriod to tell the monitor beans how often to look at the target.
Once the monitor beans are in place, just register for the MonitorNotifications that will be created upon change.
not a solution per se but you can simplify your polling-event translator JMXAgent implementation using spring integration. It has something called JMX Attribute Polling Channel which seems to fulfill your need. example here

Where do we handle permissions in MVC? At the Controller or Model level?

I'm tinkering with Play! java framework and trying to understand MVC.
Consider this scenario: A blogging app has moderators and users, and both can update posts. Moderators' updates are immediately saved. Users' updates are queued to be approved by a moderator. In MVC, where do we put the logic to determine whether to update or queue the updates?
One way to do it is in the Controller (pseudo-code):
public void function update() {
User user = User.find("byEmail");
if ( user.isModerator() ) {
post.update( args );
}
else {
// save post in a temporary table where it awaits approval.
}
}
Am I right in using this approach or are there better alternatives?
I know that this is quite an old question, but I had the same - so this might be of help:
In my current project, the policy is to layer the authorisation checks. This way, the checks will be done where they fit best:
if it is important for consistancy of the data, checks are done in the model (very rare cases, needs to be set in the API documentation!).
most checks are done at controller level, so most checks are in a single place.
some checks are done in the "View" (this means they controll the JSON output of an API, and this in turn changes behaviour in the front end). These are quite rare, as these are mostly based on data fed from the controller and not querying the user's permissions directly.
I came up with that solution after reading this post. It provides a good summary on why using the controller is a good idea - and what the alternatives are.
The main reason, why I chose the controller as a place for authorisation checks is that it allows the model (and the data it manages) to be independent of application logic - which includes authorisation.
Please keep in mind, that this is totally dependent on what you want to achieve. I just wanted to show what works for me.

Spring - multiple command class with AbstractWizardFormController

Can i have a AbstractWizardFormController controller with different command class for each page ?
Sounds like a hack to me, but sure --the formBackingObject() method is called for each page, so you can override that method and add code to determine which command object to return (based on which page view is being requested).
On the other hand, that's going to add complications when you handle each pages submission -- will you have to figure out which type of object you're getting and cast? I'd rethink -- maybe this isn't really a wizard-type situation and you should have separate controllers? Or perhaps you should look at Web Flow? My experience is that the Wizard controller is useful if you're using it as envisioned, but when you start trying to squeeze it into a scenario it's not meant for, it becomes more complicated than helpful.

Categories