Intent from onHandleIntent - android-broadcast

I have the code
public class intentService extends IntentService {
#Override
protected void onHandleIntent(Intent intent) {
RequestQueue queue = MyVolley.getRequestQueue(this);
queue = MyVolley.getRequestQueue(this);
GsonRequest<Transport> gsonRequest = new GsonRequest<Transport>(
url_transports, Transport.class, null, createMyReqSuccessListenerTransport(),
createMyReqErrorListenerTransport());
Intent updateIntent = new Intent();
updateIntent.setAction(ACTION_UPDATE);
updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
updateIntent.putExtra(EXTRA_KEY_UPDATE, 50);
this.sendBroadcast(updateIntent);
// work
The Intent is working sending update value
private Response.Listener<Transport> createMyReqSuccessListenerTransport() {
return new Response.Listener<Transport>() {
#Override
public void onResponse(Transport response) {
// send beetwean data
Intent updateIntent = new Intent();
updateIntent.setAction(ACTION_UPDATE);
updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
updateIntent.putExtra(EXTRA_KEY_UPDATE, (i * 100) / size);
**sendBroadcast(updateIntent); // dosn`t work**
}
dosn`t work

I decided the progblemm ny myself
I have to call the intent from handle
handler.post(new Runnable() {
#Override
public void run() {
// send beetwean data
Intent updateIntent = new Intent();
updateIntent.setAction(ACTION_UPDATE);
updateIntent.addCategory(Intent.CATEGORY_DEFAULT);
updateIntent.putExtra(EXTRA_KEY_UPDATE, (finalI * 100) / size );
sendBroadcast(updateIntent);
}
});

Related

How About onActivityResult when I want to read multiple file from storage

How About onActivityResult when I want to read multiple file form storage
In this xml form I have to take multiple image file by clicking different different button from the app external storage but their is a difficulties on ActivityResult override method calling , because it call automatically and can't be call multiple time for for different different button
It's working fine for single file picking and get image URI.
So how can I fix the ActivityResult override method for different different button in a single activity
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static final int PICK_PHOTO = 1958;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, PICK_PHOTO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
}
}
Taking a array to pick photo then check with if else statement by array index
public class Application_Form extends AppCompatActivity {
ActivityApplicationBinding binding;
boolean isOnlyImageAllowed = true;
private static int[] PICK_PHOTO={0,1,2,3,4,5} ;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityApplicationBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
binding.appBar.title.setText("লাইসেন্সের জন্য আবেদন করুন");
binding.appBar.back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
//check user storage permission
int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
binding.form4.choosePropertyFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 0);
}
});
binding.form4.chooseBankCertificate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent;
if (isOnlyImageAllowed) {
// only image can be selected
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
} else {
// any type of files including image can be selected
intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
}
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[0]) {
Uri imageUri = data.getData();
binding.form4.selectedPropertyFile.setText("" + imageUri.getLastPathSegment());
}
if (resultCode == RESULT_OK && requestCode == PICK_PHOTO[1]) {
Uri imageUri = data.getData();
binding.form4.selectedBankCertificate.setText("" + imageUri.getLastPathSegment());
}
}
}

Best approach to use DiffUtil with LIveData + Room Database?

I am using Room Database with LiveData , but my Local Database is updating too fast as per our requirement and at the same time i have to reload my recycler view .instead of calling notifyDataSetChanged() to adapter , i am trying to use DiffUtil , but is crashing or not reloading properly , this is uncertain .
i am following this tutorial :
Tutorials Link here
MyAdapter :
public class SwitchGridAdapter extends RecyclerView.Adapter<SwitchGridAdapter.ViewHolder> {
private List<Object> allItemsList;
private LayoutInflater mInflater;
private OnItemClickListener mClickListener;
private Context context;
private Queue<List<Object>> pendingUpdates =
new ArrayDeque<>();
// data is passed into the constructor
public SwitchGridAdapter(Context context,List<Appliance> applianceList,List<ZmoteRemote> zmoteRemoteList) {
this.mInflater = LayoutInflater.from(context);
this.context = context;
allItemsList = new ArrayList<>();
if (applianceList!=null) allItemsList.addAll(applianceList);
if (zmoteRemoteList!=null)allItemsList.addAll(zmoteRemoteList);
}
// inflates the cell layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R .layout.switch_grid_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the textview in each cell
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// Doing some update with UI Elements
}
// total number of cells
#Override
public int getItemCount() {
return allItemsList.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener {
TextView myTextView;
ImageView imgSwitch;
ViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.txtSwitchName);
imgSwitch = (ImageView) itemView.findViewById(R.id.imgSwitchStatus);
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
// handling click
}
#Override
public boolean onLongClick(View view) {
return true;
}
// convenience method for getting data at click position
Object getItem(int id) {
return allItemsList.get(id);
}
// allows clicks events to be caught
public void setClickListener(OnItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface OnItemClickListener {
void onItemClick(View view, int position);
void onItemLongPressListner(View view, int position);
}
// ✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
// From This Line Reloading with Diff Util is Done .
//✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅✅
public void setApplianceList( List<Appliance> applianceList,List<ZmoteRemote> zmoteRemoteList)
{
if (allItemsList == null)
allItemsList = new ArrayList<>();
List<Object> newAppliances = new ArrayList<>();
if (applianceList!=null) newAppliances.addAll(applianceList);
updateItems(newAppliances);
}
// when new data becomes available
public void updateItems(final List<Object> newItems) {
pendingUpdates.add(newItems);
if (pendingUpdates.size() > 1) {
return;
}
updateItemsInternal(newItems);
}
// This method does the heavy lifting of
// pushing the work to the background thread
void updateItemsInternal(final List<Object> newItems) {
final List<Object> oldItems = new ArrayList<>(this.allItemsList);
final Handler handler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
final DiffUtil.DiffResult diffResult =
DiffUtil.calculateDiff(new DiffUtilHelper(oldItems, newItems));
handler.post(new Runnable() {
#Override
public void run() {
applyDiffResult(newItems, diffResult);
}
});
}
}).start();
}
// This method is called when the background work is done
protected void applyDiffResult(List<Object> newItems,
DiffUtil.DiffResult diffResult) {
dispatchUpdates(newItems, diffResult);
}
// This method does the work of actually updating
// the backing data and notifying the adapter
protected void dispatchUpdates(List<Object> newItems,
DiffUtil.DiffResult diffResult) {
// ❌❌❌❌❌❌ Next Line is Crashing the app ❌❌❌❌❌
pendingUpdates.remove();
dispatchUpdates(newItems, diffResult);
if (pendingUpdates.size() > 0) {
updateItemsInternal(pendingUpdates.peek());
}
}
}
Observing LiveData
public void setUpAppliancesListLiveData()
{
if (applianceObserver!=null)
{
applianceObserver = null;
}
Log.e("Appliance Fetch","RoomName:"+this.roomName);
applianceObserver = new Observer<List<Appliance>>() {
#Override
public void onChanged(#Nullable List<Appliance> applianceEntities) {
// Log.e("Appliance Result","Appliance List \n\n:"+applianceEntities.toString());
new Thread(new Runnable() {
#Override
public void run() {
List<Appliance> applianceListTemp = applianceEntities;
zmoteRemoteList = new ArrayList<>(); //appDelegate.getDatabase().zmoteRemoteDao().getRemoteList(roomName);
// Sort according to name
Collections.sort(applianceListTemp, new Comparator<Appliance>() {
#Override
public int compare(Appliance item, Appliance t1) {
String s1 = item.getSwitchName();
String s2 = t1.getSwitchName();
return s1.compareToIgnoreCase(s2);
}
});
if(getActivity()!=null) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
applianceList = applianceListTemp;
mRecyclerView.getRecycledViewPool().clear();
adapter.setApplianceList(applianceList,zmoteRemoteList);
}
});
}
}
}).start();
}
};
appDelegate.getDatabase().applianceDao().getApplinaceListByRoomName(this.roomName).observe(this, applianceObserver);
}

Android Service binding with MvvmCross

I am developing xamarin.Android app in MvvmCross. I want to call a service even when the App is backgrounded and a user is logged in. The problem is, I want to call this service within every say 2 hours whether the app is in foreground or background, just the user of the App needs to be logged in.
Intent loggedintent = new Intent(this,typeof(DeviceLoginHelper));
loggedintent.PutExtra("LoggedIn", true);
StartService(loggedintent);
I have written an android service:
[Service]
public class DeviceLoginHelper : IntentService
{
protected override void OnHandleIntent(Intent intent)
{
try
{
if(intent.HasExtra("LoggedIn"))
{
}
}
catch(Exception ex) { }
}
}
But how can I implement a timer? Where do I initialise and handle event to the timer. And when timer is elapsed when should I call ?
public override void OnDestroy()
{
try
{
base.OnDestroy();
}
catch(Exception ex){}
}
and when a user loges out i want to stop this service. Where do I put the call StopService() in MvvmCross
I would not use a Timer. Instead you should configure the AlarmManager.
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
private static AlarmManager alarmMgr;
private static PendingIntent alarmIntent;
public const int NOTIFICATION_ID = 1;
public const int IDLE_TIME_MS = 30 * 1000; // 30-seconds (update here)
private NotificationManager mNotificationManager;
Notification.Builder builder;
public override void OnReceive(Context context, Intent intent)
{
// Do something when alarm triggers (here I'm building notification)
BuildNotification(context);
// reschedule alarm
ScheduleAlarm(IDLE_TIME_MS);
}
public static Context ApplicationContext { get; set; }
public static void ScheduleAlarm(int milliseconds)
{
if (milliseconds == 0) return;
alarmMgr = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
var intent = new Intent(ApplicationContext, typeof(AlarmReceiver));
alarmIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, intent, 0);
alarmMgr.Set(AlarmType.ElapsedRealtimeWakeup,
SystemClock.ElapsedRealtime() + milliseconds, alarmIntent);
}
private void BuildNotification(Context context)
{
mNotificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
var contentIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainView)), 0);
var message = $"Time is up";
var mBuilder = new Notification.Builder(context)
.SetAutoCancel(true)
.SetPriority(NotificationCompat.PriorityMax)
.SetDefaults(NotificationDefaults.All)
.SetContentTitle("Time is up")
.SetStyle(new Notification.BigTextStyle()
.BigText(message))
.SetContentText(message)
.SetSmallIcon(Resource.Drawable.ic_launcher);
mBuilder.SetContentIntent(contentIntent);
mNotificationManager.Notify(NOTIFICATION_ID, mBuilder.Build());
}
}
In your startup code, simply call:
AlarmReceiver.ApplicationContext = context;
AlarmReceiver.ScheduleAlarm(timeInMs);

Unable to access response data out of VolleyRequest, attempted callbacks

I have tried using callback similar to my fragments and other people suggestion on callbacks, However I've had no luck i could be doing the callbacks wrong. The Toast inside the onResponse method of JsonArrayRequest returns an array size of 2. But i get 0 on the toast outside of the request. consignment.class implements parcelable
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
ProgressDialog pDialog;
ArrayList<Consignment> arrayList = new ArrayList<>();
AppController appController;
ConsAdapter adapter;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
//showProgressDialog();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
//hideProgressDialog();
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(context, "Error...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
//hideProgressDialog();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
Activity Class:
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Consignment> arrayList;
TextView txtView;
BackgroundTask backgroundTask;
Type listType;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
listType = new TypeToken<ArrayList<Consignment>>(){}.getType();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
ArrayList<Consignment> list = parseResponse(response);
updateUI(list);
//Toast.makeText(GetConsActivity.this, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
Log.d("ONSUCCESS", "ARRAYSIZE: "+arrayList.size());
}
});
}
public ArrayList<Consignment> parseResponse(String response){
ArrayList<Consignment> list = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
Log.d("PARSE", "parseResponse: "+jsonArray.length());
JSONObject jsonObject = jsonArray.getJSONObject(0);
for (int i = 0; i<jsonArray.length();i++){
Consignment con = null;
Log.d("PARSE", "parseID: "+jsonObject.getInt("conid"));
con.setConid(jsonObject.getInt("conid"));
Log.d("PARSE", "conID: "+con.getConid());
con.setDescription(jsonObject.getString("description"));
list.add(con);
}
Log.d("PARSED", "parsedResponse: "+list.size());
} catch (JSONException e) {
e.printStackTrace();
}
//arrayList =gson.fromJson(response,new TypeToken<ArrayList<Consignment>>(){}.getType());
//updateUI(arrayList);
return list;
}
public void updateUI(ArrayList<Consignment> consignments){
this.arrayList = consignments;
Log.d("UPDATE", "parseResponse: "+consignments.size());
if (adapter == null) {
adapter = new ConsAdapter(consignments,GetConsActivity.this);
recyclerView.setAdapter(adapter);
}else{
adapter.setConsignments(consignments);
adapter.notifyDataSetChanged();
}
}
Error:
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [1440x2560]-format:1
E/RecyclerView: No adapter attached; skipping layout
I/qtaguid: Untagging socket 51
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 84 - 0, 0) vi=Rect(0, 84 - 0, 0) or=1
E/RecyclerView: No adapter attached; skipping layout
D/PARSE: parseResponse: 4
D/PARSE: parseID: 123456789
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.angel.createcon, PID: 26952
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.angel.createcon.Consignment.setConid(int)' on a null object reference
at com.angel.createcon.GetConsActivity.parseResponse(GetConsActivity.java:80)
at com.angel.createcon.GetConsActivity$2.onSuccess(GetConsActivity.java:56)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:50)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:47)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I/Process: Sending signal. PID: 26952 SIG: 9
Application terminated.
So I'll take a stab at this - having the activity implement the listener that way is a bit strange, though I don't think that's the issue. I also don't understand why you chose to save the list type to a variable - I've not seen anyone do that before.
However, getting to your question about the toast and why it's 0 - If you're talking about the toast that comes after the getAllCons call -it's because that code is executed before the callback code. completes.
Try something like this and see what it does.
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
TextView txtView;
BackgroundTask backgroundTask;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
List<Consignment> values = parseResponse(response);
updateUI(values);
}
});
//code may execute here but callback is not yet complete.
}
public List<Consignment> parseResponse(String response){
return gson.fromJson(response,listType);
}
private void updateUI(List<Consignment> consignments){
if(adapter == null){
adapter = new ConsAdapter(consignments)
recyclerView.setAdapter(adapter);
} else {
adapter.consignments = consignments;
adapter.notifyDataSetChanged();
}
}

Netty performs slow at writing

Netty 4.1 (on OpenJDK 1.6.0_32 and CentOS 6.4) message sending is strangely slow. According to the profiler, it is the DefaultChannelHandlerContext.writeAndFlush that makes the biggest percentage (60%) of the running time. Decoding process is not emphasized in the profiler. Small messages are being processed and maybe the bootstrap options are not set correctly (TCP_NODELAY is true and nothing improved)? DefaultEventExecutorGroup is used both in server and client to avoid blocking Netty's main event loop and to run 'ServerData' and 'ClientData' classes with business logic and sending of the messages is done from there through context.writeAndFlush(...). Is there a more proper/faster way? Using straight ByteBuf.writeBytes(..) serialization in the encoder and ReplayingDecoder in the decoder made no difference in encoding speed. Sorry for the lengthy code, neither 'Netty In Action' book nor the documentation helped.
JProfiler's call tree of the client side: http://i62.tinypic.com/dw4e43.jpg
The server class is:
public class NettyServer
{
EventLoopGroup incomingLoopGroup = null;
EventLoopGroup workerLoopGroup = null;
ServerBootstrap serverBootstrap = null;
int port;
DataServer dataServer = null;
DefaultEventExecutorGroup dataEventExecutorGroup = null;
DefaultEventExecutorGroup dataEventExecutorGroup2 = null;
public ChannelFuture serverChannelFuture = null;
public NettyServer(int port)
{
this.port = port;
DataServer = new DataServer(this);
}
public void run() throws Exception
{
incomingLoopGroup = new NioEventLoopGroup();
workerLoopGroup = new NioEventLoopGroup();
dataEventExecutorGroup = new DefaultEventExecutorGroup(5);
dataEventExecutorGroup2 = new DefaultEventExecutorGroup(5);
try
{
ChannelInitializer<SocketChannel> channelInitializer =
new ChannelInitializer<SocketChannel>()
{
#Override
protected void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new MessageByteDecoder());
ch.pipeline().addLast(new MessageByteEncoder());
ch.pipeline().addLast(dataEventExecutorGroup, new DataServerInboundHandler(DataServer, NettyServer.this));
ch.pipeline().addLast(dataEventExecutorGroup2, new DataServerDataHandler(DataServer));
}
};
// bootstrap the server
serverBootstrap = new ServerBootstrap();
serverBootstrap.group(incomingLoopGroup, workerLoopGroup)
.channel(NioServerSocketChannel.class)
.childHandler(channelInitializer)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
.option(ChannelOption.TCP_NODELAY, true)
.childOption(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024)
.childOption(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true);
serverChannelFuture = serverBootstrap.bind(port).sync();
serverChannelFuture.channel().closeFuture().sync();
}
finally
{
incomingLoopGroup.shutdownGracefully();
workerLoopGroup.shutdownGracefully();
}
}
}
The client class:
public class NettyClient
{
Bootstrap clientBootstrap = null;
EventLoopGroup workerLoopGroup = null;
String serverHost = null;
int serverPort = -1;
ChannelFuture clientFutureChannel = null;
DataClient dataClient = null;
DefaultEventExecutorGroup dataEventExecutorGroup = new DefaultEventExecutorGroup(5);
DefaultEventExecutorGroup dataEventExecutorGroup2 = new DefaultEventExecutorGroup(5);
public NettyClient(String serverHost, int serverPort)
{
this.serverHost = serverHost;
this.serverPort = serverPort;
}
public void run() throws Exception
{
workerLoopGroup = new NioEventLoopGroup();
try
{
this.dataClient = new DataClient();
ChannelInitializer<SocketChannel> channelInitializer =
new ChannelInitializer<SocketChannel>()
{
#Override
protected void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new MessageByteDecoder());
ch.pipeline().addLast(new MessageByteEncoder());
ch.pipeline().addLast(dataEventExecutorGroup, new ClientInboundHandler(dataClient, NettyClient.this)); ch.pipeline().addLast(dataEventExecutorGroup2, new ClientDataHandler(dataClient));
}
};
clientBootstrap = new Bootstrap();
clientBootstrap.group(workerLoopGroup);
clientBootstrap.channel(NioSocketChannel.class);
clientBootstrap.option(ChannelOption.SO_KEEPALIVE, true);
clientBootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
clientBootstrap.option(ChannelOption.TCP_NODELAY, true);
clientBootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
clientBootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
clientBootstrap.handler(channelInitializer);
clientFutureChannel = clientBootstrap.connect(serverHost, serverPort).sync();
clientFutureChannel.channel().closeFuture().sync();
}
finally
{
workerLoopGroup.shutdownGracefully();
}
}
}
The message class:
public class Message implements Serializable
{
public static final byte MSG_FIELD = 0;
public static final byte MSG_HELLO = 1;
public static final byte MSG_LOG = 2;
public static final byte MSG_FIELD_RESPONSE = 3;
public static final byte MSG_MAP_KEY_VALUE = 4;
public static final byte MSG_STATS_FILE = 5;
public static final byte MSG_SHUTDOWN = 6;
public byte msgID;
public byte msgType;
public String key;
public String value;
public byte method;
public byte id;
}
The decoder:
public class MessageByteDecoder extends ByteToMessageDecoder
{
private Kryo kryoCodec = new Kryo();
private int contentSize = 0;
#Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) //throws Exception
{
if (!buffer.isReadable() || buffer.readableBytes() < 4) // we need at least integer
return;
// read header
if (contentSize == 0) {
contentSize = buffer.readInt();
}
if (buffer.readableBytes() < contentSize)
return;
// read content
byte [] buf = new byte[contentSize];
buffer.readBytes(buf);
Input in = new Input(buf, 0, buf.length);
out.add(kryoCodec.readObject(in, Message.class));
contentSize = 0;
}
}
The encoder:
public class MessageByteEncoder extends MessageToByteEncoder<Message>
{
Kryo kryoCodec = new Kryo();
public MessageByteEncoder()
{
super(false);
}
#Override
protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception
{
int offset = out.arrayOffset() + out.writerIndex();
byte [] inArray = out.array();
Output kryoOutput = new OutputWithOffset(inArray, inArray.length, offset + 4);
// serialize message content
kryoCodec.writeObject(kryoOutput, msg);
// write length of the message content at the beginning of the array
out.writeInt(kryoOutput.position());
out.writerIndex(out.writerIndex() + kryoOutput.position());
}
}
Client's business logic run in DefaultEventExecutorGroup:
public class DataClient
{
ChannelHandlerContext ctx;
// ...
public void processData()
{
// ...
while ((line = br.readLine()) != null)
{
// ...
process = new CountDownLatch(columns.size());
for(Column c : columns)
{
// sending column data to the server for processing
ctx.channel().eventLoop().execute(new Runnable() {
#Override
public void run() {
ctx.writeAndFlush(Message.createMessage(msgID, processID, c.key, c.value));
}});
}
// block until all the processed column fields of this row are returned from the server
process.await();
// write processed line to file ...
}
// ...
}
// ...
}
Client's message handling:
public class ClientInboundHandler extends ChannelInboundHandlerAdapter
{
DataClient dataClient = null;
// ...
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
{
// dispatch the message to the listeners
Message m = (Message) msg;
switch(m.msgType)
{
case Message.MSG_FIELD_RESPONSE: // message with processed data is received from the server
// decreases the 'process' CountDownLatch in the processData() method
dataClient.setProcessingResult(m.msgID, m.value);
break;
// ...
}
// forward the message to the pipeline
ctx.fireChannelRead(msg);
}
// ...
}
}
Server's message handling:
public class ServerInboundHandler extends ChannelInboundHandlerAdapter
{
private DataServer dataServer = null;
// ...
#Override
public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception
{
Message msg = (Message) obj;
switch(msg.msgType)
{
case Message.MSG_FIELD:
dataServer.processField(msg, ctx);
break;
// ...
}
ctx.fireChannelRead(msg);
}
//...
}
Server's business logic run in DefaultEventExecutorGroup:
public class DataServer
{
// ...
public void processField(final Message msg, final ChannelHandlerContext context)
{
context.executor().submit(new Runnable()
{
#Override
public void run()
{
String processedValue = (String) processField(msg.key, msg.value);
final Message responseToClient = Message.createResponseFieldMessage(msg.msgID, processedValue);
// send processed data to the client
context.channel().eventLoop().submit(new Runnable(){
#Override
public void run() {
context.writeAndFlush(responseToClient);
}
});
}
});
}
// ...
}
Please try using CentOS 7.0.
I've had similar problem:
The same Netty 4 program runs very fast on CentOS 7.0 (about 40k msg/s), but can't write more than about 8k msg/s on CentOS 6.3 and 6.5 (I haven't tried 6.4).
There is no need to submit stuff to the EventLoop. Just call Channel.writeAndFlush(...) directly in your DataClient and DataServer.

Resources