java.lang.ClassCastException: fi.rogerstudio.possis.MainApplication cannot be cast to com.facebook.react.ReactApplication - reactjs

I am getting this error when receiving push notification only when the app is open, foreground mode!
Does anyone had this issue before using the Firebase push notification and react-native-fcm?
COde:
showLocalNotification(notif) {
FCM.presentLocalNotification({
title: notif.title,
body: notif.body,
priority: "high",
click_action: notif.click_action,
show_in_foreground: true,
local: true
});
}
Mainapplication.java:
public class MainApplication extends MultiDexApplication {
// Needed for `react-native link`
public List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
// Add your own packages here!
// TODO: add cool native modules
// new MainReactPackage(),
new RNBackgroundGeolocation(),
// Needed for `react-native link`
new FIRMessagingPackage(),
//new RNBackgroundGeolocation(),
//new RNFirebasePackage(),
new VectorIconsPackage()
//new RNFirebaseMessagingPackage()
);
}
}
Full Error I am getting:
java.lang.ClassCastException: fi.rogerstudio.possis.MainApplication cannot be cast to com.facebook.react.ReactApplication
at com.evollu.react.fcm.MessagingService$1.run(MessagingService.java:41)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

For someone who may be coming to this 3.5 years after the fact, the solution is to make sure your main application extends ReactApplication,
public class MainApplication extends MultiDexApplication, ReactApplication
and then implement getReactNativeHost like this:
public class MainApplication extends MultiDexApplication {
...
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
#Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
...
}

Related

spring cloud gcp pub/sub Jackson messageConverter deserialize fail

I'm trying to receive and process messages through GCP Pub/Sub.
I tried to convert and receive the payload part of the message through JacksonPubSubMessageConverter, but it failed.
It seems that I am not handling byte[] properly inside JacksonPubSubMessageConverter. Do I need to change ObjectMapper settings or override JacksonPubSubMessageConverter?
Below is a code example.
#Slf4j
#Configuration
public class PubSubConfig {
#Bean
public PubSubMessageConverter pubSubMessageConverter(ObjectMapper objectMapper) {
return new JacksonPubSubMessageConverter(objectMapper);
}
}
// ...
#Getter
#Setter
#ToString
#NoArgsConstructor(access = AccessLevel.PROTECTED)
public class MessageDTO {
private PubSubAction action;
#JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate startedAt;
private Boolean dryRun;
}
// ...
public enum PubSubAction {
MY_ACTION("my action"),
ETC("etc action");
private final String description;
PubSubAction(String description) {
this.description = description;
}
#JsonCreator
public static PubSubAction create(String name) {
return Stream.of(PubSubAction.values())
.filter(pubSubAction -> pubSubAction.name().equals(name))
.findAny()
.orElse(null);
}
}
// ...
class MyConsumer() {
private final String subscriptionName;
private final PubSubTemplate pubSubTemplate;
public MyConsumer(
String subscriptionName,
PubSubTemplate pubSubTemplate
) {
this.subscriptionName = subscriptionName;
this.pubSubTemplate = pubSubTemplate;
}
private void consume(
ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO> convertedMessage) {
try {
MessageDTO payload = convertedMessage.getPayload();
log.debug("payload {}", payload);
// payload MessageDTO(action=MY_ACTION, startedAt=null, dryRun=null)
convertedMessage.ack();
} catch (Exception e) {
log.error("Unknown Exception {} {}", e.getMessage(), this.subscriptionName, e);
}
}
private Consumer<ConvertedBasicAcknowledgeablePubsubMessage<MessageDTO>> convertConsumer() {
return this::consume;
}
public void subscribe() {
log.info("Subscribing to {}", subscriptionName);
pubSubTemplate.subscribeAndConvert(subscriptionName, this.convertConsumer(),
MessageDTO.class);
}
}

Unit test Apache Camel specific routes by filtering (Model#setRouteFilter)

How to include only certain routes in my unit test. For example, how do I enable only my-translation-route.
public class TestRoute extends RouteBuilder {
#Override
public void configure() {
from("ftp://my-ftp-server:21/messages")
.routeId("my-inbound-route")
.to("direct:my-translation-route");
from("direct:my-translation-route")
.routeId("my-translation-route")
.bean(MyBean.class)
.to("direct:my-outbound-route");
from ("direct:my-outbound-route")
.routeId("my-translation-route")
.to("http://my-http-server:8080/messages");
}
}
I tried with Model#filterRoutes but this did not work. All routes were loaded.
class TestRouteTest extends CamelTestSupport {
#Override
protected RoutesBuilder createRouteBuilder() {
return new TestRoute();
}
#Override
public boolean isUseAdviceWith() {
return true;
}
#Test
void testIfItWorks() throws Exception {
context.setRouteFilterPattern("my-translation-route", null);
AdviceWith.adviceWith(context, "my-translation-route", a -> {
a.mockEndpointsAndSkip("direct:my-outbound-route");
});
context.start();
getMockEndpoint("mock:direct:my-outbound-route").expectedBodyReceived().expression(constant("Hahaha! 42"));
template.sendBodyAndHeaders("direct:my-translation-route", "42", null);
assertMockEndpointsSatisfied();
}
}
I got it working with the override of CamelTestSupport#getRouteFilterIncludePattern, e.g.:
#Override
public String getRouteFilterIncludePattern() {
return "direct:my-translation-route";
}
But then this is set for all tests in this test class.
Possible (stupid) solution : set a conditional auto startup for your routes, whose value depends on a (Camel or JVM) property that you can set with a particular value during the unit tests:
public class TestRoute extends RouteBuilder {
#PropertyInject(name="productionMode", defaultValue="true")
private boolean productionMode;
#Override
public void configure() {
from("ftp://my-ftp-server:21/messages")
...
.autoStartUp(productionMode); // <=here
}
}
There are various ways to override properties during your tests. See https://camel.apache.org/components/3.17.x/properties-component.html

MappingException: Ambiguous field mapping detected

Using Spring boot 1.5.6.RELEASE.
I have the following mongo document base class:
#Document(collection="validation_commercial")
public abstract class Tier {
#Id
private String id;
#DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
private Date created;
#Field("tran")
private Tran tran;
public Tier() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Tran getTran() {
return tran;
}
public void setTran(Tran tran) {
this.tran = tran;
}
}
which is then extended:
public class Tier1 extends Tier {
#Field("tier1")
private Tier1Programs tier1;
public Tier1() {
this.tier1 = new Tier1Programs();
}
public Tier1Programs getTier1() {
return tier1;
}
public void setTier1(Tier1Programs tier1) {
this.tier1 = tier1;
}
}
which in turn is extended:
public class Tier2 extends Tier1 {
#Field("tier2")
private Tier2Programs tier2;
public Tier2() {
this.tier2 = new Tier2Programs();
}
public Tier2Programs getTier2() {
return tier2;
}
public void setTier2(Tier2Programs tier2) {
this.tier2 = tier2;
}
}
There is a Tier1 Supervisor (Spring Boot Application) that uses the Tier1 class within the MongoRepository interface:
public interface Tier1Repository extends MongoRepository<Tier1,String>{}
for retrieving and saving - no issue.
I then have a Tier2 Supervisor (Spring Boot Application) that uses a Tier1 Repository (for retrieving the Tier1 document and a Tier2 Repository for saving the Tier2 document:
#Repository("tier1Repository")
public interface Tier1Repository extends MongoRepository<Tier1,String>{}
#Repository("tier2Repository")
public interface Tier2Repository extends MongoRepository<Tier2,String>{}
My service is:
#Service
public class TierService {
#Qualifier("tier1Repository")
#Autowired
private final Tier1Repository tier1Repository;
#Qualifier("tier2Repository")
#Autowired
private final Tier2Repository tier2Repository;
public TierService(#Qualifier("tier1Repository") Tier1Repository tier1Repository, #Qualifier("tier2Repository") Tier2Repository tier2Repository) {
this.tier1Repository = tier1Repository;
this.tier2Repository = tier2Repository;
}
public Tier1 findOne(String id) {
return tier1Repository.findOne(id);
}
public void SaveTier(Tier2 tier) {
tier2Repository.save(tier);
}
public Tier1Repository getTier1Repository() {
return tier1Repository;
}
public Tier2Repository getTier2Repository() {
return tier2Repository;
}
}
and finally the app:
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class, JdbcTemplateAutoConfiguration.class})
#Configuration
#ComponentScan(basePackages = {"com.k12commercial.tier2supervisor"})
#ImportResource("classpath:application-context.xml")
public class Application implements CommandLineRunner {
#Autowired
private IReceiver raBidNetPriceReceiver;
#Autowired
private UdyDataSourceFactory udyDSRegistry;
public static void main(String[] args) throws InterruptedException {
try {
SpringApplication.run(Application.class, args);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run(String... args) throws Exception {
raBidNetPriceReceiver.processTierMessages();
exit(0);
}
}
When I run the Tier2 Supervisor from the command line I get the following error:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'tierService' defined in URL
[jar:file:/opt/java-commandline/tier2supervisor-1.0.jar!/BOOT-INF/classes!/com/k12commercial/tier2supervisor/service/TierService.class]: Unsatisfied dependency expressed through constructor parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tier2Repository': Invocation of init method failed; nested exception is org.springframework.data.mapping.model.MappingException: Ambiguous field mapping detected! Both private final java.lang.reflect.Type org.springframework.data.util.TypeDiscoverer.type and private final java.lang.Class org.springframework.data.util.ClassTypeInformation.type map to the same field name type! Disambiguate using #Field annotation!
I am not sure if the issue is Tier2 extending Tier1 (did try putting #Document tag above Tier1 and Tier2 with no change). I think I have marked the relevant fields so don't understand the need to disambiguate. I thought the issue was having 2 repositories (Spring Boot not knowing which one to DI) so removed the Tier1Repository - didn't work. Tried better qualifying the repositories but still got the same error. I made Tier1 and Tier2 #Transient and that got rid of the message but also removed the tier1 section in the mongo document - so wrong correction.
Thinking it is an annotation fix but not seeing it...
Please advise - thank you.
Sorry for the delay (I got pulled away to work on something else) and thank you to those who responded.
The issue was I had a MongoTemplate in my Tier level programs e.g.Tier2Programs (sub library) which Spring Boot was trying to autowire.
By moving the Mongo (CRUD) requirements to the supervisor level (I also replaced the Repositories with one MongoTemplate to simplify) I removed the ambiguity. (I also removed the Service class).
The code is contained with the RaBidNetReciever class
#Component
public class RaBidNetPriceReceiver extends BaseReceiver implements IReceiver, ApplicationEventPublisherAware {
private static final Logger LOGGER = LoggerFactory.getLogger(RaBidNetPriceReceiver.class);
private final RabbitTemplate raBidNetPriceRabbitTemplate;
public RaBidNetPriceReceiver(MongoTemplate mongoTemplate, RabbitTemplate raBidNetPriceRabbitTemplate) {
super(mongoTemplate);
this.raBidNetPriceRabbitTemplate = raBidNetPriceRabbitTemplate;
}
#Transactional
public void processTierMessages() {
try {
while (true) {
gson = getGsonBuilder().create();
byte[] body = (byte[]) raBidNetPriceRabbitTemplate.receiveAndConvert();
if (body == null) {
setFinished(true);
break;
}
tier1Message = gson.fromJson(new String(body), Tier1Message.class);
// document a 'Tier1' type so retrieve Tier1 first...
Tier1 tier1 = mongoTemplate.findById(tier1Message.getId(), Tier1.class);
Tier2Message tier2Message = new Tier2Message(tier1Message.getTran(), tier1Message.getId());
Tier2Process tierProcess = getTierProcess(tier2Message.getTran().getK12ArchitectureId());
Tier2 tier2 = new Tier2();
tier2.setId(tier1.getId());
tier2.setTier1Programs(tier1.getTier1Programs());
tier2.setCreated(tier1.getCreated());
tier2.setTran(tier1.getTran());
tierProcess.setTier(tier2);
tier2 = tier2.getTier2Programs().getRaBidNetPriceProgram().process(tierProcess);
mongoTemplate.save(tier2);
if (tier2.getTier2Programs().getRaBidNetPriceProgram().isFinished()) {
// publish event
publisher.publishEvent(new ProgramEvent(this, "FINISHED", tier2Message));
}
}
} catch (Exception e) {
LOGGER.error("id: " + tier1Message.getId() + " " + e.getMessage());
}
}
#Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.publisher = applicationEventPublisher;
}
}
Thank you,

CamelTestSupport read placeholders from yml file

I am trying to test my Camel Routes using CamelTestSupport. I have my routes defined in a class like this
public class ActiveMqConfig{
#Bean
public RoutesBuilder route() {
return new SpringRouteBuilder() {
#Override
public void configure() throws Exception {
from("activemq:{{push.queue.name}}").to("bean:PushEventHandler?method=handlePushEvent");
}
};
}
}
And my test class look like this
#RunWith(SpringRunner.class)
public class AmqTest extends CamelTestSupport {
#Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new ActiveMqConfig().route();
}
#Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
Properties properties = new Properties();
properties.put("pim2.push.queue.name", "pushevent");
return properties;
}
protected Boolean ignoreMissingLocationWithPropertiesComponent() {
return true;
}
#Mock
private PushEventHandler pushEventHandler;
#BeforeClass
public static void setUpClass() throws Exception {
BrokerService brokerSvc = new BrokerService();
brokerSvc.setBrokerName("TestBroker");
brokerSvc.addConnector("tcp://localhost:61616");
brokerSvc.setPersistent(false);
brokerSvc.setUseJmx(false);
brokerSvc.start();
}
#Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry jndi = super.createRegistry();
MockitoAnnotations.initMocks(this);
jndi.bind("pushEventHandler", pushEventHandler);
return jndi;
}
#Test
public void testConfigure() throws Exception {
template.sendBody("activemq:pushevent", "HelloWorld!");
Thread.sleep(2000);
verify(pushEventHandler, times(1)).handlePushEvent(any());
}}
This is working perfectly fine. But I have to set the placeholder {{push.queue.name}} using useOverridePropertiesWithPropertiesComponent function. But I want it to be read from my .yml file.
I am not able to do it. Can someone suggest.
Thanks
Properties are typically read from .properties files. But you can write some code that read the yaml file in the useOverridePropertiesWithPropertiesComponent method and put them into the Properties instance which is returned.
Thank Claus.
I got it working by doing this
#Override
protected Properties useOverridePropertiesWithPropertiesComponent() {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
PropertySource<?> applicationYamlPropertySource = loader.load(
"properties", new ClassPathResource("application.yml"),null);
Map source = ((MapPropertySource) applicationYamlPropertySource).getSource();
Properties properties = new Properties();
properties.putAll(source);
return properties;
} catch (IOException e) {
LOG.error("Config file cannot be found.");
}
return null;
}

Camel test using Intercept

I am trying to intercept a message to skip the Http request and proceed with my route.
Below is the class you can copy/paste to try it out.
Using camel-test, camel-core, camel-http4 2.10.2 and httpclient-osgi, httpcore-osgi 4.2.2
Here is the code :
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
/**
* Created with IntelliJ IDEA.
* User: lleclerc
* Date: 12-11-28
* Time: 16:34
* To change this template use File | Settings | File Templates.
*/
public class IsUseAdviceWithJUnit4Test extends CamelTestSupport {
private String providerEndPointURI = "http://stackoverflow.com";
private String timerEndPointURI = "timer://myTimer";
private String mockEndPointURI = "mock:myMock";
private String directEndPointURI = "direct:myDirect";
private boolean messageIntercepted;
#Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
#Override
public void configure() throws Exception {
from(timerEndPointURI + "?fixedRate=true&delay=1000&period=1000")
.to(providerEndPointURI + "?throwExceptionOnFailure=false")
.to(mockEndPointURI);
}
};
}
#Test
public void testIsUseAdviceWith() throws Exception {
messageIntercepted = false;
context.getRouteDefinitions().get(0).adviceWith(context, new AdviceWithRouteBuilder() {
#Override
public void configure() throws Exception {
replaceFromWith(directEndPointURI);
mockEndpoints();
interceptSendToEndpoint(providerEndPointURI)
.skipSendToOriginalEndpoint()
.process(new Processor() {
#Override
public void process(Exchange exchange) throws Exception {
messageIntercepted = true;
System.out.println("INTERCEPTED");
}
});
}
});
// we must manually start when we are done with all the advice with
context.start();
getMockEndpoint(mockEndPointURI).expectedMessageCount(1);
template.sendBody(directEndPointURI, "a trigger");
assertMockEndpointsSatisfied();
assertEquals(true, messageIntercepted);
assertNotNull(context.hasEndpoint(directEndPointURI));
assertNotNull(context.hasEndpoint("mock:" + directEndPointURI));
assertNotNull(context.hasEndpoint(mockEndPointURI));
}
#Override
public boolean isUseAdviceWith() {
return true;
}
#Override
public boolean isUseRouteBuilder() {
return true;
}
}
Thank you for your help !
There was bugs inside camel-http4.
http://camel.465427.n5.nabble.com/Found-a-bug-with-camel-http4-td5723733.html
http://camel.465427.n5.nabble.com/Test-Intercept-with-adviceWith-and-http-td5723473.html

Resources