this is really confusing! if you use a JsonGeneratorDelegate as-is it doesn't transmit calls to setPrettyPrinter() to the delegate
Probably just an oversight -- feel free to file an issue to get this corrected for future versions. Delegate is supposed to delegate all calls by default.
So what is your real question? You can always define your own enhanced JsonGeneratorDelegate, like this:
public class PrettyPrintJsonGeneratorDelegate extends JsonGeneratorDelegate {
public PrettyPrintJsonGeneratorDelegate (final JsonGenerator delegate) {
super (delegate);
}
#Override
public JsonGenerator setPrettyPrinter(final PrettyPrinter pp) {
delegate.setPrettyPrinter (pp);
return this;
}
}
Related
when implementing an Akka Typed actor by extending createReceive, we will see something like this:
#Override
public Receive<Command> createReceive()
{
return newReceiveBuilder()
.onMessage(SomeCommand.class, s -> something())
.build();
}
..with something() returning a Behavior, for example:
public Behavior<Command> something()
{
return Behaviors.receive(Command.class)
.onMessage(SomeCommand.class, m -> something())
.build();
}
But now we can see that createReceive() and something() being pretty much duplicates. In other words, whenever I return to the "initial" state, I will get this code duplication. So, the question is:
Can I somehow implement createReceive() by re-using the something() method? For example, is something like this possible...
#Override
public Receive<Command> createReceive()
{
return Behaviors.behave( this::something);
}
(Of course, Behaviors.behave does not exist like this, the question is, does something like this exists, "converting" a Behavior to a receive?)
Akka 2.7.0 will introduce an alternative API for defining a behavior which is basically a port of the Scala API.
public class MyActor extends AbstractOnMessageBehavior<MyActor.Command>
public static interface Command {}
public static class SomeCommand extends Command {
public static SomeCommand INSTANCE = new SomeCommand();
private SomeCommand() {}
}
public MyActor(ActorContext<Command> context) {
super(context);
}
#Override
public Behavior<Command> onMessage(Command msg) {
if (msg instanceof SomeCommand) { return something((SomeCommand)msg); }
else return Behaviors.unhandled();
}
private Behavior<Command> something(SomeCommand sc) {
// FIXME: actually do something useful
return Behaviors.same()
}
}
(Apologies if the Java is atrocious)
This API is likely slightly lower overhead than the current Java AbstractBehavior API: the ReceiveBuilder and BehaviorBuilder APIs are effectively compiling a domain-specific language like:
newReceiveBuilder()
.onMessage(SomeMessage.class, this::something)
.build()
into
if (msg instanceof SomeMessage) { return something((SomeMessage)msg); }
else return Behaviors.unhandled();
whenever an instance of this behavior handles its first message (i.e. when an actor handles its first message after transitioning to this behavior). When staying in this behavior, there's also some overhead of checking if the Receive has been built already (though JIT may largely eliminate that).
The benefit of the ReceiveBuilder/BehaviorBuilder APIs is that the instanceof checks and casts are hidden: the developer ergonomic improvement is worth some small overhead. The AbstractOnMessageBehavior lets you opt out of the builder APIs:
You can, effectively, manually compile the builder into instanceof and cast like I did above (this will work on any Java version); if you're on Java 8/11 and want max performance, this might be worth trying (but always, always, benchmark!)
You can use language features ("pattern matching") to have the Java compiler build the instanceof-and-cast logic... this should also make it easier to define a behavior in Kotlin or other JVM language which supports pattern matching. This might even be more ergonomic than the builders.
You can also use a different approach entirely (e.g. one leveraging virtual method dispatch)
Jackson docs say that a class that implements their JsonSerializable interface will be serialized by calling the Interface's serialize() method.
I tried this in a project that uses Jackson 2.8.4 under Jersey 2.25.
It continues to use Jackson's BeanSerializer to do default serialization based on public getters, instead of using the SerializableSerializer and the serialize() method.
Code looks like this fairly minimal example...
public class Minimal extends JsonSerializable.Base {
private String title;
private ZonedDateTime theTime;
public String getTitle() { return title; }
void setTitle(String title) { this.title = title; }
public ZonedDateTime getTheTime() { return theTime; }
void setTheTime(ZonedDateTime theTime) { this.theTime = theTime; }
#Override
public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeFieldName("title");
gen.writeString(this.title);
// Other serialization...
gen.writeEndObject();
}
#Override
public void serializeWithType(JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
throw new UnsupportedOperationException("Not supported.");
}
}
I also tried other ideas to get it using the right serializer...maybe foolish ideas like...
public class Minimal implements JsonSerializable {
and
#JsonSerialize(using = SerializableSerializer.class)
public class Minimal extends JsonSerializable.Base {
and
#JsonSerialize(as = JsonSerializable.Base.class)
public class Minimal extends JsonSerializable.Base {
What am I missing to get this Jackson feature working?
I verified in Jackson's latest source code that the feature still exists. I suppose I can trace it through the 2.8.4 source in the debugger, but maybe someone knows the answer.
Apparently the answer to
"What am I missing?"
is Nothing.
After writing the question, I rebuilt everything again, restarted Tomcat, and redeployed and tested again and got my expected output.
So I will chalk this up to bad build, bad deploy, confused Classloader, something like that. I am leaving the question, since it provides an example that might help someone.
I have a problem with Orika 1.4.5 and PermGen Space.
Indeed, i'm using a a ConfigurableMapper this way :
public class SoapSearchPrdvFreeSlotsMapper extends ConfigurableMapper {
#Override
public void configure(MapperFactory mapperFactory) {
mapperFactory.registerClassMap(mapperFactory.classMap(PrdvFreeSlot.class, PrdvWsListerDispoTelV2Filter.class)
.field("typeRdv", "wsldtTypeRdv")
.field("motifId", "wsldtMotifId")
.byDefault().toClassMap());
}
mapperFactory.registerClassMap(mapperFactory.classMap(PrdvFreeSlot.class, PrdvWsListerDispoTelV2.class)
.field("typeRdv", "wsldtTypeRdv")
.field("motifId", "wsldtMotifId")
.field("quantum", "wsldtActiviteIdActivQuantum")
.field("activiteJours", "wsldtActiviteIdActivJours")
.field("activiteHeureFerme", "wsldtActiviteIdActivHeureFerme")
.field("activiteHeureOuvert", "wsldtActiviteIdActivHeureOuvert")
.field("startDate", "disDate")
.field("disCapacity", "disCapacite")
.field("disReserve", "disReserve")
.field("reserveCC", "wsldtReserveCC")
.byDefault().toClassMap());
}
}
#Override
public void configureFactoryBuilder(DefaultMapperFactory.Builder builder) {
builder.build().getConverterFactory().registerConverter(new DateXmlDateConverter());
}
}
But each time i call this mapper, i have autogenerated class mappers which are stored in the PermGen.
I try to use the "existsRegisteredMapper" of the MapperFactory to prevent class mappers auto-generation but it doesn't work:
public static <T, U> boolean existsRegisteredMapperInFactory(MapperFactory mapperFactory, Class<T> classSrc, Class<U> classDest) {
return mapperFactory.existsRegisteredMapper(TypeFactory.valueOf(classSrc), TypeFactory.valueOf(classDest), true);
}
and the modified first code block:
if (!existsRegisteredMapperInFactory(mapperFactory, PrdvWsListerDispoTelV2Filter.class, PrdvFreeSlot.class)) {
mapperFactory.registerClassMap(mapperFactory.classMap(PrdvFreeSlot.class, PrdvWsListerDispoTelV2Filter.class)
.field("typeRdv", "wsldtTypeRdv")
.field("motifId", "wsldtMotifId")
.byDefault().toClassMap());
}
Please, Is there a way to prevent class mappers autogeneration without rewriting all the mappers i have ?
Thanks for your help.
Please make sure that the mapper is a singleton. You don't need to instantiate it everytime.
You don't need to verify if the the mapper has been registered or not. It will be generated only once (per MapperFactory instance).
So just make sure that SoapSearchPrdvFreeSlotsMapper is a singleton (only one instance, ConfigurableMapper is thread-safe)
Suppose I have a validation annotation on my Interface method to validate input arguments and return value.
Is it possible at the moment (V 1.9.5) to tell Mockito to invoke this validator during the invocation process?
The background would be to prevent developers from writing unrealistic tests by mocking the given interface in a way that violates the specified validator.
So what I would want is to register something like
class MyAnswerInterceptor<T> implements AnswerInterceptor<T> {
#Override
public Answer<T> intercept(final Answer<T> answer) {
return new Answer<T>() {
#Override
public T answer(InvocationOnMock invocation) throws Throwable {
validateArguments(invocation);
T result = answer.answer(invocation);
validateReturnValue(result);
return result;
}
}
}
}
to be called on every answer of a given mock.
Is this possible at all? I've looked into the code, also to check if I could hack in at some point (even using reflection or the like), but it seems due to entanglement of instance creation and logic, it's hardly possible to achieve what I want (i.e. stuff like MockHandler mockHandler = new MockHandlerFactory().create(settings); makes it impossible to hook in and put custom stuff on top without patching and deploying the whole thing...)
Any insight would be highly appreciated :-)
You could achieve that by creating a custom MockMaker.
MockMaker is an extension point that makes it possible to use custom dynamic proxies and avoid using the default cglib/asm/objenesis implementation
Our custom implementation delegates all the complex stuff to the default MockMaker: CglibMockMaker. It "decorates" only the createMock method by registering on the settings parameter an InvocationListener. This listener will be notified when an invocation have been done allowing use to call validateArguments and validateReturnValue.
import org.mockito.internal.creation.CglibMockMaker;
import org.mockito.invocation.Invocation;
import org.mockito.invocation.MockHandler;
import org.mockito.listeners.InvocationListener;
import org.mockito.listeners.MethodInvocationReport;
import org.mockito.mock.MockCreationSettings;
import org.mockito.plugins.MockMaker;
public class ValidationMockMaker implements MockMaker {
private final MockMaker delegate = new CglibMockMaker();
public ValidationMockMaker() {
}
#Override
public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
settings.getInvocationListeners().add(new InvocationListener() {
#Override
public void reportInvocation(MethodInvocationReport methodInvocationReport) {
Invocation invocation = (Invocation) methodInvocationReport.getInvocation();
validateArguments(invocation.getArguments());
validateReturnValue(methodInvocationReport.getReturnedValue());
}
});
return delegate.createMock(settings, handler);
}
#Override
public MockHandler getHandler(Object mock) {
return delegate.getHandler(mock);
}
#Override
public void resetMock(Object mock, MockHandler newHandler, MockCreationSettings settings) {
delegate.resetMock(mock, newHandler, settings);
}
protected void validateArguments(Object... arguments) {
// Arrays.stream(arguments).forEach(Objects::requireNonNull);
}
private void validateReturnValue(Object result) {
// Objects.requireNonNull(result);
}
}
Last but not least, we need to tell to Mockito to use our implementation. This is possible by adding a file
mockito-extensions/org.mockito.plugins.MockMaker
containing our MockMaker class name:
ValidationMockMaker
See Using the extension point section in the javadoc.
I have a question about asynchronous method calls in java, especially about the response value of the async method.
The situation is the following:
The async method I want to call is..
public void getSpeed(IResponseListener listener) {
....
}
The interface of the listener is...
interface IResponseListener {
public void response(ResponseEvent event);
}
This method is called when the async method has a response value
My problem now is that the class ResponseEvent has an attribute response that can be of any type (boolean,float,String...)and in the implementation of the interface IResponseListener I have to cast the value...
IResponseListener listener = new IResponseListener {
public void response(ResponseEvent event) {
float f = (float)event.response;
}
}
Is this a good solution to handle this? I think the bad thing is that the response listener HAS to know the type of the response!
Is there a better solution to handle asynchronous calls that want to give a response even if the response can be of any type?
I think a lot of these answers are starting to look like this->
public interface Function<Args, Value>
{
public Value call(Args args);
}
Your return type doesn't matter--if it can return multiple types, then the "multiple types" are a type...might I suggest a type of JSON considering what you're looking at?
The reality is you can't expect your handler to know the type in advance so you need to specify that. Whether this is with the return type or the class is up to you.
I could easily see doing a class hierarchy:
public class ResponseString implements Function<Args, String>;
public class ResponseNumber implements Function<Args, Number>;
...
public class ResponseType implements Function<Args, Type>;
or simply creating a type that has all the information you need. The long and short is that the method can DEFINE what it expects for the types and you have the ability to extend them. Keep in mind that response could also be a Function which could be executed. There's nothing wrong with knowing what to DO with something and not knowing what it is ->
Example->
//Admittedly I'd probably have a "Procedure or VoidFunction interface as well".
public yourMethod(Function<String args, Function<String,?> handler)
{
String hello = "hello";
Function<String,?> function = handler.call(hello);
function.call(hello);
}
I hope this helps. Sometimes there's no reason to go this far, and sometimes there is. You don't know the type--it seems like maybe you're hoping someone else will provide it and this can do that for you while remaining strict.
EDIT:
the example of have for this in one framework is:
Applcation.openDialog(Dialog dialog, Callable<Boolean> onClose);
This returns true of the dialog cleans up and closes and false if not. I don't really care what happens here, I do care that it tells me yes, close it, or no don't.
Use Java generics:
interface IResponseListener<T> {
public void response(T response);
}
Then, in an anonymous class:
IResponseListener listener = new IResponseListener<Float> {
public void response(Float response) {
float f = response;
}
}
I don't know whether this is correct, but if you are going to handle the return value differently, why not overload the response method with different type of objects that you would expect. Just a suggestion..
interface InterfaceName{
void response(float responseVal);
void response(boolean responseVal);
...
}
I would have done as #nico_ekito says...Or use your existing solution. It is a problem that you don't know the result type.
Anyway, you could do some adjustments and let the ResponseEvent class do the casting for you.
ResponseListener.java
interface IResponseListener {
void response(ResponseEvent event);
}
ResponseEvent.java
public class ResponseEvent {
private Object response;
#SuppressWarnings("unchecked")
public <T> T getResponse() {
return (T)response;
}
public <T> void setResponse(T response) {
this.response = response;
}
}
Usage:
IResponseListener listener = new IResponseListener() {
public void response(ResponseEvent event) {
float f = event.getResponse();
}
};
Please note that you will get a ClassCastException if your type is something other than what you expect it to be.