How to automatically initialize a static variable that call InetAddress.getLocalHost()? - java

following this short tutorial http://www.rgagnon.com/javadetails/java-0095.html I am trying to get my client IP Address.
The only difference from the tutorial is that I want that my IP address is put inside a static variable so I do in the following way:
private static InetAddress thisIp = InetAddress.getLocalHost();
But Eclipse give me the following error message: Unhandled exception type UnknownHostException
So, I think, that the problem is that I can't call this code:
InetAddress.getLocalHost();
into a static variable but I have first to declare the static variable and then initialize it into every method that use it.
The problem that I need it into a JUnit test and this is very bad initialize it every time into all #test method !!!
So, what can I do to avoid initializing it in every test method? There is some other way to initialize it only once? Can I create a initialization method that will automatically execute at the beginning when I run my test class? How?
Tnx
Andrea

Try to initialize on static block,
private static InetAddress thisIp;
static{
try {
thisIp = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
}
}

You can use a static initialization block:
class YourClass {
private static InetAddress thisIp;
static {
try {
thisIp = InetAddress.getLocalHost();
} catch(Exception ex) {
Logger.log(ex);
} finally {
...
}
}
...
}
This block can go at any point in the class, outside of any method.

Related

Resetting OutputStream so updated variables send

I've come across an issue when sending an object over a local connection. The object will send the first time as expected. However variables of the object are constantly being changed therefore need to be updated when sending to the other connection. This is done through sending messages prompting the other client to listen and wait for the object being sent.
I'm aware that the java.io.ObjectOutputStream.reset() method exists but keep getting the following error:
error: cannot find symbol
output.reset();
Here's how the code is currently structured (Minus lots of non relevant code):
import java.net.*;
import java.util.*
import java.io.*;
public class Client
{
private static Socket cSocket = null;
private static ObjectOutput output = null;
private static Person myPerson = null;
private static String serverHost = "localhost";
public void Run()
{
// Declaring the output
output = new ObjectOutputStream(
cSocket.getOutputStream()
);
}
private static void sendPerson()
{
try
{
output.writeObject( myPerson );
output.reset();
} catch (Exception e)
{
}
}
}
TLDR: Each time sendPerson() is called the other client receives the first object sent to the other client rather than the updated variables. Tried using reset(); but error is thrown.
Would just like the objects updated variables to be sent rather than the initial object always being sent.
To use ObjectOutputStream#reset you have to define your field with such type.
Not ObjectOutput, but ObjectOutputStream.
Like this:
private static ObjectOutputStream output = null;

Java: Cannot initialize InetAddress

I can't seem to be able to initialize InetAddress object for some reason, I looked at the documentation and it is exactly as how I use it.
InetAddress firstMachineAddress = InetAddress.getByName("129.26.70.95");
InetAddress secondMachineAddress = InetAddress.getByName("129.26.70.108");
And Eclipse says:
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor
What the heck is wrong?
Your code seems to be in a class's constructor which is extended by another class, like so:
import java.net.*;
class SuperclassWithUnknownHostException {
public SuperclassWithUnknownHostException() throws UnknownHostException {
InetAddress firstMachineAddress = InetAddress.getByName("129.26.70.95");
InetAddress secondMachineAddress = InetAddress.getByName("129.26.70.108");
}
}
class SubclassCannotHandleException extends SuperclassWithUnknownHostException {
}
You need to add a default constructor to the subclass which throws the exception:
class SubclassCannotHandleException extends SuperclassWithUnknownHostException {
public SubclassCannotHandleException() throws UnknownHostException {
}
}
Are you handling the UnknownHostException thrown by the method you call?
InetAddress firstMachineAddress;
try {
firstMachineAddress = InetAddress.getByName("129.26.70.95");
} catch (UnknownHostException e) {
// print exception, throw error,
// try something else etc.
}
The inetAddress object throws an exception for one, so you will need to wrap a try-catch around it or have your method throw an exception as well. Also I believe you are getting the error because there is an exception coming back that you are not handling. The getByName() method uses the a string parameter of the name of the webaddress like www.google.com or www.amazon.com and so forth.
try{
InetAddress Address = InetAddress.getByName("www.google.com");
System.out.println(Address);
}catch(UnknownHostException e){
e.printStackTrace();
}
This displays www.google.com/64.233.177.147

Class body - Call function to instantiate variable (unhandled exception type)

I'm having a small issue with my java code.
public class test {
static char[] pass = getMac(); // getting error on this line
public static char[] getMac() throws UnknownHostException
{
...code...
return x;
}
}
I am already throwing the exception in the method but i'm getting the error on this line too :
static char[] pass = getMac(); // getting error on this line
unhandled Exception Type : unknownHostException
is there any way to fix this ?
Thanks
I have tried :
try
{
static char[] pass = getMac();
}
catch (UnknownHostException e)
{
.....
}
but it doesn't work in the main class .
I am already throwing the exception in the method...
Right. That's the problem. By saying that the method throws that exception, you're forcing the calling code to handle it. Java's class initialization code isn't going to handle it for you, so you're getting an unhandled exception error.
Either handle it in the method, or defer initializing that static field until a time when you can handle it*. Note that static initializer blocks are allowed to include flow logic, so that's also an option.
Handling it in the method:
public static char[] getMac()
{
try {
// ...
return x;
}
catch (UnknownHostException e) {
// Appropriate handling
return null; // Or whatever's appropriate
}
}
Using a static initializer block:
public class test {
static char[] pass;
static {
try {
// ...
pass = x;
}
catch (UnknownHostException e) {
// Appropriate handling
pass = null; // Or whatever's appropriate
}
}
}

java.rmi.NotBoundException

i have written small RMI chat program and its compiling properly.but when i try to run Client program it results exception "java.rmi.NotBoundException - ServerInterface"
Server program runs without any errors..please help me to solve this.
here is some of Client code
public static void main (String[] args)
{
String address = "rmi://localhost/ServerInterface";
try
{
ServerInterface si= (ServerInterface) Naming.lookup(address);
new Thread(new Client(si)).start();
}
catch (Exception e)
{
System.err.println(e.toString()) ;
}
}
It looks like you are attempting to look up a name that is not bound.
public class NotBoundException extends Exception
A NotBoundException
is thrown if an attempt is made to lookup or unbind in the registry a
name that has no associated binding.
A NotBoundException is thrown if an attempt is made to lookup or unbind in the registry a name that has no associated binding.
What is your server code look like? This exception you are having most likely caused by server not set up properly.
I think in your server code you are bind with name ChatServer
Naming.rebind("ChatServer", new Server());
But in your client code you are using ServerInterface name
String address = "rmi://localhost/ServerInterface";
For more details Naming
Just make sure your registry.rebind(ClassName.class.getSimpleName(), new ClassImplementaion()) is match to your ClassImplementation.

Java Inetaddress, Swing extends, and throws Exception

In a project that I'm current working on, I'm using Eclipse with the Jigloo Gui Builder.
The builder creates the class with this class line:
public class ChatServer extends javax.swing.JFrame {
String fromclient;
String ToClient;
String serverName = InetAddress.getLocalHost().getHostAddress();
String clientName = "";
...
But Inetaddress gives an error that says "Unhandled exception type UnknownHostException".
Looking through one of the other tutorial codes that I'm trying to learn off, it has the "throws Exception" on the main class. I need it to have a "throws Exception" in the public class ChatServer because I require it to be a variable throughout the whole program.
Does anyone know the proper syntax or another alternative?
Sorry to all, but I'm pretty new to Java.
Put the assignment of serverName in the constructor of ChatServer, where you either try-catch the exception yourself and do something appropriate or let the constructor throw an UnknownHostException (if possible). Maybe there is a constructor already in the class? If not, specify one with for example:
public ChatServer() {
try {
serverName = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ex) {
// Maybe set serverName to something default
...
}
}

Categories

Resources