What is semantic of org.slf4j.Logger.isDebugEnabled(Marker)? - logback

Slf4j has boolean isDebugEnabled(Marker marker) and Javadoc says nothing about marker argument.
Logback implementation public boolean isDebugEnabled(org.slf4j.Marker marker) leads to:
public abstract FilterReply decide(
Marker marker, Logger logger, Level level,
String format, Object[] params, Throwable t);
Still I don't understand why we need Marker in is...Enabled() method.
Is it for filtering events not only by Level but also by specific Marker?

Related

Understanding Factory constructor code example - Dart

I have some niggling questions about factory constructors example mentioned here (https://www.dartlang.org/guides/language/language-tour#factory-constructors).
I am aware of only three types of constructors on a basic level - default, named and parameterised.
Why should I use factory at all for this example?
Is that a named constructor which is being used? and why?
tl;dr Use a factory in situations where you don't necessarily want to return a new instance of the class itself. Use cases:
the constructor is expensive, so you want to return an existing instance - if possible - instead of creating a new one;
you only ever want to create one instance of a class (the singleton pattern);
you want to return a subclass instance instead of the class itself.
Explanation
A Dart class may have generative constructors or factory constructors. A generative constructor is a function that always returns a new instance of the class. Because of this, it does not utilize the return keyword. A common generative constructor is of the form:
class Person {
String name;
String country;
// unnamed generative constructor
Person(this.name, this.country);
}
var p = Person("...") // returns a new instance of the Person class
A factory constructor has looser constraints than a generative constructor. The factory need only return an instance that is the same type as the class or that implements its methods (ie satisfies its interface). This could be a new instance of the class, but could also be an existing instance of the class or a new/existing instance of a subclass (which will necessarily have the same methods as the parent). A factory can use control flow to determine what object to return, and must utilize the return keyword. In order for a factory to return a new class instance, it must first call a generative constructor.
In your example, the unnamed factory constructor first reads from a Map property called _cache (which, because it is Static, is stored at the class level and therefore independent of any instance variable). If an instance variable already exists, it is returned. Otherwise, a new instance is generated by calling the named generative constructor Logger._internal. This value is cached and then returned. Because the generative constructor takes only a name parameter, the mute property will always be initialized to false, but can be changed with the default setter:
var log = Logger("...");
log.mute = true;
log.log(...); // will not print
The term factory alludes to the Factory Pattern, which is all about allowing a constructor to return a subclass instance (instead of a class instance) based on the arguments supplied. A good example of this use case in Dart is the abstract HTML Element class, which defines dozens of named factory constructor functions returning different subclasses. For example, Element.div() and Element.li() return <div> and <li> elements, respectively.
In this caching application, I find "factory" a bit of a misnomer since its purpose is to avoid calls to the generative constructor, and I think of real-world factories as inherently generative. Perhaps a more suitable term here would be "warehouse": if an item is already available, pull it off the shelf and deliver it. If not, call for a new one.
How does all this relate to named constructors? Generative and factory constructors can both be either unnamed or named:
...
// named generative
// delegates to the default generative constructor
Person.greek(String name) : this(name, "Greece");
// named factory
factory Person.greek(String name) {
return Greek(name);
}
}
class Greek extends Person {
Greek(String name) : super(name, "Greece");
}
There is not much difference between a static method and a factory constructor.
For a factory constructor the return type is fixed to the type of the class while for a static method you can provide your own return type.
A factory constructor can be invoked with new, but that became mostly irrelevant with optional new in Dart 2.
There are other features like redirects rather rarely used that are supported for (factory) constructors but not for static methods.
It is probably still good practice to use a factory constructor to create instances of classes instead of static methods to make the purpose of object creation more obvious.
This is the reason a factory constructor is used in the example you posted and perhaps because the code was originally written in Dart 1 where it allowed to create a logger instance with new like with any other class.
Yes this is a named constructor and the prefix _ makes it a private named constructor. Only named constructors can be made private because otherwise there would be no place to add the _ prefix.
It is used to prevent instance creation from anywhere else than from the public factory constructor. This way it is ensured there can't be more than one Logger instance in your application.
The factory constructor only creates an instance the first time, and for subsequent calls always returns the previously created instance.
Complementing Dave's answer, this code shows a clear example when use factory to return a parent related class.
Take a look a this code from https://codelabs.developers.google.com/codelabs/from-java-to-dart/#3
You can run this code here. https://dartpad.dartlang.org/63e040a3fd682e191af40f6427eaf9ef
Make some changes in order to learn how it would work in certain situations, like singletons.
import 'dart:math';
abstract class Shape {
factory Shape(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
// To trigger exception, don't implement a check for 'triangle'.
throw 'Can\'t create $type.';
}
num get area;
}
class Circle implements Shape {
final num radius;
Circle(this.radius);
num get area => pi * pow(radius, 2);
}
class Square implements Shape {
final num side;
Square(this.side);
num get area => pow(side, 2);
}
class Triangle implements Shape {
final num side;
Triangle(this.side);
num get area => pow(side, 2) / 2;
}
main() {
try {
print(Shape('circle').area);
print(Shape('square').area);
print(Shape('triangle').area);
} catch (err) {
print(err);
}
}
In addition to the other answers, also consider the order of instantiating objects and when the instance is created:
In normal constructor, an instance gets created and the final variables get instantiated with the initializer list. This is why there's no return statement. The instance to return is already fixed, when executing the constructor!
In a factory constructor, the instance to return is decided by the method. That's why it needs a return statement and why it'll usually call a normal constructor in at least one path.
So a factory does nothing different than a static method could do (in other languages often called getInstance()), except you cannot overload the constructor with a static method but you can with a factory method. I.e. factory methods are a way to hide the fact that the user of your class is not calling a constructor but a static method:
// C++
MyCoolService.getInstance()
// Dart
MyCoolService()

Grails 3 deep JSON marshaller

I've defined and registered some custom marshallers for my domain objects. If used alone, just rendering one instance, works fine, but the problem comes when I return a map with an array of those instances. In this moment my custom marshaller is not beign invoked.
This is one of my marshallers:
class BackendCompanyMarshaller implements ObjectMarshaller<JSON> {
#Override
public boolean supports(Object object) {
object instanceof Company
}
#Override
public void marshalObject(Object object, JSON converter)
throws ConverterException {
JSONWriter writer = converter.getWriter()
writer.object()
writer.key('id').value(object.id)
.key('name').value(object.name?.encodeAsHTML()?:'')
.key('description').value(object.description?.encodeAsHTML()?:'')
.key('enterprise').value(object.enterprise?.encodeAsHTML()?:'')
writer.endObject()
}
}
Ans for example this is what I'm returning from my controller:
render text:[achievements:arrayOfAchievements, total:2] as JSON
In previous versions of grails I know there was deep marshallers but I haven't been able to find something similar for grails 3.
I have also tried to implement a custom marshaller for List, but I'm not sure what I should return or write.

Castle Windsor 3 Interceptor not releasing components created by a typed factory but 2.5.4 did. Why?

This is a similar pattern to ones stated elsewhere and detailed in this blog post. I have this working using Windsor 2.5.4 pretty much as stated in the blogpost, but decided to switch to using Windsor 3. When I did this I noticed that the memory usage of the application go up over time - I guessed this would be that components were'nt being released.
There were a couple of modifications to the code in the blogpost, which may have caused the behaviour to differ.
Here is my AutoRelease interceptor (straight out of the blogpost, here for convenience and the lazy ;) )
[Transient]
public class AutoReleaseHandlerInterceptor : IInterceptor
{
private static readonly MethodInfo Execute = typeof(IDocumentHandler).GetMethod("Process");
private readonly IKernel _kernel;
public AutoReleaseHandlerInterceptor(IKernel kernel)
{
_kernel = kernel;
}
public void Intercept(IInvocation invocation)
{
if (invocation.Method != Execute)
{
invocation.Proceed();
return;
}
try
{
invocation.Proceed();
}
finally
{
_kernel.ReleaseComponent(invocation.Proxy);
}
}
}
One of my deviations from the blog post is the selector that the typed factory uses:-
public class ProcessorSelector : DefaultTypedFactoryComponentSelector
{
protected override Func<IKernelInternal, IReleasePolicy, object> BuildFactoryComponent(MethodInfo method,
string componentName,
Type componentType,
IDictionary additionalArguments)
{
return new MyDocumentHandlerResolver(componentName,
componentType,
additionalArguments,
FallbackToResolveByTypeIfNameNotFound,
GetType()).Resolve;
}
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
return null;
}
protected override Type GetComponentType(MethodInfo method, object[] arguments)
{
var message = arguments[0];
var handlerType = typeof(IDocumentHandler<>).MakeGenericType(message.GetType());
return handlerType;
}
}
What might be noticeable is that I do not use the default resolver. (This is where, perhaps, the problem lies...).
public class MyDocumentHandlerResolver : TypedFactoryComponentResolver
{
public override object Resolve(IKernelInternal kernel, IReleasePolicy scope)
{
return kernel.Resolve(componentType, additionalArguments, scope);
}
}
(I omitted the ctor for brevity- nothing special happens there, it just calls the base ctor).
The reason I did this was because the default resolver would try to resolve by name and not by Type- and fail. In this case, I know I only ever need to resolve by type, so I just overrode the Resolve method.
The final piece of the puzzle will be the installer.
container.AddFacility<TypedFactoryFacility>()
.Register(
Component.For<AutoReleaseHandlerInterceptor>(),
Component.For<ProcessorSelector>().ImplementedBy<ProcessorSelector>(),
Classes.FromAssemblyContaining<MessageHandler>()
.BasedOn(typeof(IDocumentHandler<>))
.WithService.Base()
.Configure(c => c.LifeStyle.Is(LifestyleType.Transient)),
Component.For<IDocumentHandlerFactory>()
.AsFactory(c => c.SelectedWith<ProcessorSelector>()));
Stepping through the code, the interceptor is called and the finally clause is executed (e.g. I didn't get the method name wrong). However, the component does not seem to be released (using the performance counter shows this. Each invocation of the factory's create method increases the counter by one).
So far, my workaround has been to add a void Release(IDocumentHandler handler) method to my factory interface, and then after it executes the handler.Process() method, it explicitly releases the handler instance, and this seems to do the job- the performance counter goes up, and as the processing is done, it goes down).
Here is the factory:
public interface IDocumentHandlerFactory
{
IDocumentHandler GetHandlerForDocument(IDocument document);
void Release(IDocumentHandler handler);
}
And here is how I use it:
IDocumentHandlerFactory handler = _documentHandlerFactory.GetHandlerForDocument(document);
handler.Process();
_documentHandlerFactory.Release(handler);
Doing the Release explicitly therefore negates the need for the interceptor, but my real question is why this behaviour differs between the releases?
Note to self:- RTFM. Or in fact, read the Breakingchanges.txt file.
Here's the change that affects this behaviour (emphasis is mine):-
change - IReleasePolicy interface has a new method: IReleasePolicy
CreateSubPolicy(); usage of sub-policies changes how typed factories
handle out-of-band-release of components (see description)
impact - medium fixability - easy
description - This was added as an attempt to enable more fine grained
lifetime scoping (mostly for per-typed-factory right now, but in the
future also say - per-window in client app). As a side-effect of that
(and change to release policy behavior described above) it is no
longer possible to release objects resolved via typed factories, using
container.Release. As the objects are now tracked only in the scope
of the factory they will be released only if a call to factory
releasing method is made, or when the factory itself is released.
fix - Method should return new object that exposes the same behavior
as the 'parent' usually it is just best to return object of the same
type (as the built-in release policies do).
I didn't find the fix suggestion terribly helpful in my instance, however my solution in the question is what you should actually do (release using the factory). I'll leave it up in case anyone else has this (non) issue.

How to write custom serializer and deserializer in Jackson?

I have a class that has more than a dozen properties. For most of the properties of primitive type, I hope to use the default BeanSerializer and BeanDeserializer or whatever to reduce the cumbersome code I need to write. For other properties of custom and array types, I want to do some custom serializer/deserializer. Note that I am not able to change the underlying JSON string. But I have full access to the android code. I am using Jackson 1.7.9/Ektorp 1.1.1.
shall I subclass BeanDeserializer? I am having trouble with that. It expects a default constructor with no parameters but I don't know how to call the super constructor.
class MyType{
// a dozen properties with primitive types String, Int, BigDecimal
public Stirng getName();
public void setName(String name);
// properties that require custom deserializer/serializer
public CustomType getCustom();
public void setCustom(CustomType ct);
}
class MyDeserializer extends BeanDeserialzer{
// an exception is throw if I don't have default constructor.
// But BeanDeserializer doesn't have a default constructor
// It has the below constructor that I don't know how to fill in the parameters
public MyDeserializer(AnnotatedClass forClass, JavaType type,
BeanProperty property, CreatorContainer creators,
BeanPropertyMap properties,
Map<String, SettableBeanProperty> backRefs,
HashSet<String> ignorableProps, boolean ignoreAllUnknown,
SettableAnyProperty anySetter) {
super(forClass, type, property, creators, properties, backRefs, ignorableProps,
ignoreAllUnknown, anySetter);
}
#Override
public Object deserialize(JsonParser jp, DeserializationContext dc, Object bean)
throws IOException, JsonProcessingException {
super.deserialize(jp, dc, bean);
MyType c = (MyType)bean;
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jp, JsonNode.class);
// Use tree model to construct custom
// Is it inefficient because it needs a second pass to the JSON string to construct the tree?
c.setCustom(custom);
return c;
}
}
I searched Google but couldn't find any helpful examples/tutorial. If anyone can send me some working examples that would be great! Thanks!
To sub-class BeanSerializer/-Deserializer, you would be better off using a more recent version of Jackson, since this area has been improved with explicit support via BeanSerializerModifier and BeanDeserializerModifier, which can alter configuration of instances.
But just to make sure, you can also specify custom serializer/deserializer to just be used on individual properties, like so:
class Foo {
#JsonSerialize(using=MySerializer.class)
public OddType getValue();
}

Is it still considered a Factory if the objects being returned by the factory are static?

When my application starts up it needs to get an instance of the correct DAL class (currently there are 4) based on what user is logged in. Certain users are pulling down from certain databases.
Is it still considered a "factory" pattern if instead of instantiating instances of those DAL classes, I simply return the correct static instance of it? I have no need to continually create these objects since all users can share them.
Psuedocode:
public class RepositoryFactory
{
public static IRepository repoA = new FranksLumberRepo();
public static IRepository repoB = new LowesHardwareRepo();
public static IRepository repoC = new HackmansHardwareRepo();
public static IRepository repoD = new TomsHardwareRepo();
public IRepository createRepo(User currentUser)
{
switch(User.Store)
{
case FrankLumber:
return repoA;
case LowesHardware:
return repoB;
case Hackmans:
return repoC;
case TomsHardware:
return repoD;
default:
throw exception;
}
}
}
Slight clarification on your terminology. The objects are not static just the references. The objects are instances which have at least one static reference. When you return the object you are returning simply a reference to that object. It has no idea that there is a static holding it in some other area.
But yes, this is a valid factory pattern.
This would be a case of an "Abstract Factory" pattern, actually.
The factory pattern is essentially an abstraction (in the general sense of the term). Even if you return the static objects you are still adding a layer of abstraction, which is good and should be considered a part of the factory pattern in general.
This would be a singleton factory.