How to unregister a registerDefaultNetworkCallback (new ConnectivityManager.NetworkCallback () ...) - android-connectivitymanager

Using this code taken from:
https://developer.android.com/training/basics/network-ops/reading-network-state
I register a DefaultNetworkCallback:
connectivityManager.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
Log.e(TAG, "The default network is now: " + network);
}
....
});
How to unregister DefaultNetworkCallback from a function?
I tried:
public void unregisterNetworkCallback(NetworkCallback networkCallback) {
ConnectivityManager.unregisterNetworkCallback(networkCallback);
}
but I don't know what parameters to put.

I have created a code that works for me for what I needed.
I create a variable:
private ConnectivityManager.NetworkCallback mNetworkCallback;
Then with that name a new ConnectivityManager.NetworkCallback()
mNetworkCallback = new ConnectivityManager.NetworkCallback()
{
#Override
public void onAvailable(Network network) {
// Log.e(TAG, "The default network is now: " + network);
}
....
});
Then I unregister with a function.
public void Unregdefault() {
try {
cm.unregisterNetworkCallback (mNetworkCallback);
} catch (Exception exception) {
// onError("could not unregister network callback", exception);
}
}

Related

How can I mock RabbitMQClient of io.quarkiverse.rabbitmqclient.RabbitMQClient and write junit for basic send and consume operation?

I'm new to the quarkus framework where I'm writing rabbitmq-client library based on quarkur framework. I'm using io.quarkiverse.rabbitmqclient.RabbitMQClient.
I need to write JUnit for basic send and consume operations, please help me with how can I write junit and mock RabbitMQClient. I'm using the below code to send and consume message.
#ApplicationScoped
public class RabbitMQProducerAdapterImpl extends RabbitMQCongiguration implements RabbitMQProducerAdapter {
#Override
public void sendMessage(String exchange, String routingKey, String messagePayload) throws IOException {
setUpConnectionAndChannel();
channel.basicPublish(exchange, routingKey, null, messagePayload.getBytes(StandardCharsets.UTF_8));
Log.info("message sent succefully: " + messagePayload);
}
}
Here is the RabbitMQCongiguration
#ApplicationScoped
public class RabbitMQCongiguration {
#Inject
private RabbitMQClient rabbitClient;
protected Channel channel;
protected void setUpConnectionAndChannel() {
try {
// create a connection
Connection connection = rabbitClient.connect();
// create a channel
channel = connection.createChannel();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
protected void setupQueueInDirectExchange(String exchangeName, String routingKey, String queueName,
boolean createExchangeQueues) throws IOException {
setUpConnectionAndChannel();
if (createExchangeQueues) {
this.channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, null);
// declaring a queue for this channel. If queue does not exist,
// it will be created on the server. this line not needed if queue already
// present
this.channel.queueDeclare(queueName, true, false, false, null);
}
// Bind Routing Key to Exchange
this.channel.queueBind(queueName, exchangeName, routingKey);
}
}
Below is the class for consumer
#ApplicationScoped
public class RabbitMQConsumerAdapterImpl extends RabbitMQCongiguration implements RabbitMQConsumerAdapter, Runnable {
private String queueName;
private MessageProcessor messageProcessor;
#Override
public void consumeMessage(String exchange, String queueName, String routingKey,
MessageProcessor messageProcessor) throws IOException {
Log.info("starting consumer...");
try {
this.queueName = queueName;
this.messageProcessor = messageProcessor;
Log.info("setting up rabbitMQPrefetchCountConfig");
setupQueueInDirectExchange(exchange, routingKey, queueName, false);
Thread consumerThread = new Thread(this);
consumerThread.start();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#Override
public void run() {
try {
// start consuming messages. Auto acknowledge messages.
Log.info("Start consuming messages from thread...");
channel.basicConsume(this.queueName, false, (Consumer) new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String msgPayload = null;
if (body == null || body.length == 0) {
Log.warn("Invalid Message Body - Consumer Tag : " + consumerTag + ", Message DeliveryTag : "
+ envelope.getDeliveryTag());
channel.basicReject(envelope.getDeliveryTag(), false);
} else {
msgPayload = new String(body);
try {
JsonParser.parseString(msgPayload);
} catch (JsonSyntaxException ex) {
Log.error(msgPayload + " is not a valid json, Reason - ", ex);
channel.basicReject(envelope.getDeliveryTag(), false);
Log.warn("Rejected the current payload.");
return;
}
messageProcessor.processMessage(msgPayload);
channel.basicAck(envelope.getDeliveryTag(), false);
}
// just print the received message.
Log.info("Received: " + new String(body, StandardCharsets.UTF_8));
}
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#ApplicationScoped
public class MessageProcessorImpl implements MessageProcessor{
#Override
public void processMessage(String messagePayload) {
Log.info("message consumed: " + messagePayload);
}
}

ViewPart hangs on click of JButton

I am working on Teamcenter RAC customization. I have changed an existing code which deals with viewpart and jbuttons on it. The viewpart(SWT) loads a stylesheet rendering panel. the problem is whenever I click on the save button (JButton) this hangs the teamcenter application on post -executing activities.
The code is as follows:
saveCheckOutButton.addActionListener( new ActionListener()
{
#Override
public void actionPerformed( ActionEvent paramAnonymousActionEvent )
{
final AbstractRendering sheetPanel = itemPanel.getStyleSheetPanel();
final AbstractRendering sheetPanel1 = itemRevPanel.getStyleSheetPanel();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground()
throws Exception
{
if(pPanel==null)
return null;
if( pPanel.isPanelSavable())
{
if(sheetPanel==null|| sheetPanel1==null)
return null;
sheetPanel.saveRendering();
sheetPanel1.saveRendering();
/*if(!sheetPanel.getErrorFlag() && !sheetPanel1.getErrorFlag())
{
sheetPanel.setModifiable( false );
sheetPanel1.setModifiable( false );
}*/
}
return null;
}
#Override
protected void done(){
if(!sheetPanel.getErrorFlag() && !sheetPanel1.getErrorFlag())
{
sheetPanel.setModifiable( false );
sheetPanel1.setModifiable( false );
}
}
};
worker.execute();
}
} );
I have written the code under swingworker as suggested by some of the experts here but to no success. Request for some immediate help.
What do you mean by "it hangs the teamcenter application". Whether it responds too slow or doInBackground() is not properly executed?
Anyway you can try executing your rendering code in SwingUtilities.invokeLater() and use the method get(). If you don't call get() in the done method, you will lose all the exceptions that the computation in the doInBackground() has thrown. So we will get to know about exception if any is there.
SwingUtilities.invokeLater() allows a task to be executed at some later point in time, as the name suggests; but more importantly, the task will be executed on the AWT event dispatch thread. Refer Invoke later API documentation for the detailed info.
About get():
Waits if necessary for the computation to complete, and then retrieves its result.
Note: calling get on the Event Dispatch Thread blocks all events, including repaints, from being processed until this SwingWorker is complete.
saveCheckOutButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent paramAnonymousActionEvent) {
final AbstractRendering sheetPanel = itemPanel.getStyleSheetPanel();
final AbstractRendering sheetPanel1 = itemRevPanel.getStyleSheetPanel();
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
if (pPanel == null)
return null;
if (pPanel.isPanelSavable()) {
if (sheetPanel == null || sheetPanel1 == null)
return null;
saveRendering();
}
return null;
}
#Override
protected void done() {
try {
get();
if (!sheetPanel.getErrorFlag() && !sheetPanel1.getErrorFlag()) {
sheetPanel.setModifiable(false);
sheetPanel1.setModifiable(false);
}
} catch (final InterruptedException ex) {
throw new RuntimeException(ex);
} catch (final ExecutionException ex) {
throw new RuntimeException(ex.getCause());
}
}
};
worker.execute();
}
});
private void saveRendering() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
sheetPanel.saveRendering();
sheetPanel1.saveRendering();
}
});
}

Authorization scope does not appear

I created a new app and the authentication part for GoogleFit is a complete copy/paste of another app that works perfectly. The window to choose an account appears but after that I'm expecting to see the window that showing needed scope but nothing.
Is there someone who already encountered this issue ?
I can post my code if needed.
Thanks a lot !
Edit
This is my code to connect to Google Fit:
private void buildFitnessClient() {
// Create the Google API Client
mFitClient = new GoogleApiClient.Builder(this)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.RECORDING_API)
.addApi(Fitness.CONFIG_API)
.addScope(new Scope(Scopes.FITNESS_LOCATION_READ_WRITE))
.addScope(new Scope((Scopes.FITNESS_NUTRITION_READ_WRITE)))
.addScope(new Scope(Scopes.FITNESS_BODY_READ_WRITE))
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Connected to Fitness API!!!");
// Now you can make calls to the Fitness APIs.
// Put application specific code here.
// Once connected go the Main2Activity
Intent start_google_plus = new Intent(GoogleFitAuthentication.this, MainActivity.class);
startActivity(start_google_plus);
finish();
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "onConnectionSuspend");
// If your connection to the sensor gets lost at some point,
// you'll be able to determine the reason and react to it here.
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Log.i(TAG, "Connection lost. Cause: Network Lost.");
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Log.i(TAG, "Connection lost. Reason: Service Disconnected");
}
}
}
)
.addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
// Called whenever the API client fails to connect.
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed. Cause: " + result.toString());
if (!result.hasResolution()) {
// Show the localized error dialog
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(),
GoogleFitAuthentication.this, 0).show();
return;
}
// The failure has a resolution. Resolve it.
// Called typically when the app is not yet authorized, and an
// authorization dialog is displayed to the user.
if (!authInProgress) {
try {
Log.i(TAG, "Attempting to resolve failed connection");
authInProgress = true;
result.startResolutionForResult(GoogleFitAuthentication.this, REQUEST_OAUTH);
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
}
}
)
.build();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "Processing onActivityResult...");
if (requestCode == REQUEST_OAUTH) {
Log.d(TAG, "requestCode == REQUEST_OAUTH");
authInProgress = false;
if (resultCode == RESULT_OK) {
Log.d(TAG, "resultCode == RESULT_OK");
// Make sure the app is not already connected or attempting to connect
if (!mFitClient.isConnecting() && !mFitClient.isConnected()) {
mFitClient.connect();
}
}
}else{
Log.d(TAG, "Impossible to process onActivityResult...");
}
}
#Override
protected void onStart() {
super.onStart();
// Connect to the Fitness API
Log.i(TAG, "Connecting...");
if(mFitClient!=null){
mFitClient.connect();
}
}
#Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop...");
if (mFitClient!=null && mFitClient.isConnected()) {
mFitClient.disconnect();
}
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(AUTH_PENDING, authInProgress);
}
When you authorized the scopes , the browser will store your session. So if you again authorize the app in the same browser, you will only shows the scope as Have offline access.

rxjava - How to handle merge exceptions without terminating the whole process

I have created two observables.
One of them throws an exception.
obs1 = Observable.from(new Integer[]{1, 2, 3, 4, 5, 6});
obs2 = Observable.create(new Observable.OnSubscribe<Integer>() {
#Override public void call(Subscriber<? super Integer> subscriber) {
boolean b = getObj().equals(""); // this throws an exception
System.out.println("1");
}
});
Now I invoke them using
Observable.merge(obs2, obs1)
.subscribe(new Observer<Integer>() {
#Override public void onCompleted() {
System.out.println("onCompleted");
}
#Override public void onError(Throwable throwable) {
System.out.println("onError");
}
#Override public void onNext(Integer integer) {
System.out.println("onNext - " + integer);
}
});
Now, I dont want my process to halt completely when an exception occurs -
I want to handle it and I want obs1 to continue its work.
I have tried to write it using onErrorResumeNext(), onExceptionResumeNext(), doOnError()
but nothing helped - obs1 did not run.
How can I handle the exception without stopping the other observable from being processed?
Sounds like you need mergeDelayError.
The problem is in your subscriber which is broken. You should catch your exception and call onError. Otherwise, you broke the rx contract.
example :
Observable<Integer> obs1 = Observable.from(Arrays.asList(1, 2, 3, 4, 5, 6));
Observable<Integer> obs2 = Observable.create((Subscriber<? super Integer> subscriber) -> {
subscriber.onError(new NullPointerException());
});
Observable.merge(obs2.onErrorResumeNext((e) -> Observable.empty()), obs1)
.subscribe(new Observer<Integer>() {
#Override public void onCompleted() {
System.out.println("onCompleted");
}
#Override public void onError(Throwable throwable) {
System.out.println("onError");
}
#Override public void onNext(Integer integer) {
System.out.println("onNext - " + integer);
}
});
so if you replace your obs2 code with this, it should work like you expected :
obs2 = Observable.create(new Observable.OnSubscribe<Integer>() {
#Override public void call(Subscriber<? super Integer> subscriber) {
try {
boolean b = getObj().equals(""); // this throws an exception
System.out.println("1");
} catch(Exception ex) {
subscriber.onError(ex);
}
}
});

Problem with updating the jTextArea

I am writing a RMI chat program. In my program I am able to receive and send messages, but i am not able to display it in the TextArea. I am not sure what is the error. I tried using Event Dispatch method also. It doesn't help.
public class client extends javax.swing.JFrame implements inter {
public client() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
final inter i = (inter) Naming.lookup("rmi://localhost:1111/client1");
final String msg = jTextField1.getText();
if (msg.length() > 0) {
jTextArea1.append("Me :" + msg);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
i.rcvMsg("Client 1 : " + msg);
} catch (RemoteException ex) {
}
}
});
}
} catch (RemoteException ex) {
} catch (NotBoundException ex) {
} catch (MalformedURLException ex) {
}
}
public void rcvMsg(String msg) {
final String s = msg;
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
System.out.println("server called");
System.out.println(s);
jTextArea1.append(s);
System.out.println("client msg" + java.awt.EventQueue.isDispatchThread());
jTextArea1.update(jTextArea1.getGraphics());
}
});
}
public static void main(String args[]) {
try {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new client().setVisible(true);
}
});
client c2 = new client();
inter stub = (inter) UnicastRemoteObject.exportObject(c2, 0);
Registry registry = LocateRegistry.createRegistry(1113);
registry.bind("client2", stub);
} catch (AlreadyBoundException ex) {
} catch (AccessException ex) {
} catch (RemoteException ex) {
}
}
}
Please help...
just sharing some information using getGraphics() is not appreciated and can cause problems,
jTextArea1.update(jTextArea1.getGraphics());
and i have also created chat application with RMI:
Pass by reference problem in RMI? there is also client written over there, may be that would be useful for you.
In main after creating c2, call c2.setVisible(true);
The code in rcvMsg is being called on the c2 instance of client. Since the c2 instance is never made visible, you see no change.
You probably want a client to connect to a server, not directly to another client. The client-to-client will work for 2 endpoints. But what happens if you want to add a third? A forth? You really want a server that will act as an intermediary for all the clients.