Why association resource is not binding - spring-data-rest

I am using spring data rest. When I try to create a resource using post method with application/json using following object, association resources are not binded although they are already present in db
{
screeName : 'adsaf',
screenType : {
screenTypeId : 1,
screenTypeName : 'Fixed'
}
}
Why? Is there anyother way of accomplishing this task other than separately setting associations? I am asking this question because if I manually receive this form in a controller and use ObjectMapper to deserialize and then save this object, all associations would be set. Then why its not happening in spring data rest

Spring Data REST works with links to resources so you have to change your payload to something like this:
POST http://localhost:8080/api/screens
{
"screenName": "adsaf",
"screenType": "http://localhost:8080/api/screenTypes/1"
}
If you need to save ScreenType when you POST Screen object too, you should turn off the exporting of your ScreenType repository:
#RepositoryRestResource(exported = false)
public interface ScreenTypeRepo extends JpaRepository<ScreenType, ...> {
}
and add cascading (at least PERSIST) to your screenType field in Screen entity:
public class Screen {
//...
#ManyToOne(cascade = CascadeType.PERSIST)
ScreenType screenType;
}
That's mean that ScreenType will be managed by Screen. In this case you would be able to use a payload like this:
POST http://localhost:8080/api/screens
{
"screenName": "adsaf",
"screenType": {
"screenTypeName": "Fixed"
}
}
to create a new ScreenType simultaneously with Screen.

This can be done using Custom HttpMessageConverter. check following thread.
Creating Resource with references using spring data rest

Related

Import variables into aurelia-dialog view-model or view

Is there a way to import additional variables/data from the dialog-service to the controller?
For example I have an array of possible options in a form of my app-view. I fetch the data via an API from a server.
I'd like to edit an entry with an aurelia-dialog and don't want to fetch the data again to avoid unnecessary traffic in my app.
How can i pass the array additionally to the model. Pack it all together in an Object and unwrap it in the controller?
As far as I know the activate-method of the controller only takes one argument, doesn't it?
Thank you
Isn't the example in the repository exactly what you are looking for?
The person attribute is passed to the dialog service via the settings object (model: this.person). This may be data you fetched from the server. As you mentioned, you can of course add multiple objects to the model as well which will be available in the activate() method of your dialogs vm.
import {EditPerson} from './edit-person';
import {DialogService} from 'aurelia-dialog';
export class Welcome {
static inject = [DialogService];
constructor(dialogService) {
this.dialogService = dialogService;
}
person = { firstName: 'Wade', middleName: 'Owen', lastName: 'Watts' };
submit(){
this.dialogService.open({ viewModel: EditPerson, model: this.person}).then(response => {
if (!response.wasCancelled) {
console.log('good - ', response.output);
} else {
console.log('bad');
}
console.log(response.output);
});
}
}

Authentication views for Laravel 5.1

Laravel 5.1 has just been released, I would like to know how could I tell the AuthController to get the login & register view from a custom directory? the default is: resources/views/auth...
The trait AuthenticateAndRegisterUsers only has this:
trait AuthenticatesAndRegistersUsers
{
use AuthenticatesUsers, RegistersUsers {
AuthenticatesUsers::redirectPath insteadof RegistersUsers;
}
}
The code you're showing there only fills one function: it tells our trait to use the redirectPath from the AuthenticatesUsers trait rather than the one from RegistersUsers.
If you check inside the AuthenticatesUsers trait instead, you will find a getLogin() method. By default, this one is defined as
public function getLogin()
{
return view('auth.login');
}
All you have to do to get another view is then simply overwriting the function in your controller and returning another view. If you for some reason would like to load your views from a directory other than the standard resources/Views, you can do so by calling View::addLocation($path) (you'll find this defined in the Illuminate\View\FileViewFinder implementation of the Illuminate\View\ViewFinderInterface.
Also, please note that changing the auth views directory will do nothing to change the domain or similar. That is dependent on the function name (as per the definition of Route::Controller($uri, $controller, $names=[]). For more details on how routing works, I'd suggest just looking through Illuminate\Routing\Router.
for those who is using laravel 5.2, you only need to override property value of loginView
https://github.com/laravel/framework/blob/5.2/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php
public function showLoginForm()
{
$view = property_exists($this, 'loginView')
? $this->loginView : 'auth.authenticate';
if (view()->exists($view)) {
return view($view);
}
return view('auth.login');
}
so to override the login view path, you only need to do this
class yourUserController {
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
.....
protected $loginView = 'your path';
}

How to add links to resources without any entities in Spring Data Rest

I have a very loosely couplet system that takes about any json payload and saves in a mongo colection.
There are no entities to expose as resouces, but only controller endpoints
eg.
#RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> publish(#RequestBody Map<String, Object> jsonBody) {
.. save the body in mongo
....}
I still want to build a hypermedia driven app. with links for navigation and paging.
The controller therefor implements ResourceProcessor
public class PublicationController implements ResourceProcessor<RepositoryLinksResource> {
....
#Override
public RepositoryLinksResource process(RepositoryLinksResource resource) {
resource.add(linkTo(methodOn(PublicationController.class).getPublications()).withRel("publications"));
return resource;
}
The problem is that the processor never gets called ??
Putting #EnableWebMvc on a configuration class solves it (the processor gets called), but firstly that should not be necessary, and secondary the format of HAL links seems broken
eg. gets formattet as a list
links: [
{
"links":[
{
"rel":"self",
"href":"http://localhost:8080/api/publications/121212"
},
{
"rel":"findByStartTimeBetween",
"href":"http://localhost:8080/api/publications/search/findStartTimeBetween?timeStart=2015-04-10T13:44:56.437&timeEnd=2015-04-10T13:44:56.439"
}
]
}
Are there alternatives to #enableWebMvc so the processor gets called ?
Currently I'm running Spring boot v. 1.2.3
Well it turns out that the answer was quite simple.
The problem was that I had static content (resources/static/index.html)
This will suppress the hypermedia links from the root.
Moving the static content made everything thing work great.

Understanding cakephp3 error handling

I want to create a maintenance Page for my cake website by checking a Database Table for a maintenance flag using a sub-function of my AppController "initilize()" method. If the flag is set, i throw my custom MaintenanceException(Currently containing nothing special):
class MaintenanceException extends Exception{
}
To handle it, I implemented a custom App Exception Renderer:
class AppExceptionRenderer extends ExceptionRenderer {
public function maintenance($error)
{
return "MAINTENANCE";
}
}
I am able to see this maintenance Text on my website if I set my DB flag to true, but I could not find any information in cake's error handling documentation (http://book.cakephp.org/3.0/en/development/errors.html) on how I can actually tell the Exception renderer to render view "maintenance" with Template "infopage".
Can I even us that function using the ExceptionRenderer without a custom error controller? And If not, how should a proper ErrorController implementation look like? I already tried this:
class AppExceptionRenderer extends ExceptionRenderer {
protected function _getController(){
return new ErrorController();
}
public function maintenance($error)
{
return $this->_getController()->maintenanceAction();
}
}
together with:
class ErrorController extends Controller {
public function __construct($request = null, $response = null) {
parent::__construct($request, $response);
if (count(Router::extensions()) &&
!isset($this->RequestHandler)
) {
$this->loadComponent('RequestHandler');
}
$eventManager = $this->eventManager();
if (isset($this->Auth)) {
$eventManager->detach($this->Auth);
}
if (isset($this->Security)) {
$eventManager->detach($this->Security);
}
$this->viewPath = 'Error';
}
public function maintenanceAction(){
return $this->render('maintenance','infopage');
}
}
But this only throws NullPointerExceptions and a fatal error. I am really dissapointed by the cake manual as well, because the code examples there are nowhere close to give me an impression of how anything could be done and what functionality I actually have.
Because I had some more time today, I spent an hour digging into the cake Source and found a solution that works well for me (and is propably the way it should be done, altough the cake documentation does not really give a hint):
Step 1: Override the _template(...)-Method of the ExceptionRenderer in your own class. In my case, I copied the Method of the parent and added the following Code at the beginning of the method:
$isMaintenanceException = $exception instanceof MaintenanceException;
if($isMaintenanceException){
$template = 'maintenance';
return $this->template = $template;
}
This tells our Renderer, that the error Template called "maintentance"(which should be located in Folder: /Error) is the Error Page content it should render.
Step 2: The only thing we have to do now (And its is kinda hacky in my opinion, but proposed by the cake documentation in this exact way) is to set the layout param in our template to the name of the base layout we want to render with. So just add the following code on top of your error template:
$this->layout = "infopage";
The error controller I created is actually not even needed with this approach, and I still don't know how the cake error controller actually works. maybe I will dig into this if I have more time, but for the moment.

How do I get Xtext's model from a different plugin?

I've written an Xtext-based plugin for some language. I'm now interested in creating a new independent view (as a separate plugin, though it requires my first plugin), which will interact with the currently-active DSL document - and specifically, interact with the model Xtext parsed (I think it's called the Ecore model?). How do I approach this?
I saw I can get an instance of XtextEditor if I do something like this when initializing my view:
getSite().getPage().addPartListener(new MyListener());
And then, in MyListener, override partActivated and partInputChanged to get an IWorkbenchPartReference, which is a reference to the XtextEditor. But what do I do from here? Is this even the right approach to this problem? Should I instead use some notification functionality from the Xtext side?
Found it out! First, you need an actual document:
IXtextDocument doc = editor.getDocument();
Then, if you want to access the model:
doc.modify(new IUnitOfWork.Void<XtextResource>() { // Can also use just IUnitOfWork
#Override public void process(XtextResource state) throws Exception {
...
}
});
And if you want to get live updates whenever it changes:
doc.addModelListener(new IXtextModelListener() {
#Override public void modelChanged(XtextResource resource) {
for (EObject model : resource.getContent()) {
...
}
}
});