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.
Related
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);
}
}
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);
}
}
#Override
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
onUpdate(context, appWidgetManager, appWidgetIds, null);
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, final Intent receiveIntent) {
RemoteViews rw = new RemoteViews(context.getPackageName(), R.layout.calendar_widget);
packageManager=context.getPackageManager();
//code for other jobs
if (receiveIntent != null){
manualUpdate = receiveIntent.getBooleanExtra("manual", false);
final RemoteViews[] remoteViews= new RemoteViews[]{rw};
if(manualUpdate){
remoteViews[0].setViewVisibility(R.id.update_ready_text,View.VISIBLE);//work
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
remoteViews[0].setViewVisibility(R.id.update_ready_text,View.INVISIBLE);//not work!!
System.out.println("handler ran is succes");
}
});
}
//code for other jobs...
appWidgetManager.updateAppWidget(appWidgetId, rw);
}
//out result:
I/System.out: onReceive : android.appwidget.action.APPWIDGET_UPDATE
I/System.out: handler ran is succes.
///////the handler runs, but the 'textview' will not be invisible.which method would be appropriate?.thx for help!
if(manualUpdate){
remoteViews[0].setViewVisibility(R.id.update_ready_text,View.VISIBLE);//work
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
remoteViews[0].setViewVisibility(R.id.update_ready_text,View.INVISIBLE);//
appWidgetManager.updateAppWidget(appWidgetIds,rw);
}
});
}
*** i found the solution. i forgot update widget in handler. it works -:))))
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();
}
});
}
I would like to run a task during the waiting of a web request. If the task finishes before the request can return a response, then I would display a message "The server is taking too long". I'm using a WebClient object, how can I manage the time out?
public Class Result
{
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("critere", out sCritere))
{
try
{
_datamanager = new DataManager();
_datamanager.m_evt_Client_DownloadStringCompleted += OnDownloadStringCompleted;
_datamanager.DownloadXmlData(DataManager.URL_RECHERCHE, sCritere);
//HERE I NEED TO RUN A TIMER If the response is too long i would display a message
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK);
NavigationService.GoBack();
NavigationService.RemoveBackEntry();
}
}
}
}
public Class DataManager
{
public void DownloadXmlData(string uri, string critere = "")
{
try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.Credentials = new NetworkCredential(UserSaved, PasswordSaved, domain);
client.DownloadStringAsync(new Uri(uri + critere));
}
catch(WebException )
{
throw new WebException(MyExceptionsMessages.Webexception) ;
}
catch (Exception )
{
throw new UnknowException(MyExceptionsMessages.UnknownError);
}
}
public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
//raise Downloadstringcompleted event if error==null
}
}
You can use BackgroundWorker..
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
// your task to do while webclient is downloading
};
bw.RunWorkerCompleted += (s, e) =>
{
// check whether DownloadStringCompleted is fired or not
// if not, cancel the WebClient's asynchronous call and show your message.
client.CancelAsync();
MessageBox.Show("message");
}
client.DownloadStringAsync(uri);
bw.RunWorkerAsync();