Registering Transaction Event Handlers in neo4j - neo4j

I'm currently using Spring Data with Neo4j and have subclassed the SpringRestGraphDatabase to allow the registration of specific transaction event handlers.
I call the registerTransactionEventHandler method to do so. Unfortunately I always get the following exception:
Caused by: java.lang.UnsupportedOperationException: null
at org.neo4j.rest.graphdb.AbstractRemoteDatabase.registerTransactionEventHandler(AbstractRemoteDatabase.java:52) ~[neo4j-rest-graphdb-1.6.jar:1.6]
at org.neo4j.rest.graphdb.RestGraphDatabase.registerTransactionEventHandler(RestGraphDatabase.java:28) ~[neo4j-rest-graphdb-1.6.jar:1.6]
By looking closely at the AbstractRemote I see that it always throws an exception:
public <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> tTransactionEventHandler ) {
throw new UnsupportedOperationException();
}
The RestGraphDatabase doesn't provide an implementation for the register method hence the exception. I'm not sure what alternatives to use, especially as I'm extending SpringRestGraphDatabase.
Is there a cleaner alternative?
(I'm using v2.1.0.M1)

Yeah,
the exposure of these handlers would be very costly over the network. Depending on what you want to do, I would suggest writing a custom plugin to expose your operations and register what you need via a REST endpoint, see http://docs.neo4j.org/chunked/snapshot/server-plugins.html

Related

On IServiceProvider what are the differences between the GetRequiredService and GetService methods?

What are the differences between IServiceProvider.GetRequiredService() and IServiceProvider.GetService()?
When is it a better idea to use GetRequiredService()?
You should rarely have to call these methods at all, as you should use constructor injection where ever possible.
In rare cases, such as factories or to dynamically instantiate command handlers, you can resolve it yourself.
That being said, you should use GetRequiredService where you require the service. It will throw an exception, when the service is not registered.
GetService on the other side is for optional dependencies, which will just return null when there is no such service registered.
The difference is that GetService<T>() returns null if it can't find the service. GetRequiredService<T>() throws an InvalidOperationException instead.

How to catch exceptions in grails REST controllers

If you use a controller to implement rest APIs, you want to deal with any exception thrown and return a generic or specific well formed REST response.
We can't use global error URL mapping method, as the application has a number of APIs and interfaces with different response requirements, and we also don't know which type of Grails' HTTP error codes will be thrown (e.g don't know if it will be a 400, 422, 500 etc). Also, if we used the error page mappings, we won't be able to put relevant data into the JSON response.
E.g. this will generate a GrailsRuntimeException:
class SomeController {
def payload = request.JSON
def someMethod() {
BigDecimal x = new BigDecimal(payload.notExists)
}
The problem is, it seems impossible to catch any error thrown.
E.g. neither this approach:
def handleRuntimeException(RuntimeException e) {
render("some JSON error message")
}
Nor this approach:
try {
:
}
catch (GrailsRuntimeException e) {
render("some JSON error message")
}
Works - it never catches the error.
Tried GroovyRuntimeException, Exception, MissingMethodException, Throwable etc.
The only solution we can think of is to not do any work in the controller, do everything in a service, where apparently we can catch errors.
This approach:
static mappings = {
"500"(controller: "error")
}
Is not want we need for several reasons:
We have several different APIs in different controllers which would require different response formats.
we also have UI controllers, which would want the default error system which shows the stack trace etc.
We want to handle the error in the controller where the exception happened, so we can clean up, or at least can log or return the stat which only the controller knows.
Have decided the only way is to move all code into services, and do nothing in the controller except pass the request, and render the resultant string. i.e. all parameter handling, especially number conversion, is done in the service.
It's ironic that the solution that you see as suboptimal that you're settling for is exactly what you should always do. This isn't PHP - don't put logic in Controllers (or GSPs).
Services are by default transactional, so they're a great place to put code that writes to the database since that should always happen in a transaction. They're also excellent for business logic whether it's transactional or not, and you can either annotate individual methods with #Transactional to partition the methods into ones that run in a transaction and ones that don't, or split the services into some that are fully transactional and some that aren't.
If you keep all of the HTTP-related code in the controllers, doing the data binding from params, and calling helper classes (services, domain classes, taglibs, etc.) you get a good separation of concerns, and if the service layer doesn't know anything about params, HttpServletRequest, HTTP sessions, etc. then it's easily reusable in other Grails apps and even in non-Grails apps. They'll also be easier to test, since there isn't so much inter-related code that needs to be mocked and otherwise made test-friendly.
Using this approach, the controllers basically become dumb routers, accepting requests, calling helpers to do the real work, and delegating page rendering or response writing, or redirecting or forwarding.
I am very late to answer this, but I think it might help people stumbling and searching for solution.
Here is one of my blogs explaining Custom exception handling in grails and error responses for RESTfull services
Hope this might help someone
I am using grails 3.2.4 and there is no issue as you have explained here. I have moved all business logics inside the service class and catching exceptions by parent controller trait. Here I am handling this exception in another ParentExceptionController trait which is implemented by classes where such exception is occurring from service class. Example:
UserService {
boolean create(Map params) {
throw new InvalidParameterException('some message')
}
UserController implements ParentExceptionController {
UserService userService
userService.create(params.userDetails)
}
trait ParentExceptionController {
Object handleInvalidParameterException(InvalidParameterExceoption exception) {
log.error 'log message'
respond([message: exception.message])
}
first and second both are working in my case.

Localizing validation messages from Domain Objects (Entities)

It's not my intent to engage in a debate over validation in DDD, where the code belongs, etc. but to focus on one possible approach and how to address localization issues. I have the following behavior (method) on one of my domain objects (entities) which exemplifies the scenario:
public void ClockIn()
{
if (WasTerminated)
{
throw new InvalidOperationException("Cannot clock-in a terminated employee.");
}
ClockedInAt = DateTime.Now;
:
}
As you can see, when the ClockIn method is called, the method checks the state of the object to ensure that the Employee has not been terminated. If the Employee was terminated, we throw an exception consistent with the "don't let your entities enter an invalid state" approach.
My problem is that I need to localize the exception message. This is typically done (in this application) using an application service (ILocalizationService) that is imported using MEF in classes that require access to its methods. However, as with any DI framework, dependencies are only injected/imported if the object was instantiated by the container. This is typically not the case with DDD.
Furthermore, everything I've learned about DDD says that our domain objects should not have dependencies and those concerns should be handled external from the domain object. If that is the case, how can I go about localizing messages such as the one shown above?
This is not a novel requirement as a great many business applications require globalization/localization. I'd appreciate some recommendations how to make this work and still be consistent with the goals of a DDD.
UPDATE
I failed to originally point out that our localization is all database driven, so we do have a Localization Service (via the injectable ILocalizationService interface). Therefore, using the static Resources class Visual Studio provides as part of the project is NOT a viable option.
ANOTHER UPDATE
Perhaps it would move the discussion along to state that the app is a RESTful service app. Therefore, the client could be a simple web browser. As such, I cannot code with any expectation that the caller can perform any kind of localization, code mapping, etc. When an exception occurs (and in this approach, attempting to put the domain object into an invalid state is an exception), an exception is thrown and the appropriate HTTP status code returned along with the exception message which should be localized to the caller's culture (Accept-Language).
Not sure how helpful this response is to you, but localization is really a front-end concern. Localizing exceptions messages as per your example is not common practice, as end users shouldn't see technical details such as those described in exception messages (and whoever will be troubleshooting your exceptions probably has a sufficient level English even if it is not their native language).
Of course if necessary you can always handle exceptions and present a localized, user-friendly message to your users in your front-end. But keeping it as a font-end concern should simplify your architecture.
As Clafou said, you shouldn't use exceptions for passing messages to the UI in any way.
If you still insist in doing this, one option is to throw an error code instead of the message
throw new InvalidOperationException("ERROR_TERMINATED_EMPLOYEE_CLOCKIN");
and then, when it happens, do whatever you need to do with the exception (log, look up localization, whatever).
If localisation is important part of the domain/application you should make it a first class citizen and inject wherever it belongs. I am not sure what you mean with "DDD says that our domain objects should not have dependencies" - please explain.
You are correct for trying to avoid adding internal dependencies to your domain model objects.
A better solution would be to handle the action inside of a service method such as:
public class EmployeeServiceImpl implements EmployeeService {
public void ClockEmployeeIn(Employee employee) throws InvalidOperationException {
if (employee.isTerminated()) {
// Localize using a resource lookup code..
throw new InvalidOperationException("Error_Clockin_Employee_Terminated");
}
employee.setClockedInAt(DateTime.Now);
}
}
You can then inject the service using your DI framework at the point where you will be making the clockin call and use the service to insulate your domain objects from changes to business logic.

Resolving multiple services using constructor injection with Windsor in MVC3

I have a controller that takes an instance of ICustomerService. The constructor for one of my implementations (ok, the only implementation atm) takes an array of ICustomerExporter instances.
I'm registering all implementations of ICustomerExporter using the following code:
_container.Register(AllTypes
.FromAssembly(typeof(ICustomerExporter).Assembly)
.BasedOn<ICustomerExporter>().LifestyleSingleton());
And my DefaultCustomerService implementation looks like:
public DefaultCustomerService(ISession session, ICustomerExporter[] exporters)
{
this._session = session;
this._exporters = exporters;
}
However, when I try to run the app, I get the following error:
PM.Services.Implementation.DefaultCustomerService' is waiting for the following
dependencies: - Service 'PM.Services.ICustomerExporter[]' which was not registered.
Well pretty clearly it IS registered, I can even stop in the debugger and verify in the container's component list that the ExcelCustomerExporter implementation is there. So why am I getting this error message?
Looks like you're registering for ICustomerExporter, but I don't know that Windsor will assume that an implementation of ICustomerExporter will always satisfy your ICustomerExporter[] dependency. Have you tried registering a ICustomerExporter[] dependency also?
Just to answer this question for anyone who comes along, when registering multiple services like this, you must do 2 things:
Register the ArrayResolver with the kernel prior to registering types
Make sure to tell the kernel to use the interface as the service base.

Spring Security - Prevent AccessDeniedException from stopping application normal flow

I'm using Spring Secuirty 3 with ACL module. I'm securing the methods with #PreAuthentication annotations using a custom PermissionEvaluator. Its working fine, however every time the PermissionEvaluator returns an ACCESS_DENIED an AccessDeniedException is thrown at some point and this stops the application execution. The desired behaivore will be that when the PermissionEvaluator returns and ACCESS_DENIED, the secured method call is only prevented (skipped) and the rest of the application keeps running normally. Does anyone have an idea on how to achieve this?
If you wrap each call where you want this to happen in a try...catch, you can get this behavior. Basically, since it's an exception, any normal exception handling will apply to it. If your application can handle that exception and continue normally, then do exactly that!
Here's an example of what I mean:
// The 1st method that could be denied but you want to continue execution after
try {
// Call method A that will throw the exception
} catch (/*The exception you expect to be thrown and want to continue after*/){}
// The 2nd method that could be denied but you want to continue execution after
try {
// Call method B that will throw the exception
} catch (/*The exception you expect to be thrown and want to continue after*/){}
etc.
Yes, it does add a lot of overhead to calling those methods, but it is a fairly simple way of allowing execution to continue after an exception is raised.
I would also argue that it is also more correct, since the calling code does know how to deal with those exceptions. This also doesn't require any additional Spring configuration, which means that the code behavior remains closer to the default and does not rely on external configurations to determine it's behavior.

Resources