SMack API in java - java

public void processMessage(Chat chat, Message message) {
if (message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: "+ message.getBody());
**processmsg** = message.getBody();
System.out.println("Message from Friend -----:"+**processmsg**);
}
Hi.how to use this processmsg String in another method.if i use outside this method i get null value. plz reply soon

Store processmsg as an instance variable in the class that contains processMessage
class Foo {
private String processmsg;
public void processMessage(Chat char, Message message) {
processmsg = message.getBody();
}
public void bar() {
// do whatever you want
}
}
Obviously you'll need to check that it's been assigned and so on before you use it (e.g. you couldn't use bar before processMessage), but you get the idea!

Related

Mockito 1.9: format the expected value (like "actual formatter" in custom ArgumentMatcher)

In Mockito 1.9.5 I'd like to format the actual value when verifying the (in order) call arguments of a method.
Mockito provides a overridable describeTo method within ArcgumentMatcher<T>s that enables me to format the expected value.
When mocking JRE classes like DatagramPacket using PowerMockito's whenNew, the actual value is not formatted the way I like.
In the following example I'm only interested if the address of the DatagramPacket was called in order. If not, I'd like to see the mismatching, actual value and not the default toString() name "java.net.DatagramPacket#7546a399".
My custom matcher is able to match only the InetSocketAddress.
Example
The custom matcher:
static class IsDatagramForAddress extends ArgumentMatcher<DatagramPacket> {
final InetSocketAddress addr;
public IsDatagramForAddress(InetSocketAddress addr){
this.addr = addr;
}
public boolean matches(Object dgp) {
SocketAddress isa = ((DatagramPacket) dgp).getSocketAddress();
boolean eq = isa.equals(addr);
// System.out.println(dgp + ": " + isa + "< >" + addr + " == " + eq);
return eq;
}
#Override
public void describeTo(Description description) {
description.appendText(addr == null ? null : addr.toString());
}
}
The test:
private static DatagramPacket isDatagramForAddress(InetSocketAddress addr){
return argThat(new IsDatagramForAddress(addr));
}
...
#Test
public void testSendIsCalledWithServersInOrder() throws Exception {
InOrder order = inOrder(sock);
order.verify(sock).send(isDatagramForAddress(new InetSocketAddress("8.8.8.2", 100)));
order.verify(sock).send(isDatagramForAddress(new InetSocketAddress("8.8.8.1", 100)));
}
This is what I get:
org.mockito.exceptions.verification.VerificationInOrderFailure:
Verification in order failure
Wanted but not invoked:
datagramSocket.send(/8.8.8.1:100);
-> at xxxx.XxxxTest.testSendIsCalledWithServersInOrder(XxxxTest.java:95)
Wanted anywhere AFTER following interaction:
datagramSocket.send(
java.net.DatagramPacket#7546a399
);
-> at xxxx.XxxxTest.testSendIsCalledWithServersInOrder(XxxxTest.java:90)
at xxxx.XxxxTest.testSendIsCalledWithServersInOrder(XxxxTest.java:95)
...
This is what I expect:
org.mockito.exceptions.verification.VerificationInOrderFailure:
Verification in order failure
Wanted but not invoked:
datagramSocket.send(/8.8.8.1:100);
-> at xxxx.XxxxTest.testSendIsCalledWithServersInOrder(XxxxTest.java:95)
Wanted anywhere AFTER following interaction:
datagramSocket.send(/8.8.8.2:100);
-> at xxxx.XxxxTest.testSendIsCalledWithServersInOrder(XxxxTest.java:90)
at xxxx.XxxxTest.testSendIsCalledWithServersInOrder(XxxxTest.java:95)
...
Question boiled down
How can I format/toString() the actual value?
You could make your ArgumentMatcher store the last object that was passed to it, then include it in your describeTo method. This might look something like this.
static class IsDatagramForAddress extends ArgumentMatcher<DatagramPacket> {
final InetSocketAddress addr;
DatagramPacket lastCompared;
public IsDatagramForAddress(InetSocketAddress addr){
this.addr = addr;
}
public boolean matches(Object dgp) {
if (dgp instanceof DatagramPacket) {
lastCompared = (DatagramPacket) dgp;
SocketAddress isa = lastCompared.getSocketAddress();
return isa.equals(addr);
}
return false;
}
#Override
public void describeTo(Description description) {
description.appendText(addr == null ? null : addr.toString());
if (lastCompared != null) {
description.appendText("Last socket address was " + lastCompared.getSocketAddress());
}
}
}

Confusing Java extend

I am trying to understand the usage of Java extend.... I created a sample testing code to under how it works....
public class Parent {
public String Msg="Original";
public String getMsg() {
return Msg;
}
public void setMsg(String msg) {
Msg = msg;
}
public void printing(){
System.out.println(Msg);
}
}
public class Child extends Parent{
public HashMap<String, String> Msg2;
public Integer Msg3;
public HashMap<String, String> getMsg2() {
return Msg2;
}
public void setMsg2(HashMap<String, String> msg2) {
Msg2 = msg2;
}
public void printing(){
System.out.println("1 : " + Msg);
System.out.println( Msg2 );
}
public static void main(String[] args) {
Child a = new Child();
System.out.println(a.Msg.getClass()); // able to detect variable from parent
System.out.println(a.Msg2.getClass()); // Not able to detected, even variable from
// same instance object child
System.out.println(a.Msg3.getClass()); // Not able to detected, even variable from
// same instance object child
a.printing();
}
}
I getting confuse why Msg variable from parent object can detected easy.
While Msg2 and Msg 3 coming from the same instance Child -> a can't recognize it's own variable.
The error message getting from Msg2 or Msg 3 is, Exception in thread "main" java.lang.NullPointerException
Is there anyone able to explain why java behave in such way ?
Thank you....
You have not initialized Msg2 and Msg3. You need to use the new keyword to initialize them, so that they are not null.
add these two statements.
Msg2 = new HashMap<String,String>();
Msg3 = new Integer();
Because Msg has been initialised to a non-null value (the string "Original") but the other fields have not, so they're null and you get an exception trying to call a method (getClass) on a null reference. If you just tried to print out Msg2 rather than Msg2.getClass() then you'd see the value null with no exception.
first set a value to your msg in your child class so its not null by default.
Int Msg3 = 5;
and display it this way
System.out.println("Here is a msg:" + child.Msg4);

I want to store the data received from serial port in a string variable that will be accessed in another class

I want to store the data received from serial port in a string variable that will be accessed in another class.
I wrote up code that prints the data received from com port but when the variable is accessed out of the method it returns null..
Please help me out.. I am using RxTx library for this.
public class ProtocolImpl implements Protocol {
byte[] buffer = new byte[1024];
int tail = 0;
public String message;
public void onReceive(byte b) {
// simple protocol: each message ends with new line
if (b=='\n') {
onMessage();
} else {
buffer[tail] = b;
tail++;
}
}
public void onStreamClosed() {
onMessage();
}
/*
* When message is recognized onMessage is invoked
*/
private void onMessage() {
if (tail!=0)
{
// constructing message
message = getMessage(buffer, tail);
//rmess = message;
System.out.println("RECEIVED MESSAGE: " + message);
if ("KITM".equalsIgnoreCase(message)) {
CommPortSender.send(getMessage("OK"));
}
tail = 0;
}
}
public String rmess() /*this method is returning null.. please help me out*/
{
if (tail!=0) {
message = getMessage(buffer, tail);
}
return message;
}
// helper methods
public byte[] getMessage(String message) {
return (message).getBytes();
}
public String getMessage(byte[] buffer, int len) {
return new String(buffer, 0, tail);
}
}
You are using an instance variable message. There is one instance of this variable for each ProtocolImpl object. Presumably the ProtocolImpl object on which onMessage is called is a different ProtocolImpl object on which rmess is called.
The easy fix is just to make message a static variable so that there is only one instance of that variable in the whole program. Be careful, though, this can cause some subtle problems like synchronization and object independence. A better solution is to make sure you are using the same ProtocolImpl object to call both onMessage and rmess.
Your message object is not serialized so you are getting message is null. You can implement java.io.Serializable

RMI chat program, need red "error" message

public String commando(String username, String channel, String text) throws RemoteException{
String[] result = text.split(" ", 3);
if(result[0].equalsIgnoreCase("/join")){
channel = result[1];
setChannel(channel);
joinChannel(username, channel);
}
else if(result[0].equalsIgnoreCase("/leave")){
channel = result[1];
setChannel(channel);
leaveChannel(username, channel);
}
else if(result[0].equalsIgnoreCase("/whisper")){
for (int x=2; x<result.length; x++)
newPrivateMessage(username, result[1], result[x]);
}
else if(result[0].equalsIgnoreCase("/exit")){
System.exit(0);
}
else{
error(brukernavn, "Wrong!");
}
return tekst;
}
I need the error to be in red. This message ("Wrong!") goes to the user that wrote something like /dfdsfsd
I get the message up on the screen, but i cant get it in red. Some idea?
EDIT:
Interference:
public interface ChatFront extends Remote {
void error(String to, String message) throws RemoteException;
}
public interface Klient extends Remote {
void error(String to, String message) throws RemoteException;
}
In the server:
class ChatFrontImpl extends UnicastRemoteObject implements ChatFront {
private UserDAO b = new UserDAO();
private Hashtable<String, ArrayList<String>> chanel = new Hashtable<String, ArrayList<String>>();
private ArrayList<Klient> clients= new ArrayList<Client>();
public ChatFrontImpl() throws RemoteException {
}
public void error(String to, String message) throws RemoteException{
errorTo(to, message);
}
private void errorTo(String to, String message) throws RemoteException{
for(Client k: clients){
if(k.findName().equals(to)){
k.error(to, message);
}
}
}
I have edited some of the names (use Norwegian) so this can be a problem for u, but the program works. The only problem is that i cant get red color on the error message
EDIT 2: Forgot the GUI in client:
public class GUI extends javax.swing.JFrame {
GUILogikk gl = new GUILogikk(this);
public void error(String to, String message){
//chatFelt.setCaretColor(Color.RED);
chatFelt.append("" + message + "\n");
chatFelt.setCaretPosition(chatFelt.getText().length());
}
}
If you're using a console window, you'll have to find functions specific to your operating system to set text color. Those functions vary across operating systems, so either reconsider using a console window or address the issue for each system you plan to use your application on. If you're using something like Swing, you can inspect available text color properties associated with the component you're attempting to draw on (setSelectedTextColor(), etc). More here: JTextArea
If you simply want to draw on a Graphics object, you can do the following:
g.setColor(Color.RED);
g.drawString("WRONG!", 32, 32); // text, x, y

How can I customize custom exceptions in Java?

This is the original exception code
public class NoValueForParametarException extends Exception {
private Exception nestedException;
private int errorCode;
public NoValueForParametarException(String message) {
super(message);
}
public NoValueForParametarException(Exception ex,String message) {
super(message);
this.nestedException = ex;
}
public NoValueForParametarException(String message, int errorCode) {
super(message);
this.setErrorCode(errorCode);
}
public Exception getNestedException() {
return this.nestedException;
}
public void setNestedException(Exception nestedException) {
this.nestedException = nestedException;
}
public int getErrorCode() {
return this.errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String toString() {
StringBuffer errorMsg = new StringBuffer();
errorMsg.append("[" + super.getMessage() + "]:");
errorMsg.append((this.nestedException != null) ? ("\n[Nested exception]:" + this.nestedException):"");
return errorMsg.toString();
}
}
and this is the new one
public class NoValueForParametarWebServiceException extends NoValueForParametarException {
public NoValueForParametarWebServiceException(String message) {
super(message);
}
public NoValueForParametarWebServiceException(Exception ex,String message) {
super(message);
this.setNestedException(ex);
}
public NoValueForParametarWebServiceException(String message, int errorCode) {
super(message);
this.setErrorCode(errorCode);
}
public String toString() {
StringBuffer errorMsg = new StringBuffer();
errorMsg.append(super.getMessage());
errorMsg.append((this.getNestedException() != null) ? ("\n[Nested exception]:" + this.getNestedException()):"");
return errorMsg.toString();
}
}
All I need is to change the part of the toString() method so instead of errorMsg.append("[" + super.getMessage() + "]:"); I have errorMsg.append(super.getMessage());. The problem appears when, in a method, the original is thrown because the catch block set to NoValueForParametarWebServiceException doesn't catch the original. I know I could catch the original and just re-throw the new one (which would also be satisfying), but I was wondering if there is another way.
EDIT: It seems what I need is unclear, so to be more clear:
The program throws NoValueForParametarException. I want to catch it but use the toString() method of NoValueForParametarWebServiceException (that is the sole reason of creating the new class) because I need the output format of the new version without changing the old.
I don't see any reason to subclass your first exception. Also, if you get rid of the nestedException instance variable and use java.lang.Throwable's cause instead, you don't have to mess with overriding toString and you can delete most of this code.
The problem appears when, in a method,
the original is thrown because the
catch block set to
'NoValueForParametarWebServiceException'
doesn't catch the original. I know I
could catch the original and just
re-throw the new one (which would also
be satisfying)
You don't need to re throw child exception.
Just catch parent exception in this case.
try{
//your code
}catch(NoValueForParametarException e){
//whatever handling you need to do. suppose you call toString() method
System.out.println(e.toString());
}
In above case catch block will be executed if any of your exceptions are thrown
(NoValueForParametarException or NoValueForParametarWebServiceException).
And depending upon which exception is thrown its toString() method will be called. (Simple inheritance rule) i.e.
NoValueForParametarException is
thrown toString defined in
NoValueForParametarException class
will be called for instance.
And if
NoValueForParametarWebServiceException
is thrown then overriden toString
method from
NoValueForParametarWebServiceException
will be called.
Some tutorials related to exceptions:
http://download.oracle.com/javase/tutorial/essential/exceptions/index.html
http://tutorials.jenkov.com/java-exception-handling/index.html
Hope this helps.

Categories