Atmosphere: The method getDefault() from the type BroadcasterFactory is deprecated - atmosphere

I'm using Atmosphere 2.2.0-RC3. And I have this warning: "The method getDefault() from the type BroadcasterFactory is deprecated" in the line BroadcasterFactory.getDefault().lookup(topic, true)
Here is the code:
#Path("/chat/{topic}")
#AtmosphereService (broadcaster = JerseyBroadcaster.class)
public class ChatResourceTopic {
private #PathParam("topic")
String topic;
#Suspend( contentType = MediaType.APPLICATION_JSON, listeners = { OnDisconnect.class })
#GET
public Broadcastable suspend() {
return new Broadcastable(BroadcasterFactory.getDefault().lookup(topic, true ));
}
...
}
I have checked the wiki and is widely used: https://github.com/Atmosphere/atmosphere/wiki/Understanding-Broadcaster
How could I change the code to avoid the warning?
Note: I also use this in:
BroadcasterFactory.getDefault().lookup(topic).broadcast(response);

I don't use Jersey with Atmosphere (I use #ManagedService) but you should be able to inject either an AtmosphereResource or BroadcasterFactory with the #Context annotation when you use Jersey.
public Broadcastable suspend(#Context BroadcasterFactory factory) {
OR
public Broadcastable suspend(#Context AtmosphereResource resource) {
BroadcasterFactory factory = resource.getAtmosphereConfig().getBroadcasterFactory();
I have not tested this but it's in older documentation

Related

'RoutingSlipCompleted' does not contain a definition for 'GetVariable'

after using massTransit (8.0.8) I got following error :
'RoutingSlipCompleted' does not contain a definition for 'GetVariable'
and the best extension method overload
'RoutingSlipEventExtensions.GetVariable(ConsumeContext,
string, Guid)' requires a receiver of type
'ConsumeContext'
here is my code:
using MassTransit;
using MassTransit.Courier.Contracts;
using MassTransit.Courier;
public class CheckInventoriesConsumer: IConsumer<ICheckInventoryRequest>
, IConsumer<RoutingSlipCompleted>
, IConsumer<RoutingSlipFaulted>
{
private readonly IEndpointNameFormatter _formatter;
public CheckInventoriesConsumer(IEndpointNameFormatter formatter)
{
_formatter = formatter;
}
public async Task Consume(ConsumeContext<ICheckInventoryRequest> context)
{
var routingSlip = CreateRoutingSlip(context);
await context.Execute(routingSlip);
}
private RoutingSlip CreateRoutingSlip(ConsumeContext<ICheckInventoryRequest> context)
{ // lot of code here
}
public async Task Consume(ConsumeContext<RoutingSlipCompleted> context)
{
// error is here
context.Message.GetVariable<Guid>(nameof(ConsumeContext.RequestId));
throw new NotImplementedException();
}
}
It is not going to find GetVariable method from MassTransit.Courier and I encounter with this error.
As you've already found based upon your comments:
context.GetVariable<Guid>(nameof(ConsumeContext.RequestId));
Is the right solution.
MassTransit Version 8 has more extensive serialization support, and the SerializationContext (from ConsumeContext) is needed to properly deserialize the variable from the routing slip event.

Xamarin Android binding does not implement interface issue

I've a java binding for android which somewhat works bar the new feature I'm trying to integrate with. Only now I have realised that the intended callback is not happening. Here are the classes (decompiled to java) in question:
At the top level we have
public interface MyPackage {
MyPackage.Companion Companion = MyPackage.Companion.$$INSTANCE;
public static final class Companion {
#Nullable
private static MyEventHandler myEventHandler;
// $FF: synthetic field
static final MyPackage.Companion $$INSTANCE;
#Nullable
public final MyEventHandler getMyEventHandler() {
return myEventHandler;
}
public final void setMyEventHandler(#Nullable MyEventHandler var1) {
myEventHandler = var1;
}
private Companion() {
}
static {
MyPackage.Companion var0 = new MyPackage.Companion();
$$INSTANCE = var0;
}
}
}
MyEventHandler class:
public abstract class MyEventHandler {
public abstract void handleEvent(#NotNull String var1, #NotNull Properties var2);
}
Properties class:
import java.util.Map;
public class Properties extends r {
public Properties() {
}
Properties(Map<String, Object> var1) {
super(var1);
}
public Properties a(String var1, Object var2) {
super.b(var1, var2);
return this;
}
}
and the problematic r class:
public class r implements Map<String, Object> {
private final Map<String, Object> a;
various implementations...
}
So I noticed the issue when I couldnt override the HandleEvent method at the integration level and started looking at the Binding logs and found:
Warning=>
BINDINGSGENERATOR: Warning BG8801: Invalid parameter type MyPackage...Properties in method HandleEvent in managed type MyPackage.MyEventHandler. (BG8801)
And in build logs:
message BG0000: warning BG8102: Class MyPackage....Properties has unknown base type MyPackage....r.
warning BG8801: Invalid parameter type MyPackage...Properties in method HandleEvent in managed type MyPackage.MyEventHandler.
As it was obvious r is an obfuscated class I need to make chagnes to my Metadata so I went ahead and popped in:
<attr path="/api/package[#name='MyPackage']/class[#name='r']" name="obfuscated">false</attr>
Which resulted in the R being generated but now I get the 5 following compile error:
Error CS0535: 'R' does not implement interface member 'IMap.EntrySet()' (CS0535)
Error CS0738: 'R' does not implement interface member 'IMap.KeySet()'. 'R.KeySet()' cannot implement 'IMap.KeySet()' because it does not have the matching return type of 'ICollection'. (CS0738)
Error CS0535: 'R' does not implement interface member 'IMap.Put(Object?, Object?)' (CS0535)
Error CS0535: 'R' does not implement interface member 'IMap.PutAll(IDictionary?)' (CS0535)
Error CS0738: 'R' does not implement interface member 'IMap.Values()'. 'R.Values()' cannot implement 'IMap.Values()' because it does not have the matching return type of 'ICollection'. (CS0738)
I tried to make a managed return using
<attr path="/api/package[#name='MyPackage']/class[#name='r']/method[#name='entrySet' and count(parameter)=0]" name="managedReturn">Java.Util.IMap</attr>
With same number of compile error as above. Then I tried removing the node using:
<remove-node path="/api/package[#name='MyPackage']/class[#name='r']/method[#name='entrySet']"/>
Still no luck. :(
What am I missing here? Any pointers/suggestions will be appreciated!
It seems like you are trying to expose a Map to C# and as you stated, Java Generics are not handled very well.
In a very popular social network you received an answer from #mattleibow. I do not take credit for his answer but I went to check nonetheless and it seems fine.
If you look at the description of the Java.Lang.HashMap type
https://learn.microsoft.com/en-us/dotnet/api/java.util.hashmap?view=xamarin-android-sdk-9 it's a good candidate for you to expose.
You can also try with the corresponding interface for better safety https://learn.microsoft.com/en-us/dotnet/api/java.util.imap?view=xamarin-android-sdk-9
If it works you will still have to cast the types yourself.
Please answer to the comment to say that problem is solved for the sake of future generations arriving on this post :D
Credit is not mine so don't give it to me :-)
John,
I got arround fixing it by providing implementation of the the said methods in a partial class. Basically added a new file called R.cs under Additions folder as follows:
namespace YourNameSpace
{
public partial class R
{
public void PutAll(System.Collections.IDictionary p0)
{
PutAll(p0);
}
public Java.Lang.Object Put(Java.Lang.Object key, Java.Lang.Object value)
{
return Put(key, value);
}
public System.Collections.ICollection EntrySet()
{
return EntrySet();
}
public System.Collections.ICollection KeySet()
{
return KeySet();
}
public System.Collections.ICollection Values()
{
return Values();
}
}
}
I couldn't get it to work by adding XML transformation, but I think there was some tooling issue.

Mapper decorator not getting compiled

Mapper decorator for my mapper is not getting compiled.Mapper is getting compiled, but not the decorator. Because, during the build I'm getting the type conversion error, even though I'm doing it in the mapper decorator. Is there anything more to add?
mapper code:
#Mapper
#DecoratedWith(OneMapperDecorator.class)
public interface OneMapper {
public TwoObject convertToTwoObject(OneObject one);
}
decorator code:
public abstract class OneMapperDecorator implements OneMapper {
private final OneMapper delegate;
public OneMapperDecorator (OneMapper delegate) {
this.delegate = delegate;
}
#Override
public TwoObject convertToTwoObject(OneObject one)
{
TwoObject two=delegate.convertToTwoObject(one);
two.setTotalFare(new BigDecimal(one.getPrice()));//string to bigdecimal conversion
return two;
}
}
The decorator is meant to augment the mapping not to replace it. MapStruct has no way of knowing that you are mapping your totalFare in the decorator. You have 2 options:
Define a custom mapping method
In your OneMapper you can add a default method that would perform the mapping (as the error says.
#Mapper
#DecoratedWith(OneMapperDecorator.class)
public interface OneMapper {
#Mapping(target = "totalFare", source = "price");
TwoObject convertToTwoObject(OneObject one);
default BigDecimal map(String value) {
return value == null ? null : new BigDecimal(value);
}
}
Ignore the mapping
In case you want to do the mapping in your decorator then you need to tell MapStruct to not map it.
#Mapper
#DecoratedWith(OneMapperDecorator.class)
public interface OneMapper {
#Mapping(target = "totalFare", ignore = true);
TwoObject convertToTwoObject(OneObject one);
}
One advise from me if you are using your delegate only to map extra fields I would either add custom methods or use #AfterMapping and #BeforeMapping to handle that.

How can I make AutoMoqCustomization use Strict MockBehavior?

Using AutoFixture with the AutoFixture.AutoMoq package, I sometimes find tests that weren't configured to correctly test the thing they meant to test, but the problem was never discovered because of the default (Loose) Mock behavior:
public interface IService
{
bool IsSomethingTrue(int id);
}
void Main()
{
var fixture = new Fixture()
.Customize(new AutoMoqCustomization());
var service = fixture.Freeze<Mock<IService>>();
Console.WriteLine(service.Object.IsSomethingTrue(1)); // false
}
I'd like to make Mocks get created with Strict behavior, so we're forced to call Setup() for the methods we expect to be called. I can do this for each individual mock like this:
fixture.Customize<Mock<IService>>(c => c.FromFactory(() => new Mock<IService>(MockBehavior.Strict)));
But after combing through source code for AutoMoqCustomization() and the various ISpecimenBuilder and other implementations, I'm pretty lost as to the best way to just make all Mocks get initialized with strict behavior. The framework appears to be very flexible and extensible, so I'm sure there's a simple way to do this--I just can't figure out how.
There's no simple built-in feature that will enable you to do something like that, but it shouldn't be that hard to do.
Essentially, you'd need to change MockConstructorQuery so that it invokes the constructor that takes a MockBehavior value, and pass in MockBehavior.Strict.
Now, you can't change that behaviour in MockConstructorQuery, but that class is only some 9-10 lines of code, so you should be able to create a new class that implements IMethodQuery by using MockConstructorQuery as a starting point.
Likewise, you'll also need to create a custom ICustomization that does almost exactly the same as AutoMoqCustomization, with the only exception that it uses your custom IMethodQuery with strict mock configuration instead of MockConstructorQuery. That's another 7 lines of code you'll need to write.
All that said, in my experience, using strict mocks is a bad idea. It'll make your tests brittle, and you'll waste a lot of time mending 'broken' tests. I can only recommend that you don't do this, but now I've warned you; it's your foot.
For those interested, down below you can find #MarkSeemann's reply translated into code. I am pretty sure it does not cover all use cases and it was not heavily tested. But it should be a good starting point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.AutoMoq;
using Ploeh.AutoFixture.Kernel;
namespace ConsoleApplication1
{
public class StrictAutoMoqCustomization : ICustomization
{
public StrictAutoMoqCustomization() : this(new MockRelay()) { }
public StrictAutoMoqCustomization(ISpecimenBuilder relay)
{
// TODO Null check params
Relay = relay;
}
public ISpecimenBuilder Relay { get; }
public void Customize(IFixture fixture)
{
// TODO Null check params
fixture.Customizations.Add(new MockPostprocessor(new MethodInvoker(new StrictMockConstructorQuery())));
fixture.ResidueCollectors.Add(Relay);
}
}
public class StrictMockConstructorMethod : IMethod
{
private readonly ConstructorInfo ctor;
private readonly ParameterInfo[] paramInfos;
public StrictMockConstructorMethod(ConstructorInfo ctor, ParameterInfo[] paramInfos)
{
// TODO Null check params
this.ctor = ctor;
this.paramInfos = paramInfos;
}
public IEnumerable<ParameterInfo> Parameters => paramInfos;
public object Invoke(IEnumerable<object> parameters) => ctor.Invoke(parameters?.ToArray() ?? new object[] { });
}
public class StrictMockConstructorQuery : IMethodQuery
{
public IEnumerable<IMethod> SelectMethods(Type type)
{
if (!IsMock(type))
{
return Enumerable.Empty<IMethod>();
}
if (!GetMockedType(type).IsInterface && !IsDelegate(type))
{
return Enumerable.Empty<IMethod>();
}
var ctor = type.GetConstructor(new[] { typeof(MockBehavior) });
return new IMethod[]
{
new StrictMockConstructorMethod(ctor, ctor.GetParameters())
};
}
private static bool IsMock(Type type)
{
return type != null && type.IsGenericType && typeof(Mock<>).IsAssignableFrom(type.GetGenericTypeDefinition()) && !GetMockedType(type).IsGenericParameter;
}
private static Type GetMockedType(Type type)
{
return type.GetGenericArguments().Single();
}
internal static bool IsDelegate(Type type)
{
return typeof(MulticastDelegate).IsAssignableFrom(type.BaseType);
}
}
}
Usage
var fixture = new Fixture().Customize(new StrictAutoMoqCustomization());

How do you annotate a nested Java class for Swagger?

I'm using the swagger-springmvc integration to annotate my Java code to produce a Swagger definition. All was going well until I got to a request class (posted to my controller) that contains a reference to another class:
#ApiModel(value = "description")
public class MyRequest {
private MyOtherClass aclass;
...
#ApiModelProperty(value = "description", required = true)
public MyOtherClass getAclass() {
return aclass;
}
...
}
In another file MyOtherClass is annotated in the same way:
#ApiModel(value = "description")
public class MyOtherClass {
public String anAttribute;
...
#ApiModelProperty(value = "description", required = true)
public String getAnAttribute() {
return anAttribute;
}
...
}
When viewed in the Swagger UI, the MyOtherClass model is not in the generated definition and the request object is just shown as a string:
{
"aclass": "MyOtherClass",
...
}
Rather than:
{
"trips": [
{
"anAttribute" : ""
}
],
...
}
Am I missing an annotation somewhere or is this a limitation? It seems like there should be some way to force the class to be included in the model.
This was an error on swagger-springmvc <= 0.8.2, they were not resolving the complete tree of attributes through reflection. Now, with version 0.8.8 it is really simple to configure Swagger for your Spring project, and this problem has been successfully solved.
You don't need to add any special additional annotation!. Enjoy!

Resources