Created
March 14, 2016 22:38
-
-
Save maleficarum/013ba9abae14938f9655 to your computer and use it in GitHub Desktop.
Telnet 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.apache.commons.net.telnet.TelnetClient; | |
import org.apache.log4j.Logger; | |
import java.io.IOException; | |
import java.net.ConnectException; | |
import java.net.UnknownHostException; | |
/** | |
* Execute a telnet connection to determine if the server and port are accessible. | |
* | |
* @author will | |
*/ | |
public final class TelnetExecutor implements Executor { | |
private static final Logger LOG = Logger.getLogger(TelnetExecutor.class); | |
private static final int PORT_MIN = 0; | |
private static final int PORT_MAX = 65535; | |
private final String _server; | |
private final int _port; | |
public TelnetExecutor(final String server, final int port) { | |
if (server == null || server.trim().length() == 0) { | |
LOG.warn("Server name has a length of zero. Status result will fail."); | |
_server = null; | |
} else { | |
_server = server; | |
} | |
if (port < PORT_MIN || port > PORT_MAX) { | |
LOG.warn("Server port is out of bounds. Status result will fail."); | |
_port = -1; | |
} else { | |
_port = port; | |
} | |
} | |
/** | |
* Determine the result of the port request. | |
* <p/> | |
* A return value of <code>Success</code> indicates successful connection, <code>Error</code> indicates a | |
* configuration problem, <code>Fail</code> indicates a failed connection, and <code>Unknown</code> indicates an | |
* unexpected problem. | |
* | |
* @return A {@link Status} representing the result. | |
*/ | |
@Override | |
public Status getResult() { | |
if (_server == null || _port < 0) { | |
return Status.ERROR; | |
} | |
Status status; | |
final TelnetClient telnetClient = new TelnetClient(); | |
try { | |
telnetClient.connect(_server, _port); | |
telnetClient.disconnect(); | |
status = Status.SUCCESS; | |
} catch (ConnectException ce) { | |
LOG.info("Could not connect to server '" + _server + "' _port " + _port); | |
status = Status.FAIL; | |
} catch (UnknownHostException e) { | |
LOG.error("Unknown host: " + _server); | |
status = Status.ERROR; | |
} catch (IOException e) { | |
LOG.error("Error connecting to server: " + _server + " - " + e.getMessage(), e); | |
status = Status.UNKNOWN; | |
} | |
return status; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment