Is there any difference betweent ctx.disconnect() and ctx.close() in netty? What are those two function application scenarios? - tcp

public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state().equals(IdleState.READER_IDLE)) {
System.out.println("READER_IDLE");
ctx.disconnect();
ctx.close();
}
}
}
Do I need invoke ctx.disconnect() before ctx.close()?

Related

Why I need to add some delay while making concurrent request in streaming gRPC? (Java) to get output

#Test
public void testType() throws InterruptedException {
Integer num = 15;
String name = "Sahil";
Float percentage = 96.7f;
DOB dob = DOB.newBuilder().setDay(20).setMonth(8).setYear(2022).build();
ArrayList<Object> objects = new ArrayList<>(Arrays.asList(num,name,percentage,dob));
TypeRequest.Builder builder = TypeRequest.newBuilder();
StreamObserver<TypeResponse> typeResponseStreamObserver = new StreamObserver<TypeResponse>() {
#Override
public void onNext(TypeResponse typeResponse) {
System.out.println(
"Type : " + typeResponse.getType()
);
}
#Override
public void onError(Throwable throwable) {
System.out.println("Error : "+throwable);
}
#Override
public void onCompleted() {
System.out.println("Finished all requests");
}
};
StreamObserver<TypeRequest> typeRequestStreamObserver = this.calculatorServiceStub.getType(typeResponseStreamObserver);
for(Object obj : objects){
if (obj instanceof Integer){
builder.setNum((Integer) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof String) {
builder.setName((String) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof Float) {
builder.setFNum((Float) obj);
typeRequestStreamObserver.onNext(builder.build());
} else if (obj instanceof DOB) {
builder.setDob((DOB) obj);
typeRequestStreamObserver.onNext(builder.build());
}
// --------------------------------------------
Thread.sleep(500);
// --------------------------------------------
}
typeRequestStreamObserver.onNext(builder.clearType().build());
typeRequestStreamObserver.onCompleted();
}
If I did not add any delay then the output console is just blank. Testing with tools like BloomRPC and Postman it works fine,
but for this I don't know why this is happening?
Any little help will be very helpful. I appreciate it.

Spring cloud function to create a GlobalKTable from strem

Is there an example of how to create a GlobalKTable to keep count from a KStream using Spring Cloud stream and using Functional approach?
Is implementing processor interface the right approach?
#Bean
public Consumer<KStream<String, Long>> processorsample() {
return input -> input.process(() -> new Processor<String, Long>() {
#Override
public void init(ProcessorContext context) {
if (state == null) {
state = (KeyValueStore<String, Long>) context.getStateStore("mystate");
}
}
#Override
public void process(String key, Long value) {
if (state != null) {
if (key != null) {
Long currentCount = state.get(key);
if (currentCount == null) {
state.put(key, value);
} else {
state.put(key, currentCount + value);
}
}
}
}
#Override
public void close() {
if (state != null) {
state.close();
}
}
}, "mystate");
}
According to the documentation GlobalKTables are read-only, you cannot modify a global table during the processing.
Since GlobalKTables are consumers of a Kafka topic, you can just send your data to the GlobalKTable's source topic, and eventually, it's going to be added to the table. But you cannot be sure that the GlobalKTable will be updated immediately.

Android Retrofit 2.0: no response to HTTP call

I am an Android developer, I am working with Retrofit. The first day I had a response but the second day the response did not come, why I will working after I can uninstall and install the app then only it will work why, how to I resolve it please help me...
private void HomeWorks() {
HomeWorkApi homeWorkApi =
MissReportServer.getClient().create(HomeWorkApi.class);
Call<VrrittamResponse<ArrayList<HomeWork>>> call =
homeWorkApi.getHomeWork(access_token);
call.enqueue(new Callback<VrrittamResponse<ArrayList<HomeWork>>>() {
#Override
public void onResponse(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Response<VrrittamResponse<ArrayList<HomeWork>>> response) {
try {
ArrayList<HomeWork> homeWork = response.body().getContent();
if (homeWork != null && !homeWork.isEmpty()) {
recyclerView.setAdapter(new HomeWorkAdapter(homeWork,
R.layout.list_item_homework, getActivity()));
}
else {
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
catch (Exception ex){
ExceptionHandle.alertDialogNotShow(getActivity());
}
}
#Override
public void onFailure(Call<VrrittamResponse<ArrayList<HomeWork>>> call, Throwable t) {
Log.e("TAG",t.getMessage());
ExceptionHandle.alertDialogShow(getActivity());
}
});
}

SyncAdapter onPerformSync get current location

When onPerformSync occurs I need the current location but I do not want to set up a separate service that is constantly active requesting location because my SyncAdapter period exponentially backs off such that the periods between syncs could be many hours apart. It would be wasteful to have location requests running between each sync.
I am planning on using a GoogleApiClient and LocationServices.FusedLocationApi.requestLocationUpdates then Thread.sleep(###) the onPerformSync thread until a location is found.
However I have read that requestLocationUpdates needs to be called on the main looper and that it makes callbacks on that thread in which case I expect will it fail to return location results because I am sleeping on the thread which called it.
Will I need to start my own looper thread?
Is there another/better way to get current location from onPerformSync?
Turns out my fears were not justified, my method does work without error. I have put together a handy example class below in case anyone else wants to do this:
public class cSyncLocation implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener
{
// =======================================================
// private vars
// =======================================================
private GoogleApiClient moGoogleApiClient;
private LocationRequest moLocationRequest;
private Location moCurrentLocation;
private static final int kTIMEOUT_MILLISECONDS = 2500;
// =======================================================
// public static vars
// =======================================================
// =======================================================
// public methods
// =======================================================
public void Start(Context oContext)
{
if (moGoogleApiClient == null)
{
moGoogleApiClient = new GoogleApiClient.Builder(oContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
if (moLocationRequest == null)
{
moLocationRequest = new LocationRequest();
moLocationRequest.setInterval(1);
moLocationRequest.setFastestInterval(1);
moLocationRequest.setInterval(1);
moLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
// Start the connection
if (moGoogleApiClient != null)
{
if (!moGoogleApiClient.isConnecting() && !moGoogleApiClient.isConnected())
moGoogleApiClient.connect();
else if (moCurrentLocation == null)
LocationServices.FusedLocationApi.requestLocationUpdates(moGoogleApiClient, moLocationRequest, this);
}
}
public void Stop()
{
if (moGoogleApiClient != null && moGoogleApiClient.isConnected())
LocationServices.FusedLocationApi.removeLocationUpdates(moGoogleApiClient, this);
if (moGoogleApiClient != null)
moGoogleApiClient.disconnect();
}
public Location GetLocationBlocking(Context oContext)
{
if (moCurrentLocation == null)
{
intTimeout = kTIMEOUT_MILLISECONDS;
Start(oContext);
while(intTimeout > 0 && aFrmLocationActivity.IsLastLocationExpired(oContext))
{
Thread.sleep(100);
intTimeout -= 100;
}
Stop();
}
return moCurrentLocation;
}
// =======================================================
// Location API Events
// =======================================================
#Override
public void onLocationChanged(Location oLocation)
{
if (oLocation != null)
{
moCurrentLocation = oLocation;
}
}
// =======================================================
// Google API Connection Events
// =======================================================
#Override
public void onConnected(Bundle connectionHint)
{
// Connected to Google Play services! The good stuff goes here.
if (moGoogleApiClient != null)
{
Location oLocation = LocationServices.FusedLocationApi.getLastLocation(moGoogleApiClient);
if (oLocation != null)
moCurrentLocation = oLocation;
else
LocationServices.FusedLocationApi.requestLocationUpdates(moGoogleApiClient, moLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int cause)
{
//...
}
#Override
public void onConnectionFailed(ConnectionResult result)
{
//...
}
}
How to use it, in your onPerformSync method call it like this
cSyncLocation oSyncLocation = new cSyncLocation();
Location oLocation = oSyncLocation.GetLocationBlocking(getContext());
Obviously you will want to add some exception handling and deal with null location result.

Firing CDI event from interceptor class

Is it possible to fire CDI events from within a interceptor ? (Using Jboss 7.1.1)
For example, if I have an interceptor PerformanceLogInterceptor
#Interceptors({PerformanceLogInterceptor.class})
public class ProcessHandler extends HandlerBase {
.
.
.
Could it fire an event as such:
public class PerformanceLogInterceptor {
private Logger LOG = LoggerFactory.getLogger("PerformanceLog");
#EJB
PerformanceMonitor performanceMonitor;
#Inject
Event<ExceptionEvent> exceptionEvent;
#AroundInvoke
#AroundTimeout
public Object performanceLog( InvocationContext invocationContext ) throws Exception {
String methodName = invocationContext.getMethod().toString();
long start = System.currentTimeMillis();
try {
return invocationContext.proceed();
} catch( Exception e ) {
LOG.warn( "During invocation of: {} exception occured: {}", methodName, Throwables.getRootCause(e).getMessage() );
performanceMonitor.addException( methodName, e );
Exception toSend;
if(e instanceof EfsobExceptionInformation ){
toSend = e;
} else {
LOG.debug("Wrapping exception");
EfsobExceptionWrapper wrapped = new EfsobExceptionWrapper(e);
toSend = wrapped;
}
if(exceptionEvent != null) {
LOG.debug("sending exceptionEvent");
exceptionEvent.fire(new ExceptionEventBuilder()
.setExceptionName(toSend)
.setEfsobExceptionType(toSend)
.setId(toSend)
.setStacktrace(toSend)
.build()
);
} else {
LOG.debug("exceptionEvent was null");
}
LOG.debug("rethrowing");
throw toSend;
} finally {
long total = System.currentTimeMillis() - start;
performanceMonitor.addPerformanceMetrics(methodName, total);
}
}
}
Note: exceptionEvent is null at runtime in the Above.
I moved it into an Async block of the PerformanceMonitor bean referenced above.... and then it works (WAT?)
#Singleton
#ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class PerformanceMonitor {
#Inject
Event<ExceptionEvent> exceptionEvent;
private Logger LOG = LoggerFactory.getLogger("PerformanceMonitor");
#Asynchronous
public void addException(String methodName, Exception e) {
if(exceptionEvent != null) {
LOG.debug("sending exceptionEvent");
exceptionEvent.fire(new ExceptionEventBuilder()
.setExceptionName(e)
.setEfsobExceptionType(e)
.setId(e)
.setStacktrace(e)
.build()
);
} else {
LOG.debug("exceptionEvent was null");
}
}
}

Resources