RTMPMinaConnection - Incoming message handling failed while encoding RTP to RTMP with xuggler - red5

I recently posted a question regarding an issue I was getting a PixelType error. You can read that post here
I think I resolved that issue by creating the following class.
package com.mwallace.xuggler.tools;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.AudioSamplesEvent;
import com.xuggle.mediatool.event.IAddStreamEvent;
import com.xuggle.mediatool.event.IAudioSamplesEvent;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.mediatool.event.VideoPictureEvent;
import com.xuggle.xuggler.IAudioResampler;
import com.xuggle.xuggler.IAudioSamples;
import com.xuggle.xuggler.IError;
import com.xuggle.xuggler.IPixelFormat;
import com.xuggle.xuggler.IStreamCoder;
import com.xuggle.xuggler.IVideoPicture;
import com.xuggle.xuggler.IVideoResampler;
import com.xuggle.xuggler.ICodec;
public class ConvertVideo extends MediaToolAdapter implements Runnable
{
private int VIDEO_WIDTH = 640;
private int VIDEO_HEIGHT = 480;
private IMediaWriter writer;
private IMediaReader reader;
private String outputFile;
private IVideoResampler videoResampler = null;
private IAudioResampler audioResampler = null;
public ConvertVideo(String inputFile, String outputFile)
{
this.outputFile = outputFile;
reader = ToolFactory.makeReader(inputFile);
reader.addListener(this);
}
#Override
public void onAddStream(IAddStreamEvent event)
{
int streamIndex = event.getStreamIndex();
IStreamCoder streamCoder = event.getSource().getContainer()
.getStream(streamIndex).getStreamCoder();
if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO)
{
writer.addAudioStream(streamIndex, streamIndex, 2, 44100);
} else if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO)
{
streamCoder.setWidth(VIDEO_WIDTH);
streamCoder.setHeight(VIDEO_HEIGHT);
writer.addVideoStream(streamIndex, streamIndex, VIDEO_WIDTH,
VIDEO_HEIGHT);
}
super.onAddStream(event);
}
#Override
public void onVideoPicture(IVideoPictureEvent event)
{
IVideoPicture pic = event.getPicture();
if (videoResampler == null)
{
videoResampler = IVideoResampler.make(VIDEO_WIDTH, VIDEO_HEIGHT,
pic.getPixelType(), pic.getWidth(), pic.getHeight(),
pic.getPixelType());
System.out.println("width and height : " + pic.getPictureType() + " : " + pic.getWidth() + " : " + pic.getHeight());
}
IVideoPicture out = IVideoPicture.make(IPixelFormat.Type.YUV420P, VIDEO_WIDTH,
VIDEO_HEIGHT);
videoResampler.resample(out, pic);
IVideoPictureEvent asc = new VideoPictureEvent(event.getSource(), out,
event.getStreamIndex());
super.onVideoPicture(asc);
out.delete();
}
#Override
public void onAudioSamples(IAudioSamplesEvent event)
{
IAudioSamples samples = event.getAudioSamples();
if (audioResampler == null)
{
audioResampler = IAudioResampler.make(2, samples.getChannels(),
44100, samples.getSampleRate());
}
if (event.getAudioSamples().getNumSamples() > 0)
{
IAudioSamples out = IAudioSamples.make(samples.getNumSamples(),
samples.getChannels());
audioResampler.resample(out, samples, samples.getNumSamples());
AudioSamplesEvent asc = new AudioSamplesEvent(event.getSource(),
out, event.getStreamIndex());
super.onAudioSamples(asc);
out.delete();
}
}
#Override
public void run()
{
writer = ToolFactory.makeWriter(outputFile, reader);
//writer.addListener(ToolFactory.makeViewer(true));
this.addListener(writer);
while (reader.readPacket() == null)
{
System.out.println("reading packet");
IError err = null;
if (reader != null)
{
err = reader.readPacket();
}
if(err != null ){
System.out.println("Error: " + err);
break;
}
}
}
}
After my Flash client connects successfully I then call a method on the server called helloXuggler() that looks something like this in my main Application file.
public static void helloXuggler()
{
String sourceUrl = "rtsp://10.0.1.68:8554/CH001.sdp?AuthMode=Web&AuthValue=6049";
String destinationUrl = "./webapps/AEWings/streams/xuggler.flv";
//this.convertVideo = new ConvertVideo(sourceURL, destinationURL);
System.out.printf("transcode %s -> %s\n", sourceUrl, destinationUrl);
ConvertVideo converter = new ConvertVideo(sourceUrl, destinationUrl);
converter.run();
// read packets from the source file, which dispatch events to the
// writer, this will continue until
}
All seems to go well and everything connects and the method gets called but after maybe 30 seconds or so I get the following stack trace and I'm not sure what to do about it.
[WARN] [NioProcessor-2] org.red5.server.net.rtmp.RTMPMinaConnection - Incoming message handling failed on HFQIN76JSTZXW
org.springframework.core.task.TaskRejectedException: Executor [java.util.concurrent.ThreadPoolExecutor#68e415b8] did not accept task: org.springframework.util.concurrent.ListenableFutureTask#4279ae24
at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.submitListenable(ThreadPoolTaskExecutor.java:297) ~[spring-context-4.0.3.RELEASE.jar:4.0.3.RELEASE]
at org.red5.server.net.rtmp.RTMPMinaConnection.handleMessageReceived(RTMPMinaConnection.java:159) ~[red5-server.jar:na]
at org.red5.server.net.rtmp.RTMPMinaIoHandler.messageReceived(RTMPMinaIoHandler.java:167) [red5-server.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain$TailFilter.messageReceived(DefaultIoFilterChain.java:690) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:417) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:47) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:765) [mina-core-2.0.7.jar:na]
at org.apache.mina.filter.codec.ProtocolCodecFilter$ProtocolDecoderOutputImpl.flush(ProtocolCodecFilter.java:407) [mina-core-2.0.7.jar:na]
at org.apache.mina.filter.codec.ProtocolCodecFilter.messageReceived(ProtocolCodecFilter.java:236) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:417) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:47) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:765) [mina-core-2.0.7.jar:na]
at org.red5.server.net.rtmpe.RTMPEIoFilter.messageReceived(RTMPEIoFilter.java:132) [red5-server.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:417) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.access$1200(DefaultIoFilterChain.java:47) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain$EntryImpl$1.messageReceived(DefaultIoFilterChain.java:765) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.IoFilterAdapter.messageReceived(IoFilterAdapter.java:109) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.callNextMessageReceived(DefaultIoFilterChain.java:417) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.filterchain.DefaultIoFilterChain.fireMessageReceived(DefaultIoFilterChain.java:410) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:710) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:664) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:653) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$600(AbstractPollingIoProcessor.java:67) [mina-core-2.0.7.jar:na]
at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1124) [mina-core-2.0.7.jar:na]
at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64) [mina-core-2.0.7.jar:na]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) [na:1.6.0_65]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) [na:1.6.0_65]
at java.lang.Thread.run(Thread.java:695) [na:1.6.0_65]
Caused by: java.util.concurrent.RejectedExecutionException: null
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1774) ~[na:1.6.0_65]
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:768) ~[na:1.6.0_65]
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:656) ~[na:1.6.0_65]
at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.submitListenable(ThreadPoolTaskExecutor.java:293) ~[spring-context-4.0.3.RELEASE.jar:4.0.3.RELEASE]
... 27 common frames omitted

Related

How to check whatsapp sticker is already added or not in react native?

I am facing an issue related to WhatsApp sticker implementation. I have used this library I want to check that particular sticker is already added or not in WhatsApp.
How can I achieve this? Please guide me.
I have used below file from this library. isPackageInstalled() function worked for me (Note : I just wanted this functionality only for Android)
package org.roborox.whatsapp;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.Uri;
import androidx.annotation.NonNull;
public class WhitelistCheck {
private static final String AUTHORITY_QUERY_PARAM = "authority";
private static final String IDENTIFIER_QUERY_PARAM = "identifier";
private static String STICKER_APP_AUTHORITY = "sticker_pack_authority";// StickerContentProvider.authority;
public static String CONSUMER_WHATSAPP_PACKAGE_NAME = "com.whatsapp";
public static String INSTAGRAM_PACKAGE_NAME = "com.instagram.android";
public static String SMB_WHATSAPP_PACKAGE_NAME = "com.whatsapp.w4b";
private static String CONTENT_PROVIDER = ".provider.sticker_whitelist_check";
private static String QUERY_PATH = "is_whitelisted";
private static String QUERY_RESULT_COLUMN_NAME = "result";
public static boolean isWhitelisted(#NonNull Context context, #NonNull String identifier) {
try {
boolean consumerResult = isWhitelistedFromProvider(context, identifier, CONSUMER_WHATSAPP_PACKAGE_NAME);
boolean smbResult = isWhitelistedFromProvider(context, identifier, SMB_WHATSAPP_PACKAGE_NAME);
return consumerResult && smbResult;
} catch (Exception e) {
return false;
}
}
private static boolean isWhitelistedFromProvider(#NonNull Context context, #NonNull String identifier, String whatsappPackageName) {
final PackageManager packageManager = context.getPackageManager();
if (isPackageInstalled(whatsappPackageName, packageManager)) {
final String whatsappProviderAuthority = whatsappPackageName + CONTENT_PROVIDER;
final ProviderInfo providerInfo = packageManager.resolveContentProvider(whatsappProviderAuthority, PackageManager.GET_META_DATA);
// provider is not there.
if (providerInfo == null) {
return false;
}
final Uri queryUri = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(whatsappProviderAuthority).appendPath(QUERY_PATH).
appendQueryParameter(AUTHORITY_QUERY_PARAM, BuildConfig.CONTENT_PROVIDER_AUTHORITY).appendQueryParameter(IDENTIFIER_QUERY_PARAM, identifier).build();
final Cursor cursor = context.getContentResolver().query(queryUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int whiteListResult = cursor.getInt(cursor.getColumnIndexOrThrow(QUERY_RESULT_COLUMN_NAME));
return whiteListResult == 1;
}
} else {
//if app is not installed, then don't need to take into its whitelist info into account.
return true;
}
return false;
}
public static boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
final ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
//noinspection SimplifiableIfStatement
if (applicationInfo != null) {
return applicationInfo.enabled;
} else {
return false;
}
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
public static boolean redirectToInstagram(Context context) {
final PackageManager packageManager = context.getPackageManager();
if (isPackageInstalled(INSTAGRAM_PACKAGE_NAME, packageManager)) {
Intent i = context.getPackageManager().getLaunchIntentForPackage(INSTAGRAM_PACKAGE_NAME);
context.startActivity(i);
return true;
} else {
return false;
}
}
}

While true loop executed only a limited amount of times

So i have this telegram bot and i have a while loop in the main string args because i need it to check something for eternity. But after a while or even emediatly the while loop stops.
import org.telegram.telegrambots.ApiContextInitializer;
import org.telegram.telegrambots.TelegramBotsApi;
import org.telegram.telegrambots.exceptions.TelegramApiException;
import java.time.Duration;
import java.time.LocalDateTime;
public class Main {
public static void main(String[] args) {
// Initialize Api Context
ApiContextInitializer.init();
boolean running = false;
// Instantiate Telegram Bots API
TelegramBotsApi botsApi = new TelegramBotsApi();
SwtPremiumBot bot = new SwtPremiumBot();
// Register our bot
try {
botsApi.registerBot(bot);
System.out.println("BOT REGISTERED");
running=true;
//storing the filIDS
String[] files=new String[9];
files[0]="AgADBAADa6wxG1gRcVGzXAwfpuZjo0JZJhoABOvVf8G55uyhXeUEAAEC";
files[1]="AgADBAADbKwxG1gRcVGGoZcrmZ786ph7jBoABG7SjlCeIwnjXngDAAEC";
files[2]="AgADBAADbawxG1gRcVFwF6pUv1RskZ1GKRoABMefcdSzWLaxYWIFAAEC";
files[3]="AgADBAADbqwxG1gRcVGB0noIZtEpgypbNBoABL1GJAMM9QxqElABAAEC";
files[4]="AgADBAADcqwxG1gRcVGBiPqbusQgZmBLkRoABE-nBSP6FJZYGnEAAgI";
files[5]="AgADBAADc6wxG1gRcVHwFx4ec9kWnafJKhoABMBQxr6mC9qHXFsFAAEC";
files[6]="AgADBAADdKwxG1gRcVERF469BLWkMB0LkRkABOfM_ioz6u6iG0oAAgI";
files[7]="AgADBAADdawxG1gRcVFa7fItTXuxtu0JjhoABMl076IfG9VFB3oDAAEC";
files[8]="AgADBAADdqwxG1gRcVHEf5OseR1P4aTlkBkABFGmx73rlPOjUksAAgI";
String[] gifs=new String[13];
gifs[0]="CgADBAADYAIAAlgRcVFuikWviGM3ugI";
gifs[1]="CgADBAADYQIAAlgRcVEEWh_ZQxpfNAI";
gifs[2]="CgADBAADYgIAAlgRcVEpmx9MY-rSHwI";
gifs[3]="CgADBAADYwIAAlgRcVF0pJYhUNuCIwI";
gifs[4]="CgADBAADZAIAAlgRcVFvJlndVDLAaAI";
gifs[5]="CgADBAADZQIAAlgRcVFzc-BYUtICfAI";
gifs[6]="CgADBAADZgIAAlgRcVFML1TuOWgTFQI";
gifs[7]="CgADBAADZwIAAlgRcVGDlLtcdA1gGgI";
gifs[8]="CgADBAADaAIAAlgRcVHk0_p_0xy4XQI";
gifs[9]="CgADBAADaQIAAlgRcVH9Y38kRM025QI";
gifs[10]="CgADBAADagIAAlgRcVH7ZXg3Vvju9AI";
gifs[11]="CgADBAADawIAAlgRcVG00SeL2VBKowI";
gifs[12]="CgADBAADbAIAAlgRcVFetih9aTXW8gI";
bot.setFileIds(files);
bot.setGifs(gifs);
} catch (TelegramApiException e) {
e.printStackTrace();
String error = e.toString();
bot.addErrors(error, LocalDateTime.now());
}
LocalDateTime lastCheck = LocalDateTime.now();
while (running){
LocalDateTime now = LocalDateTime.now();
Duration d = Duration.between(lastCheck, now);
long duration = d.toMillis();
if (duration>20000) {
bot.checkCompleteOrders();
bot.checkPublishTime();
lastCheck = LocalDateTime.now();
System.out.println("Orders checked.");
}
}
String error = "WHILE LOOP BROKEN";
bot.addErrors(error, LocalDateTime.now());
}
}
Thanks in advance.

Read data from database using UDF in pig

I have requirement to read data from a database and analyse the data using pig.
I have written a UDF in java Referring following link
register /tmp/UDFJars/CassandraUDF_1-0.0.1-SNAPSHOT-jar-with-dependencies.jar;
A = Load '/user/sampleFile.txt' using udf.DBLoader('10.xx.xxx.4','username','password','select * from customer limit 10') as (f1 : chararray);
DUMP A;
package udf;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.mapreduce.InputFormat;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.pig.LoadFunc;
import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigSplit;
import org.apache.pig.data.Tuple;
import org.apache.pig.data.TupleFactory;
import com.data.ConnectionCassandra;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
public class DBLoader extends LoadFunc {
private final Log log = LogFactory.getLog(getClass());
Session session;
private ArrayList mProtoTuple = null;
private String jdbcURL;
private String user;
private String pass;
private int count = 0;
private String query;
ResultSet result;
List<Row> rows;
int colSize;
protected TupleFactory mTupleFactory = TupleFactory.getInstance();
public DBLoader() {
}
public DBLoader(String jdbcURL, String user, String pass, String query) {
this.jdbcURL = jdbcURL;
this.user = user;
this.pass = pass;
this.query = query;
}
#Override
public InputFormat getInputFormat() throws IOException {
log.info("Inside InputFormat");
// TODO Auto-generated method stub
try {
return new TextInputFormat();
} catch (Exception exception) {
log.error(exception.getMessage());
log.error(exception.fillInStackTrace());
throw new IOException();
}
}
#Override
public Tuple getNext() throws IOException {
log.info("Inside get Next");
Row row = rows.get(count);
if (row != null) {
mProtoTuple = new ArrayList<Object>();
for (int colNum = 0; colNum < colSize; colNum++) {
mProtoTuple.add(row.getObject(colNum));
}
} else {
return null;
}
Tuple t = mTupleFactory.newTuple(mProtoTuple);
mProtoTuple.clear();
return t;
}
#Override
public void prepareToRead(RecordReader arg0, PigSplit arg1) throws IOException {
log.info("Inside Prepare to Read");
session = null;
if (query == null) {
throw new IOException("SQL Insert command not specified");
}
if (user == null || pass == null) {
log.info("Creating Session with user name and password as: " + user + " : " + pass);
session = ConnectionCassandra.connectToCassandra1(jdbcURL, user, pass);
log.info("Session Created");
} else {
session = ConnectionCassandra.connectToCassandra1(jdbcURL, user, pass);
}
log.info("Executing Query " + query);
result = session.execute(query);
log.info("Query Executed :" + query);
rows = result.all();
count = 0;
colSize = result.getColumnDefinitions().asList().size();
}
#Override
public void setLocation(String location, Job job) throws IOException {
log.info("Inside Set Location");
try {
FileInputFormat.setInputPaths(job, location);
} catch (Exception exception) {
log.info("Some thing went wrong : " + exception.getMessage());
log.debug(exception);
}
}
}
Above is my pig script and java code.
Here /user/sampleFile.txt is a dummy file with no data.
I am getting following exception:
Pig Stack Trace
ERROR 1066: Unable to open iterator for alias A
org.apache.pig.impl.logicalLayer.FrontendException: ERROR 1066: Unable to open iterator for alias A
at org.apache.pig.PigServer.openIterator(PigServer.java:892)
at org.apache.pig.tools.grunt.GruntParser.processDump(GruntParser.java:774)
at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:372)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:198)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:173)
at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:84)
at org.apache.pig.Main.run(Main.java:484)
at org.apache.pig.Main.main(Main.java:158)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.hadoop.util.RunJar.run(RunJar.java:221)
at org.apache.hadoop.util.RunJar.main(RunJar.java:136)
Caused by: java.io.IOException: Job terminated with anomalous status FAILED
at org.apache.pig.PigServer.openIterator(PigServer.java:884)
... 13 more
Vivek! Do you even get in prepareToRead? (I see you did some logging, so it would be nice to know what you actually have in log) Also it would be really great to provide full stacktrace as I see you don't have full underlying exception.
Just some thoughts - I never tried writing a LoadFunc without implementing my own InputFormat and RecordReader - TextInputFormat checks for file existence and it's size (and creates a number of InputSplits based on file size(s)), so if your dummy file is empty there is a big possibility that no InputSplits are produced or zero-length InputSplit is produced. As it has zero-length it may cause pig to throw that exception. So the good suggestion is to implement own InputFormat (it's actually pretty easy). Also just as a fast try - try
set pig.splitCombination false
Probably it won't help, but it's easy to try.

NullpointerException allthough reference is passed

Irc client which can make multiple connections to different irc servers.
Each tab represents a server connection. I want a connection closed when its tab is closed.
When i start a connection using the menuitembutton event i construct a serverConnection object, passing it to the main controller (serverConnection con) before i launch the communication method in a new thread.
Now the problem is that when onTabClose event is fired i get a nullpointerexception when i use the reference from the main controller to change a flag so that the method running in the thread will return and eventually stop instead of using the deprecated thread.stop() method. (Keep in mind that a thread using that object is already running)
Why do i get that exception when i have already passed a reference? (garbage collector can't have touched the object since it's used in the thread and main controller reference)
serverConnection class
package jircclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.function.Consumer;
public class serverConnection
{
//VARIABLES
public clientInfo client;
private String server_to_connect;
private String channel_to_connect;
private String serv_resp;
private int port;
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private ArrayList<channel> channels;
public boolean threadExitFlag = false;
//DEFAULT CONSTRUCTOR
public serverConnection() {}
//FULL CONSTRUCTOR
public serverConnection(clientInfo clientInfo, String server_to_connect, int port, String channel_to_connect) throws IOException
{
this.client = clientInfo;
this.server_to_connect = server_to_connect;
this.port = port;
this.channel_to_connect = channel_to_connect;
try
{
//Creating socket connection
this.socket = new Socket(this.server_to_connect,port);
//Socket output writer
writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
//Socket input writer
reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
serv_resp = null;
System.out.println("Connection established.");
}
catch(UnknownHostException exc)
{
System.out.println("ERROR: "+ exc.toString());
}
catch(IOException exc)
{
System.out.println("ERROR: "+ exc.toString());
}
finally
{
System.out.println("Closing connection.");
socket.close();
}
}
public Consumer<String> messageCallback ;
public void setMessageCallback(Consumer<String> messageCallback) {
this.messageCallback = messageCallback ;
}
//server response getter
public String getServerResponse()
{
return serv_resp;
}
public void exitThread()
{
this.threadExitFlag = true;
}
//Introduction to server and listen
public void startCommunication() throws IOException
{
//
this.socket = new Socket(this.server_to_connect,port);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
serv_resp = null;
//
writer.write("NICK " + client.getClientNickname() + "\r\n");
writer.write("USER " + client.getClientLogin() + " 0 * : " + client.getClientRealName() + "\r\n");
writer.flush();
while ((serv_resp = reader.readLine()) != null)
{
System.out.println(serv_resp);
if (messageCallback != null)
messageCallback.accept(serv_resp);
if (serv_resp.indexOf("004") >= 0)
{
break;
}
else if (serv_resp.indexOf("433") >= 0)
{
System.out.println("Nickname is already in use.");
return;
}
}
//Get channel list
writer.write("LIST \r\n");
writer.flush();
//Join desired client
writer.write("JOIN " + channel_to_connect + "\r\n");
writer.flush();
//keep listening
while ((serv_resp = reader.readLine()) != null)
{
//check if running thread should terminate
if(threadExitFlag)
{
System.out.println("THREAD FLAG POINT");
writer.write("QUIT :Bye..");
socket.close();
return;
}
if (messageCallback != null)
messageCallback.accept(serv_resp);
if (serv_resp.startsWith("PING "))
{
this.pingPong();
} else
{
System.out.println(serv_resp);
}
}
}
//Ping respond
public void pingPong() throws IOException
{
writer.write("PONG " + serv_resp.substring(5) + "\r\n");
writer.flush();
}
mainController class
package jircclient.FXML;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import jircclient.serverConnection;
public class FXMLmainController implements Initializable
{
//VARIABLES
private connectionThreadFactory connectionThreadFactory;
private ExecutorService executor;
private int tabCounter = 0;
public serverConnection con;
//CONTROLLER VARIABLES
#FXML
TextArea txt;
#FXML
TabPane tabPane;
#FXML
private void connectServerMenuButtonAction(ActionEvent event)
{
System.out.println("You clicked connectServerButtonAction!");
FXMLLoader loader = new FXMLLoader(getClass().getResource("/jircclient/FXML/FXMLserver.fxml"));
try
{
Parent root = (Parent) loader.load();
Scene scene = new Scene(root, 320, 200);
Stage stage = new Stage();
stage.setTitle("Server Info");
stage.setResizable(false);
stage.setScene(scene);
stage.show();
FXMLserverController controller = loader.getController();
controller.initData(stage, this);
}
catch (IOException ex)
{
Logger.getLogger(FXMLserverController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#FXML
private void onTabCloseEvent(Event event)
{
//Event type instead of ActionEvent because the latter didnt work
//i must be able to get a reference to the serverConnection object of the associated tab
//i have to keep a list of the tab ids and the thread objects so i can set the threadExitFlag to TRUE
System.out.println("CLOSE");
System.out.println("FLAG: "+ con.threadExitFlag);
con.exitThread();
}
#Override
public void initialize(URL url, ResourceBundle rb)
{
System.out.println("Initialize in controller!");
connectionThreadFactory = new connectionThreadFactory("Server Connection");
executor = Executors.newFixedThreadPool(5, connectionThreadFactory);
}
//setters - getters
public connectionThreadFactory getConnectionThreadFactory()
{
return connectionThreadFactory;
}
public ExecutorService getExecutorService()
{
return executor;
}
public int getTabCounter()
{
return tabCounter;
}
public void setTabCounter(int tabCounter)
{
this.tabCounter = tabCounter;
}
public void increaseTabCounter()
{
tabCounter++;
}
}
serverController class - starts when connectServerMenuButtonAction is fired and opens new window-stage
package jircclient.FXML;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import jircclient.clientInfo;
import jircclient.serverConnection;
public class FXMLserverController extends AnchorPane implements Initializable
{
//PARENT VARIABLES - REFERENCES
Stage stage;
FXMLmainController parentController;
//CONTROLLER VARIABLES
#FXML
TextField ircServerField, port, nicknameField, loginField, realNameField;
#FXML
PasswordField passwordField;
public void initData(Stage stage, FXMLmainController parentController)
{
this.stage = stage;
this.parentController = parentController;
}
#Override
public void initialize(URL url, ResourceBundle rb)
{
System.out.println("serverController reporting in!");
}
#FXML
private void connectButtonAction(ActionEvent event) throws IOException
{
//get info from text fields - initialize serverConnection
clientInfo clientInfo = new clientInfo(this.realNameField.getText(), this.nicknameField.getText(), this.loginField.getText());
serverConnection serverConnection = new serverConnection(clientInfo, ircServerField.getText(), Integer.parseInt(port.getText()), "#linux");
serverConnection.setMessageCallback(message ->
Platform.runLater(() -> ((TextArea) parentController.tabPane.lookup("#txt")).appendText(message+"\n")));
//prepare thread
Thread serverThread = parentController.getConnectionThreadFactory().newThread(() -> {
try
{
serverConnection.startCommunication();
System.out.println("Terminating Thread...");
}
catch(IOException ex)
{
Logger.getLogger(FXMLmainController.class.getName()).log(Level.SEVERE, null, ex);
}
});
//add server tab
parentController.tabPane.getTabs().add(FXMLLoader.load(getClass().getResource("/jircclient/FXML/FXMLtab.fxml")));
parentController.tabPane.getTabs().get(parentController.getTabCounter()).setText(ircServerField.getText());
parentController.increaseTabCounter();
//start thread-communication
serverThread.setDaemon(true);
parentController.getExecutorService().execute(serverThread);
parentController.con = serverConnection;
System.out.println("CON IFNO"+ parentController.con.threadExitFlag);
//close window
stage.close();
}
#FXML
private void cancelButtonAction(ActionEvent event)
{
//close window
stage.close();
}
}
fxml snippet for the #onTabCloseEvent event
<Tab xmlns:fx="http://javafx.com/fxml/1" fx:controller="jircclient.FXML.FXMLmainController" onClosed="#onTabCloseEvent">
stack trace:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1762)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1645)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at com.sun.javafx.scene.control.behavior.TabPaneBehavior.canCloseTab(TabPaneBehavior.java:152)
at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderSkin$5.handle(TabPaneSkin.java:1291)
at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderSkin$5.handle(TabPaneSkin.java:1282)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/96639997.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1757)
... 43 more
Caused by: java.lang.NullPointerException
at jircclient.FXML.FXMLmainController.onTabCloseEvent(FXMLmainController.java:69)
... 53 more
line 69 and 70 FXMLmainController:
System.out.println("FLAG: "+ con.threadExitFlag);
con.exitThread();

J2ME connect localhost nullpointerexception 0

I am trying to connect localhost and insert data into database through j2me application.but when I am connecting the server it shows there is a nullpointerexception 0 error.
this is midlet code
import java.io.DataOutputStream;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.*;
public class Midlet_1 extends MIDlet implements CommandListener {
Display mdDisplay;
Form mForm;
StringItem messageitem;
Command exit, connectCommand;
public Midlet_1() {
mForm = new Form("My Counter midlet");
messageitem = new StringItem(null, "");
exit = new Command("Exit", Command.EXIT, 0);
connectCommand = new Command("Connect", Command.SCREEN, 0);
mForm.append(messageitem);
mForm.addCommand(exit);
mForm.addCommand(connectCommand);
mForm.setCommandListener(this);
}
public void startApp() {
mdDisplay = Display.getDisplay(this);
mdDisplay.setCurrent(mForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exit) {
notifyDestroyed();
} else if (c == connectCommand) {
Form waitform = new Form("Waiting");
mdDisplay.setCurrent(waitform);
Thread t = new Thread() {
public void run() {
connect();
}
};
t.start();
}
}
private void connect() {
try {
HttpConnection hs = null;
InputStream in = null;
String url = "localhost:8080/testweb/src/save";
hs.setRequestProperty("User-Agent", "Profile/MIDP-2.0,Configuration/CLDC-2.0");
hs.setRequestProperty("Content-Language", "en-US");
hs.setRequestMethod(HttpConnection.POST);
DataOutputStream ds = hs.openDataOutputStream();
ds.writeUTF("nam56");
ds.writeUTF("67");
ds.writeUTF("0716522549");
ds.flush();
ds.close();
in = hs.openInputStream();
int connectlength = (int) hs.getLength();
byte[] raw = new byte[connectlength];
int length = in.read(raw);
// int ch;
// StringBuffer sb=new StringBuffer();
// while((ch=in.read())!=-1){
// sb.append((char)ch);
// }
in.close();
hs.close();
String s = new String(raw, 0, length);
messageitem.setText(s);
} catch (Exception e) {
messageitem.setText(e.toString());
System.out.println(e);
}
mdDisplay.setCurrent(mForm);
}
}
and this is servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
DataInputStream in=new DataInputStream(request.getInputStream());
String name=in.readUTF();
String id=in.readUTF();
String contt=in.readUTF();
Connection c=DBcon.setconConnection();
Statement s=c.createStatement();
s.executeUpdate("insert into details values('"+id+"','"+name+"''"+contt+"')");
out.print("successfullllll");
} finally {
out.close();
}
}
please check this out.....
This might work only if you are running an emulator on the same machine as the server. Try to replace locahost by 127.0.0.1.
In your connect() method, I can see that you initialized hs as null then you called setRequestProperty. Try to initialize hs properly before calling its methods.