Confusing Java extend - java

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);

Related

Using broadcast variables in apache spark

I am getting an error while using broadcast variable inside a CoGroupFunction. The error disappears if appProvider.value() is commented. Have you any idea how to solve this issue ? is the error related to the variable definition or initialization ?
public class UsageJobDS implements Serializable{
private static final Logger log = org.apache.log4j.LogManager.getLogger("myLogger");
Broadcast<Provider> appProvider;
void init(){
// init broadcast variable
....
}
public static void main(String[] args) {
UsageJobDS ujb = new UsageJobDS();
ujb.init();
ujb.run();
}
void run(){
KeyValueGroupedDataset<Long, Row> charges = usageCharges.groupByKey(x -> x.getLong(x.fieldIndex("si__subscription_id")), Encoders.LONG());
Dataset<ProcessEdr> cogg = edrs.cogroup(charges, rateEDRs, Encoders.bean(ProcessEdr.class));
log.warn("Count cogg " + cogg.count());
}
CoGroupFunction<Long, EDR2, Row, ProcessEdr> rateEDRs = (subscription_id, edrsIter, chargesIter) -> {
Logger log = org.apache.log4j.LogManager.getLogger("myLogger");
log.warn("inside rateEDRs function");
while (edrsIter.hasNext()) {
appProvider.value(); // HERE
}
return results.iterator();
};
}
and I am getting this error
java.lang.ClassCastException: cannot assign instance of java.lang.invoke.SerializedLambda to field org.opencell.spark.jobs.UsageJobDS.rateEDRs of type org.apache.spark.api.java.function.CoGroupFunction in instance of org.opencell.spark.jobs.UsageJobDS
at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:2233)
at java.io.ObjectStreamClass.setObjFieldValues(ObjectStreamClass.java:1405)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2288)
Actually it works if the cogroup function definition is changed to the below code. However, the error cause still unknown.
Dataset<ProcessEdr> cogg = edrs.cogroup(charges, (subscription_id, edrsIter, chargesIter) -> {
ArrayList<ProcessEdr> results = new ArrayList<>();
System.out.println("App Provider name" + appProvider.value().getIssuer_name());
return results.iterator();
}, Encoders.bean(ProcessEdr.class));

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

java return string from class (linkedhashmap)

Not sure if the title makes sense, but I am trying to return a Success message from a class that receives a linkedhashmap, however eclipse is giving me error when I try to compile the files, offering
Remove arguments to match 'logFile()'
Create constructor 'logFile(Map<String, String>)'
How do set it up to send a Map and revieve a String?
thx
Art
Code corrected as per #Jeff Storey below with error suppression for eclipse
calling class
eventLog.put(stringA,stringB);
logFile logStuff = new logFile();
successRtn = logFile.Process(eventLog);
// Do Stuff with SuccessRtn
logFile class
public class logFile {
static String Success = "Fail";
public static String Process(Map<String, String> eventlog){
// Do Stuff
Success = "Yeh!"
return Success;
}
public static void main(String[] args){
#SuppressWarnings("static-access")
String result = new logFile().Procces(eventLog);
System.out.println("result = " + result);
}
The main method is a special method whose signature must public static void main(String[] args) when being used as an entry point to your application. Create a second method that does the actual work, like this:
public class LogFile {
public String process(Map<String,String> eventLog) {
// do stuff
return success;
}
public void main(String[] args) {
// eventLog will probably be read from a filepath passed into the args
String result = new LogFile().process(eventLog);
System.out.println("result = " + result);
}
}
Note that a lot of your naming conventions are also non standard. Classes should begin with a capital letter and variables should begin with a lower case.

Simple ArrayList question

I have this class:
public class User {
public User(String nickname, String ipAddress) {
nickname = nickname.toLowerCase();
System.out.println(nickname + " " + ipAddress);
}
}
And another class that creates an array containing User objects.
class UserMananger {
static User user;
static User user2;
static User user3;
static ArrayList allTheUsers;
public void UserManager() {
allTheUsers = new ArrayList();
user = new User("Slavisha", "123.34.34.34");
user2 = new User("Zare", "123.34.34.34");
user3 = new User("Smor", "123.34.34.34");
allTheUsers.add(user);
allTheUsers.add(user2);
allTheUsers.add(user3);
}
}
What I want to do is to call a main method that will give me all elements from the list that are type User in format: "nickname ipAddress"
public static void main(String args[]) {
System.out.println(allTheUsers.get(0));
}
For example, this main method should give me something like:
Slavisha 123.34.34.34
but it doesn't. What seems to be the problem?
First problem: you haven't overridden toString() in User. For example:
#Override
public String toString() {
return nickname + " " + ipAddress;
}
Second problem: each time an instance of UserManager is created, you're changing the values of your static variables... but you're not doing anything unless an instance of UserManager is created. One option is to change the constructor of UserManager into a static initializer:
static {
// Initialize the static variables here
}
Third problem: you haven't shown us where your main method is, so we don't know whether it has access to allTheUsers.
Fourth problem: "it doesn't" isn't a good description of your problem. Always say what appears to be happening: are you getting an exception? Is it just printing the wrong thing?

SMack API in 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!

Categories