Android App crashing on receipt of push notification - push-notification

My android application is crashing on receipt of push notification. The code im using is shown below
var CloudPush = require('ti.cloudpush');
var deviceToken = '';
//fetch device token
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
alert('Device Token: ' + deviceToken);
Ti.API.info('Device Token: ' + e.deviceToken);
},
error : function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
CloudPush.addEventListener('callback', function(evt) {
alert(evt.payload);
});
Im unable to figure out what i am doing wrong or find any information on this issue.
Any information would be really helpful. Thanks in advance.
PS - Im using Titanium SDK 3.1.0.
Logs listed below -
E/TiApplication(9474): (main) [27233,59667] Sending event: exception on thread: main msg:java.lang.NoSuchMethodError: org.appcelerator.titanium.TiApplication.isCurrentActivityInForeground; Titanium 3.1.0,2013/04/15 18:46,57634ef
E/TiApplication(9474): java.lang.NoSuchMethodError: org.appcelerator.titanium.TiApplication.isCurrentActivityInForeground
E/TiApplication(9474): at ti.cloudpush.CloudpushModuleGeneric.receivePayload(CloudpushModuleGeneric.java:81)
E/TiApplication(9474): at ti.cloudpush.GCMReceiver.onReceive(GCMReceiver.java:26) E/TiApplication(9474): at android.app.ActivityThread.handleReceiver(ActivityThread.java:2280)
E/TiApplication(9474): at android.app.ActivityThread.access$1600(ActivityThread.java:143)
E/TiApplication(9474): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
E/TiApplication(9474): at android.os.Handler.dispatchMessage(Handler.java:99)
E/TiApplication(9474): at android.os.Looper.loop(Looper.java:137)
E/TiApplication(9474): at android.app.ActivityThread.main(ActivityThread.java:4950)
E/TiApplication(9474): at java.lang.reflect.Method.invokeNative(Native Method)
E/TiApplication(9474): at java.lang.reflect.Method.invoke(Method.java:511)
E/TiApplication(9474): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
E/TiApplication(9474): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
E/TiApplication(9474): at dalvik.system.NativeStart.main(Native Method)

The error you got is :
E/TiApplication(9474): java.lang.NoSuchMethodError:
org.appcelerator.titanium.TiApplication.isCurrentActivityInForeground
Googling this method, I found it here.
That means you are probably using a jar that contains a wrong version of the org.appcelerator.titanium.TiApplication class.

I faced an issue while implementing the GCM push. It was due to the issue with CloudPush module I used. I was using CloudPush module 3.x. I changed the module back to 2.3.3 and it worked. Same issue will occur if your application is installed in Android 2.3.x devices. So try changing the Android CloudPush module to 2.3.3 and don't forget to specify the version on TiApp.xml

Related

BackoffExceptions are logged at error level when using RetryTopicConfiguration

I am a happy user of the recently added RetryTopicConfiguration there is however a small issue that is bothering me.
The setup I use looks like:
#Bean
public RetryTopicConfiguration retryTopicConfiguration(
KafkaTemplate<String, String> template,
#Value("${kafka.topic.in}") String topicToInclude,
#Value("${spring.application.name}") String appName) {
return RetryTopicConfigurationBuilder
.newInstance()
.fixedBackOff(5000L)
.maxAttempts(3)
.retryTopicSuffix("-" + appName + ".retry")
.suffixTopicsWithIndexValues()
.dltSuffix("-" + appName + ".dlq")
.includeTopic(topicToInclude)
.dltHandlerMethod(KAFKA_EVENT_LISTENER, "handleDltEvent")
.create(template);
}
When the a listener throws an exception that triggers a retry, the DefaultErrorHandler will log a KafkaBackoffException at error level.
For a similar problem it was suggested to use a ListenerContainerFactoryConfigurer yet this does not remove all error logs, since I still see the following in my logs:
2022-04-02 17:34:33.340 ERROR 8054 --- [e.retry-0-0-C-1] o.s.kafka.listener.DefaultErrorHandler : Recovery of record (topic-spring-kafka-logging-issue.retry-0-0#0) failed
org.springframework.kafka.listener.ListenerExecutionFailedException: Listener failed; nested exception is org.springframework.kafka.listener.KafkaBackoffException: Partition 0 from topic topic-spring-kafka-logging-issue.retry-0 is not ready for consumption, backing off for approx. 4468 millis.
Can the log-level be changed, without adding a custom ErrorHandler?
Spring-Boot version: 2.6.6
Spring-Kafka version: 2.8.4
JDK version: 11
Sample project: here
Thanks for such a complete question. This is a known issue of Spring for Apache Kafka 2.8.4 due to the new combine blocking and non-blocking exceptions feature and has been fixed for 2.8.5.
The workaround is to clear the blocking exceptions mechanism such as:
#Bean(name = RetryTopicInternalBeanNames.LISTENER_CONTAINER_FACTORY_CONFIGURER_NAME)
public ListenerContainerFactoryConfigurer lcfc(KafkaConsumerBackoffManager kafkaConsumerBackoffManager,
DeadLetterPublishingRecovererFactory deadLetterPublishingRecovererFactory,
#Qualifier(RetryTopicInternalBeanNames
.INTERNAL_BACKOFF_CLOCK_BEAN_NAME) Clock clock) {
ListenerContainerFactoryConfigurer lcfc = new ListenerContainerFactoryConfigurer(kafkaConsumerBackoffManager, deadLetterPublishingRecovererFactory, clock);
lcfc.setBlockingRetriesBackOff(new FixedBackOff(0, 0));
lcfc.setErrorHandlerCustomizer(eh -> ((DefaultErrorHandler) eh).setClassifications(Collections.emptyMap(), true));
return lcfc;
}
Please let me know if that works for you.
Thanks.
EDIT:
This workaround disables only blocking retries, which since 2.8.4 can be used along non-blocking as per the link in the original answer. The exception classification for the non-blocking retries is in the DefaultDestinationTopicResolver class, and you can set FATAL exceptions as documented here.
EDIT: Alternatively, you can use the Spring Kafka 2.8.5-SNAPSHOT version by adding the Spring Snapshot repository such as:
repositories {
maven {
url 'https://repo.spring.io/snapshot'
}
}
dependencies {
implementation 'org.springframework.kafka:spring-kafka:2.8.5-SNAPSHOT'
}
You can also downgrade to Spring Kafka 2.8.3.
As Gary Russell pointed out, if your application is already in production you should not use the SNAPSHOT version, and 2.8.5 is out in a couple of weeks.
EDIT 2: Glad to hear you’re happy about the feature!

Titanium appcelerator error when opening window after push notification received

I use titanium appcelerator for a little app, with pushwoosh as notification server.
On my index.xml i have following :
<Alloy>
<!-- Anddroid Window -->
<Window id="index" platform="android">
<Require type="view" id="firstscreen" src="firstscreen"/>
</Window>
<!-- iOS Window -->
<NavigationWindow id="nav" platform="ios">
<Window id="win1" backgroundColor="white">
<Require type="view" id="firstscreen" src="firstscreen"/>
</Window>
</NavigationWindow>
</Alloy>
secondly index.js, where i receive push and want to redirect user to login js for example, the aim is to open corresponding page from push custom value, but here i do it simple, just for test.
if (OS_ANDROID) {
$.index.addEventListener('open', after_win_load);
$.index.open();
} else {
$.nav.addEventListener('open', after_win_load);
$.nav.open();
}
var pushwoosh = require('com.pushwoosh.module');
/*
* PUSHWOOSH
* */
pushwoosh.onPushOpened(function(e) {
var message = e.message;
var login = Alloy.createController('login').getView();
$.nav.open(login);
});
pushwoosh.initialize({
"application" : "XXXX-XXXXXX",
"gcm_project" : "XXXXXXXXXXX"
});
pushwoosh.registerForPushNotifications(
function(e) {
var pushToken = e.registrationId;
;
console.log('Push token ' + pushwoosh.getPushToken());
Alloy.Globals.resgisterId = e.registrationId;
},
function(e) {
var errorMessage = e.error;
console.log("Error during registration: " + e.error);
// alert('push error');
}
);
And the last login.xml and login.js
<Alloy>
<Window id="login" >
<ScrollView scrollingEnabled="true" contentWidth="Ti.UI.FILL" disableBounce="true">
<!-- Here another view -->
</ScrollView>
</Window>
</Alloy>
//// login.js is simple :
var args = $.args;
console.log('hey boy');
When receiving push notification, and click on it to redirect to login js i have following error :
[WARN] : Creating [object login] in a different context than the calling function.
[WARN] : Creating [object __alloyId48] in a different context than the calling function.
[ERROR] : Script Error {
[ERROR] : column = 2330;
[ERROR] : line = 1;
[ERROR] : message = "null is not an object (evaluating 'a.__views.login.add')";
[ERROR] : sourceURL = "file:///var/containers/Bundle/Application/ADE5F25A-17A4-4197-98C7-0781216545A3/myApp.app/alloy/controllers/login.js";
[ERROR] : stack = "Controller#file:///var/containers/Bundle/Application/ADE5F25A-17A4-4197-98C7-0781216545A3/myApp.app/alloy/controllers/login.js:1:2330\ncreateController#file:///var/containers/Bundle/Application/ADE5F25A-17A4-4197-98C7-0781216545A3/myApp.app/alloy.js:1:5254\nopenWin#file:///var/containers/Bundle/Application/ADE5F25A-17A4-4197-98C7-0781216545A3/myApp.app/xpng.js:1:283\nfile:///var/containers/Bundle/Application/ADE5F25A-17A4-4197-98C7-0781216545A3/myApp.app/alloy/controllers/firstscreen.js:1:3855";
[ERROR] : }
I have no idea where the error is, could you please help me to resolve this?
Thank you.
You just need a little change in code:
pushwoosh.onPushOpened(function(e) {
var message = e.message;
var login = Alloy.createController('login').getView();
OS_IOS ? $.nav.openWindow(login) : login.open();
});
For iOS - you need to use openWindow() method of NavigationWindow, and for Android it's simple open() call.
Note:
Since you mentioned that you want to navigate user to different section of the app, so you will need to take care that your NavigationWindow exists before you open another window in it.
That's why you are getting that null error because when you receive notification and you tap on it, it opens the app and run this pushwoosh.onPushOpened method, and till this time you don't have any NavigationWindow created. So you need a different flow for navigation to different sections.
After tapping on notification, if your app is running in background mode, then I believe you won't get this error because you already have a NavigationWindow created,
But if your app is in killed state and you receive and tap on notification, then you will get this error because your app has no NavigationWindow created yet (that's why you see the different context written on console).
So to do what you want, you will need to create a different flow to handle the scenario of opening the app's login window upon receiving a push message. (in simple words you'll still need to create NavigationWindow and open login window in it or a different approach).
I hope you now have the clear idea of what actually causing your app to show that error.

Handling client and server error on grpc java/node

I am using grpc to communicate between a Java server and node client. When either of them die/crash the other dies to.
Here is the exception thrown on Java server when node client dies -
Nov 08, 2016 11:28:03 AM io.grpc.netty.NettyServerHandler onConnectionError
WARNING: Connection Error
java.io.IOException: An existing connection was forcibly closed by the remote host
at sun.nio.ch.SocketDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:43)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:288)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1100)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:349)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:112)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:571)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:512)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:426)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:398)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:877)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:745)
Here is the exception thrown on node when java dies:
events.js:141
throw er; // Unhandled 'error' event
^
Error: {"created":"#1478623914.082000000","description":"An existing connection was forcibly closed by the remote host.\r\n","file":"..\src\core\lib\iomgr\tcp_windows.c","file_line":171,"grpc_status":14}
at ClientReadableStream._emitStatusIfDone ( C:\HarshalDev\Live_TDFX\TDSL0007-TDFXPlatfo rmsDesignandBuild\tdfxlive\node_modules\grpc\src\node\src\client.js:189:19)
at ClientReadableStream._receiveStatus (C:\ HarshalDev\Live_TDFX\TDSL0007-TDFXPlatformsDesignandBuild\tdfxlive\node_modules\grpc\src\node\src\client.js:169:8)
at C:\HarshalDev\Live_TDFX\TDSL0007-TDFXPlatformsDesignandBuild\tdfxlive\node_modules\grpc\src\node\src\client.js:577:14
[nodemon] app crashed - waiting for file changes before starting...
QUESTION - How do I handle those exceptions?
I tried without any success adding try/catch and adding a uncaught exception handlers for threads.
Java code to initialize -
ServerBuilder<?> serverBuilder = ServerBuilder.forPort(getPort());
server = serverBuilder
.addService(createBwayStreamingService())
.addService(ServerInterceptors.intercept(createBwayOrderService(), authServerInterceptor))
.addService(createBwayInstrumentService())
.addService(createBwaySettlementService())
.addService(createBwayDateTimeService())
.addService(ServerInterceptors.intercept(createBwayConfService(), authServerInterceptor))
.addService(ServerInterceptors.intercept(createBwayTradeService(), authServerInterceptor))
.addService(ServerInterceptors.intercept(createBwayAuthService(), authServerInterceptor))
.build();
Preconditions.checkNotNull(server);
server.start();
System.out.println("Server started, listening on " + getPort());
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
System.out.println("Shutting down gRPC server");
TocGateway.this.stop();
System.out.println("Server shut down");
}
});
server.awaitTermination();
Node client handler (one of the services, all other services use the same pattern) -
let protoDescriptorStreaming = grpc.load((process.env.FX_LIVE_PROTO_DIR || '../tocGateway/src/main/proto') + '/streaming.proto');
let streamingService = new protoDescriptorStreaming.tds.fxlive.bway.BwayStreamService(process.env.TOC_GATEWAY_ADDRESS || 'localhost:8087', grpc.credentials.createInsecure());
The Java warning is harmless. Your application should continue running normally after the exception. It would be nice to reduce the log level to have less logspam, but it also shouldn't impact the correctness of your application.

sending mail using thymeleaf in Spring Schedular

I am trying to send email using thymeleaf template. But I am getting an error message as
org.thymeleaf.exceptions.TemplateProcessingException: Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]
at org.thymeleaf.resourceresolver.ServletContextResourceResolver.getResourceAsStream(ServletContextResourceResolver.java:74)
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:221)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1192)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1148)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1095)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1008)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:982)
at in.coep.vlabteam.leap.implementations.ScheduleNotificationImpl.sendNotification(ScheduleNotificationImpl.java:205)
at in.coep.vlabteam.leap.implementations.ScheduleNotificationImpl.sendScheduleNotificationMail(ScheduleNotificationImpl.java:105)
at in.coep.vlabteam.leap.services.ScheduleNotificationService.sendScheduleNotificationByMail(ScheduleNotificationService.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:98)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:206)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
10936 [taskScheduler-1] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][taskScheduler-1] Exception processing template "scheduleMail.html": Resource resolution by ServletContext with org.thymeleaf.resourceresolver.ServletContextResourceResolver can only be performed when context implements org.thymeleaf.context.IWebContext [current context: org.thymeleaf.context.Context]
I cant used WebContext() instead of Context(). Because for webContext I need HttpServletRequest object that I can't get here, because it is not in scope of request.
I am trying to send mail using context(), but I am getting an error.
Please anyone have solution on this. Thanks in advance
Here is my code,
final Context ctx = new Context();
ctx.setVariable("eagletId", user.getEagletId());
ctx.setVariable("name", user.getFirstName());
ctx.setVariable("setSentDate", new Date());
ctx.setVariable("department", user.getDepartment());
ctx.setVariable("batch", user.getBatch());
// ctx.setVariable("month" Constants.LeapConstants.UserType);
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message =
new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
message.setSubject("Create your report for month");
message.setFrom("leap#gmail.com");
message.setTo("vlab#gmail.com");
// Create the HTML body using Thymeleaf
final String htmlContent = this.templateEngine.process("scheduleMail.html", ctx);
message.setText(htmlContent, true /* isHtml */);
// Send mail
this.mailSender.send(mimeMessage);
Your template engine is configured with ServletContextTemplateResolver instead of either FileTemplateResolver or ClassLoaderTemplateResolver. This will be defined most likely in a spring config file somewhere. If configured in code, see the Thymeleaf user's guide on configuring the template engine and configuration of the templateResolver. It's good doc.
Via xml configuration, it should look something like this:
<beans:bean id="templateResolver"
class="org.thymeleaf.templateresolver.ClassLoaderTemplateResolver">
</beans:bean>

JSoup randomly throws java.io.IOException: stream is closed when running from browser

I'm having some weird JSoup problem when running my JavaFX application from the browser (or as web-start).
When I run from inside the IDE (Eclipse or Netbeans) or as a standalone app, it runs normally. When I try to run as a web-start or from the browser (Chrome), JSoup randomly throws a "java.io.IOException: stream is closed".
The site I'm trying to parse is thepiratebay.sx. When I first run the application (from browser), I get this error. With the application running, if I try to parse again, than it works... sometimes.
The JSoup code:
try {
//TODO: Change to HttpFetcher. This method is reporting "stream is closed" when running on browser
Connection con = Jsoup.connect(url)
.timeout(HTTP_TIMEOUT)
.userAgent(UserAgentGenerator.getUserAgent())
.followRedirects(false);
doc = con.get();
System.out.println("Fetching... " + url);
} catch (IOException e) {
e.printStackTrace();
System.out.println("Parser connect must have timed out, no results. " + url);
fetchFailed[i] = true;
continue;
}
finally {
i++;
if (CommonTFUtils.isAllTrue(fetchFailed)) {
throw new HttpException("Fetcher failed on every URL of " + response.getSite_name());
}
}
And the exception thrown:
CacheEntry[http://thepiratebay.sx/browse/207/0/7]: updateAvailable=true,lastModified=Tue May 14 14:28:16 BRT 2013,length=-1
java.io.IOException: stream is closed
at sun.net.www.http.ChunkedInputStream.ensureOpen(Unknown Source)
at sun.net.www.http.ChunkedInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.close(Unknown Source)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:468)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:410)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:164)
at org.jsoup.helper.HttpConnection.get(HttpConnection.java:153)
at com.package.torrent.parser.GenericParser.search(GenericParser.java:147)
at com.package.torrent.parser.GenericParser.browse(GenericParser.java:82)
at com.package.search.TrackerSearch.searchTracker(TrackerSearch.java:69)
at com.package.search.TrackerSearch.searchAllTrackers(TrackerSearch.java:40)
at com.package.search.TrackerSearch.searchAllTrackers(TrackerSearch.java:23)
at com.package.search.MovieBrowser.browseTrackers(MovieBrowser.java:49)
at com.package.ui.browse.BrowseController$MovieBrowserTask.call(BrowseController.java:237)
at com.package.ui.browse.BrowseController$MovieBrowserTask.call(BrowseController.java:213)
at javafx.concurrent.Task$TaskCallable.call(Task.java:1259)
at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Does anyone have an idea of what might be causing this?
Thanks in advance.
I think I found a solution. Place this code before you ever call JSoup. Apparently, applets and web start set this value to true. Now, I wonder why Sun forces you to access a static variable non-statically.
new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
JSoup doesn't handle well when the URL is cached and treats it as an exception.

Resources