Java Inetaddress, Swing extends, and throws Exception - java

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
...
}
}

Related

SocketImpl and JUnit/Gradle

I'm trying to make Socks v4 work out of the box in java.net, and I seem to have succeeded!
Roughtly the code that I'm using is this:
class SocketImplFactorySocks4 implements SocketImplFactory {
#Override
public SocketImpl createSocketImpl() {
System.out.println("Socket implementation triggered");
try {
return socketSocks4Factory();
} catch (Exception e) {
e.printStackTrace();
throw new Error("Can't go further");
}
}
private SocketImpl socketSocks4Factory() throws
[...] {
Class<?> aClass = Class.forName("java.net.SocksSocketImpl");
Constructor<?> cons = aClass.getDeclaredConstructor();
if (!cons.isAccessible())
cons.setAccessible(true);
Object socket = cons.newInstance();
Method method = socket.getClass().getDeclaredMethod("setV4");
if (!method.isAccessible())
method.setAccessible(true);
method.invoke(socket);
Field field = socket.getClass().getDeclaredField("useV4");
field.setAccessible(true);
Object value = field.get(socket);
return (SocketImpl) socket;
}
}
Long story short, it works when I create a socket and pass -DsocksProxyHost and -DsocksProxyPort.
My problem is when I use the same code in my junit test, I can check with Reflections that Socket.impl.useV4 is set to true, socksProxy* settings are set systemwide, but when I use my socket, it avoids using proxy altogether (I can see it in wireshark).
It's either JUnit or Gradle, but I've reached my limits. Please advice on where should I go next. build.gradle.kts for reference:
tasks{
test{
systemProperty("socksProxyHost", "localhost")
systemProperty("socksProxyPort", "8080")
}
}
Thanks in advance!
Well, it took me way too much time to figure it out, but I did. My initial goal was to test my Socks v4 server code, but there were two problems on my way:
1) Even though Java Socket has support for Socks v4 as client, it is not enabled by default. And there is no way to flip the toggle.
2) Having solved #1, I tried to write E2E test to smoke the whole thing, but for some reason it was avoiding going into the Socks proxy, even though the toggle (useV4) was true. This is what I came with here on SO.
To solve the first problem, I implemented SocketImplFactory (see above in the question).
What helped to tackle the topic question was my admin background, even though it didn't kick in until recently. :) I separated the original suspects (JUnit and Gradle) and made the test in a standalone psvm file. The test didn't work, it still avoided going through the proxy. And this is when it hit me: exception for localhost!
Basically, there is a hardcoded exception for localhost(127.0.0.1, ::, etc) deep in Java core library. After some searching I came across DsocksNonProxyHosts option. Which didn't help, as you might have guessed already :)
Eventually I ended up at this answer, which mentioned that I might need to implement ProxySelector. Which I did:
static class myProxySelector extends ProxySelector {
#Override
public List<Proxy> select(URI uri) {
List<Proxy> proxyl = new ArrayList<Proxy>(1);
InetSocketAddress saddr = InetSocketAddress.createUnresolved("localhost", 1080);
Proxy proxy = SocksProxy.create(saddr, 4);
proxyl.add(proxy);
System.out.println("Selecting Proxy for " + uri.toASCIIString());
return proxyl;
}
#Override
public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
if (uri == null || sa == null || ioe == null) {
throw new IllegalArgumentException("Arguments can't be null.");
}
}
}
The whole socket setup looks like this:
private void setupSocket() throws IOException {
Socket.setSocketImplFactory(new SocketImplFactorySocks4());
ProxySelector proxySelector = new myProxySelector();
ProxySelector.setDefault(proxySelector);
proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1080));
}
Now everything I wanted works: I'm both able to E2E-test my socks4 code and can do it localhost.

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

ClassNotFoundException with JGroups

I have an issue with JGroups where after building my project, running it produces this error:
Caused by: java.lang.ClassNotFoundException: org.jgroups.ReceiverAdapter
My class looks something like this -
import org.jgroups.ReceiverAdapter;
import org.jgroups.Channel;
import org.jgroups.JChannel;
public class MyClass extends ReceiverAdapter implements MyInterface {
Channel channel;
String state = "state";
public MyClass() {
super();
start();
}
public void start() {
try {
channel = new JChannel();
channel.setReceiver(this);
channel.connect("ServerCluster");
channel.getState(null, 0);
System.out.println("Connected to cluster");
} catch (Exception e) {
System.out.println("Failed to connect to cluster");
}
}
public void getState(OutputStream output) throws Exception {
System.out.println("get response");
}
public void setState(InputStream input) throws Exception {
System.out.println("set test");
}
}
Running the project from IntelliJ produces no errors, but does not produce the desired prints from getState() and setState() either. I tried creating a brand new project in the Eclipse IDE, but the same is happening there too. Connecting has been working fine, states is a new addition to my project.
Running java MyClass from the command line fires the error seen at the start of this question. The JGroups jar seems to be added to the classpath properly as org.jgroups.Channel and org.jgroups.Channel (among others) are being found.
There is a SimpleChat program provided by the JGroup devs, but when I created a new project for this I encountered the same problem.
Edit
So it turns out I have to explicitly set the classpath when running from the CLI. But still, when running the code it seems like the getState() and setState() methods are never called as there are no print statements. SimpleChat doesn't print received state... like it is meant to.
Does anyone have a solution?
Best.
So, I on the JChannel I was using RpcDispatcher and it seems I can't use the dispatcher and the getState() and setState() methods on the same channel. Simple solution: create a second channel. Seems my knowledge on the fundamentals of JGroups is lacking!

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.

chaining constructors in Java without throwing exceptions from the default constructor

I've read this: Can I use throws in constructor? -- which gave me the right idea, and led me to one answer, but was not very explicit. I've also read several others, but could not find my answer. To recap what I've learned for context, essentially, this will not compile...
public ExampleClass(String FileName)
{
this(new FileInputStream(FileName));
}
public ExampleClass(FileInputStream FileStream)
{
DoSomethingToSetupBasedUponFileStream(FileStream);
}
...because the FileInputStream constructor (called from the String Constructor) may throw a FileNotFoundException. You can still create the constructor by making it throw the same exception as follows:
public ExampleClass(String FileName) throws FileNotFoundException
{
this(new FileInputStream(FileName));
}
My question is related to a default constructor (no arguments) that would simply use a default filename String constant:
public ExampleClass() throws FileNotFoundException
{
this(DEFAULT_FILE_NAME);
}
This would chain the constructors as:
ExampleClass() --> ExampleClass(<String>) --> ExampleClass(<InputFileStream>)
In a case like this, is it possible to use a default value (static final class member) in the default constructor, to instantiate (further down the chain) a FileInputStream, but not have to use the throws FileNotFoundException code (which would require someone using the class to either re-throw or handle the exception?
If I could do something like the following, I would handle the exception myself:
public ExampleClass()
{
try
{
this(DEFAULT_FILE_NAME);
}
catch (Exception e)
{
DoSomethingToHandleException(e);
}
}
...However, as far as I know this is not possible, because the "Constructor call must be the first statement in a constructor"
Being more used to .Net at this point, I've never been forced to deal with exceptions if I didn't really want to... :D
Refactor your file construction code out of your constructor, so you could do something like this --
public ExampleClass() {
try {
fileInputStreamMethod(DEFAULT_FILE);
}
catch(Exception e) {
...
}
public ExampleClass(String fileName) throws Exception {
fileInputStreamMethod(fileName);
}
private void fileInputStreamMethod(String fileName) throws Exception {
// your file handling methods
}
You are correct that you cannot catch an exception from the call to this(...).
You could use a static method to produce what you want:
static ExampleClass createDefault()
{
try
{
return new ExampleClass(DEFAULT_FILE_NAME);
}
catch(Exception e)
{
DoSomethingToHandleException(e)
}
}
You could do something like this:
public ExampleClass(String FileName)
{
this(getStream(FileName));
}
private static FileInputStream getStream(String name) {
try {
return new FileInputStream(name);
} catch (Exception e) {
// log error
return null;
}
}
The real question is, why would you not want to throw an exception? How should your program behave if the file cannot be opened? I think it would be unusual that you would want it to proceed as if there were no problem. Quite likely, the null input stream will cause grief later on.
In general, you're better off throwing an exception as close to the source of an error as possible.
Basically what you have to do is do the work that your constructor has to do in a different method(something that's not a constructor) and then use it in the default constructor. But am not sure how useful this technique is in your scenario.
cheers!

Categories

Resources