Having trouble sending one password attempt at a time (Java) - java

I am trying to do an extra credit assignment for my Java class where we are attempting to hack into a server. The problem I am having right now is only sending one password at a time:
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
private Socket socket;
private PrintWriter out;
private BufferedReader in;
private static int passwordLength;
private static String attempt;
private static int counter = 0;
private static String acceptable = "ABCDEFGHIJKLMNOPQRSTUVWXYXZabcdefghijklmnopqrstuvwxyz0123456789";
public Client()
{
try
{
System.out.println("Connecting to server...");
socket = new Socket("localhost", 58999);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e)
{
System.out.println("Run the server first.");
}
}
public void close()
{
try
{
socket.close();
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
public String sendPassword(String pass)
{
if (!HUSH) System.out.print("Sending: " + pass);
out.println(pass);
String result = null;
try
{
result = in.readLine();
if (!HUSH)
{
if (result.equals("no"))
System.out.println(" (wrong password)");
else if (result.equals("yes"))
System.out.println(" (CORRECT!)");
}
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
return result;
}
public static boolean HUSH = false;
public static void main(String[] args)
{
Client me = new Client();
//BEGIN YOUR WORK
int length;
HUSH = false; //change this to false for testing
System.out.println("Input character length");
Scanner ui = new Scanner(System.in);
length = ui.nextInt();
Client(length);//set the max length of the password
generate();//pull into the first generate method
me.sendPassword("1234");
me.sendPassword(attempt); //the first password i am trying to break
me.sendPassword("letmein");
me.sendPassword("willthiswork");
// END YOUR WORK
me.close();
}
public static void Client(int max)
{
passwordLength = max;
}
public static void generate()
{
generate(""); //enters generate(String password)
}
static void generate(String password)
{
//base case
if(password.length() == passwordLength)//if password is long enough
System.out.println(++counter + " " + password);
else
for(int x = 0; x < acceptable.length(); x++)
generate(attempt = password + acceptable.charAt(x));
}
}
When I run the code (using the server that is supplied), it runs every possible password combination, but returns 9 (passwordLength number of times) instead of sending say..... A (wrong password) B (wrong password) so on and so forth. I know I need to add something onto my for loop to call it back to main, but I'm not sure how to.

Related

Entering an only alphanumeric string runs into a java.lang.IndexOutOfBoundsException but works like intended otherwise

I get an error when I try to type a password consisting only alphanumeric characters but loops the way I intended if I type symbols. This is my first time trying to make a program that writes and reads a file and I'm still stuck here. I tried to paste the entire code to a different class but still runs into the same situation. I have no clue what caused this error. The IDE I'm currently using is Eclipse.
The full error is:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 1 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
TaskPerf6.main(TaskPerf6.java:66)
Source:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
public class TaskPerf6 {
public static boolean isAlphaNumeric(String username) {
return username != null && username.matches("^[a-zA-Z0-9]*$");
}
public static boolean isAlphaNumeric1(String password) {
return password != null && password.matches("^[a-zA-Z0-9]*$");
}
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("Type L to log-in or R to register.");
String choice = scan.nextLine();
File file = new File("records.txt");
FileWriter writer = new FileWriter(file);
//Register
if (choice.compareToIgnoreCase("R") == 0) {
System.out.println("Registration:");
while(true) {
try {
System.out.println("Write your username (Alphanumeric Characters Only):");
String username = scan.nextLine();
if (isAlphaNumeric(username)==true) break;
writer.write(username + "\n");
writer.close();
}
catch (java.lang.IndexOutOfBoundsException e) {
System.out.println("a");
}
catch (java.io.IOException e) {
System.out.println("");
}
}
while(true) {
try {
System.out.println("Write your password (Alphanumeric Characters Only):");
String password = scan.nextLine();
if (isAlphaNumeric1(password)==true) break;
writer.write(password + "\n");
writer.close();
}
catch (java.lang.IndexOutOfBoundsException e) {
System.out.println("a");
}
catch (java.io.IOException e) {
System.out.println("");
}
}
String line1 = Files.readAllLines(Paths.get("records.txt")).get(1);
}
}
}
You do not need two of the same methods; delete one of the isAlphaNumeric methods.
public static boolean isAlphaNumeric(String word) {
return word != null && word.matches("^[a-zA-Z0-9]*$");
}
Your problem is here:
String line1 = Files.readAllLines(Paths.get("records.txt")).get(1);
you are attempting to retrieve the second line of this file from the .get(1), when you have not wrote anything to the file.
The reason why you are not writing to a file is because you are using break whenever the username and password matches your regex pattern.
if (isAlphaNumeric(username)==true) break;
writer.write(username + "\n");
writer.close();
which will take you out of the while loop before you can write to the file.
You should practice breaking up your code for reusability. Very helpful: here is my solution for your task.
public class TaskPerf6 {
static String fileName = "records.txt";
static File file = new File(fileName);
static Scanner scan = new Scanner(System.in);
static final String REGISTER = "R";
static final String LOGIN = "L";
public static void main(String[] args){
System.out.println("Type L to log-in or R to register.");
String choice = scan.nextLine();
switch(choice.toUpperCase()) {
case REGISTER:
register();
break;
case LOGIN:
login();
break;
}
String line1 = getLineItem(0);
System.out.println(line1);
}
private static void login() {
// TODO
}
private static void register() {
while(true) {
System.out.println("Write your username (Alphanumeric Characters Only):");
String username = scan.nextLine();
if (processed(username))
break;
}
while(true) {
System.out.println("Write your password (Alphanumeric Characters Only):");
String password = scan.nextLine();
if (processed(password))
break;
}
}
private static boolean processed(String word) {
boolean success = true;
if (isAlphaNumeric(word)) {
if (!writeToFile(word)) {
System.out.println("Was unable to write to file");
success = false;
}
} else {
System.out.println("Was not alphanumeric, try again");
success = false;
}
return success;
}
private static boolean isAlphaNumeric(String word) {
return word != null && word.matches("^[a-zA-Z0-9]*$");
}
private static boolean writeToFile(String word ) {
boolean success = true;
try {
FileWriter writer = new FileWriter(file);
writer.write(word + "\n");
writer.close();
} catch (IndexOutOfBoundsException | IOException e) {
success = false;
}
return success;
}
private static String getLineItem(int i) {
String item = "";
try {
item = Files.readAllLines(Paths.get(fileName)).get(i);
} catch (IOException e) {
e.printStackTrace();
}
return item;
}
}
first change to be done might be not closing writer in the first loop for username but in second loop for password.
while(true) {
try {
System.out.println("Write your username (Alphanumeric Characters Only):");
String username = scan.nextLine();
if (isAlphaNumeric(username)==true){
System.out.println("username correct");
writer.write(username+"\n");
break;}
} catch (java.lang.IndexOutOfBoundsException e) {System.out.println("a");}
catch (java.io.IOException e) {System.out.println("");}
}
while(true) {
try {
System.out.println("Write your password (Alphanumeric Characters Only):");
String password = scan.nextLine();
if (isAlphaNumeric1(password)==true){
System.out.println("pass correct");
writer.write(password);
writer.close();
break;
}
}
catch (java.lang.IndexOutOfBoundsException e) {System.out.println("a");}
catch (java.io.IOException e) {System.out.println("");}
}
When record.txt cannot be found and you try to get index 1 that's why you're getting the index out of bound exception. Please use the following if check:
String line1;
if(!Files.readAllLines(Paths.get("records.txt")).isEmpty())
line1 = Files.readAllLines(Paths.get("records.txt")).get(1);

File transfer Client to Client in JAVA

I need to implement a program to transfer files. I decided to make it using a chat template I've made about 1 month ago so I would have a chat with file transfer option.
The transfer should follow the following points:
1- Server only keeps a list of all files provided by connected clients (No file are actually located in the server, only their names)
2- Client "1" requests file "A" then:
if file "A" is located ONLY in client "2", then client "2" should send 100% of the file to client "1"
if file "A" is located in client "2" and client "3" also has file "A", then client "2" should send 50% of the file to client "1" and client "3" should send the other 50%.
(if the file is located in 4 clients it should be 25% each....and so it goes...)
I've already managed to make the server find out which client is requesting the file and which clients have it. But now I'm stuck, I don't know how to make the transfer.
Could someone give me an example of how to do it? or point me through the right direction?
[I'm aware my code has some flaws and I will fix it later, right now I need to make the transfer happen before working on fixes, so please, unless it's related, try to focus on that]
Server:
package tor;
import java.util.*;
import java.io.*;
import java.net.*;
public class Server extends Thread {
private String cname;
private Socket client;
public static Vector<PrintStream> clients;
public static Vector<String> clientnames;
public static Vector<String> archives;
public Server(Socket client) {
this.client = client;
}
public static void main(String[] args) {
clients = new Vector<PrintStream>();
clientnames = new Vector<String>();
archives = new Vector<String>();
try {
ServerSocket server = new ServerSocket(2391);
System.out.println("Server Started!!\n");
while (true) {
Socket client = server.accept();
Server s = new Server(client);
s.start();
}
} catch (IOException e) {
System.out.println("Server could not start ");
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintStream out = new PrintStream(client.getOutputStream());
cname = in.readLine();
System.out.println(cname + " Connected --- SERVER!");
if (cname == null) {
System.out.println("Unknown Name");
return;
}
clientnames.add(cname);
clients.add(out);
connected(" ********** [", cname, "] Connected! **********");
String arq;
int size = in.read();
System.out.println(size);
for (int i = 0; i < size; i++) {
arq = in.readLine();
archives.add(arq);
}
String msg = in.readLine();
String selected;
while (true) {
while (!(msg).equals("/exit") && !(msg).equals("/Exit") && !(msg).equals("/EXIT")) {
if ((msg).equals("/list") || (msg).equals("/List") || (msg).equals("/list")) {
out.println("-------- Archives List --------");
for (int i = 0; i < archives.size(); i++) {
out.println(i+"- "+archives.get(i));
}
out.println("-------- ******************* --------");
msg = in.readLine();
} else if (msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))){
msg = in.readLine();
int gnum = Integer.parseInt(msg);
selected=archives.get(gnum);
returnAll("[", out, "]: ", "idreq");
out.println("1");
reqAll(selected);
// I BELIVE HERE IS THE RIGHT PLACE TO MAKE DE TRANSFER CODE
msg = in.readLine();
} else {
returnAll("[", out, "]: ", msg);
msg = in.readLine();
}
}
msg = in.readLine();
size = Integer.parseInt(msg);
for (int i = 0; i <= size; i++) {
arq = in.readLine();
for(int j=0;j<archives.size();j++) {
if (archives.get(j).equals(arq)) {
archives.remove(j);
}
}
}
returnAll(" ********** [", out, "] disconnected ", " ********** ");
clients.remove(out);
clientnames.remove(cname);
client.close();
break;
}
} catch (IOException e) {
System.out.println("A Client disconnected ");
}
}
// METHOD TO SEND CONNECTION MESSAGE
public void connected(String msg1, String cname, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + msg2);
}
}
// METHOD TO RETURN MESSAGE TO ALL CLIENTS
public void returnAll(String msg1, PrintStream saida, String ac, String msg2) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(msg1 + cname + ac + msg2);
}
}
public void reqAll(String req) throws IOException {
Enumeration<PrintStream> e = clients.elements();
while (e.hasMoreElements()) {
PrintStream message = (PrintStream) e.nextElement();
message.println(req);
}
}
}
Client:
package tor;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Client extends Thread {
private Socket con;
private static boolean done = false;
static ArrayList<String> localArq = new ArrayList<String>();
static int c=0;
public Client(Socket s) {
con = s;
}
public static void main(String[] args) {
try {
String ip;
Scanner s = new Scanner(System.in);
System.out.print("Enter Server's IP: ");
ip =s.next();
Socket con = new Socket(ip, 2391);
PrintStream out = new PrintStream(con.getOutputStream());
System.out.println("Connected to Server!");
System.out.print("Enter your Nickname: ");
BufferedReader scan = new BufferedReader(new InputStreamReader(System.in));
String cname = scan.readLine();
out.println(cname);
String dir="C:\\javator\\"+cname;
Thread t = new Client(con);
t.start();
File folder = new File(dir);
folder.mkdir();
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
localArq.add(listOfFiles[i].getName());
}
}
int size=localArq.size();
out.write(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
String msg;
while (true) {
System.out.print("");
msg = scan.readLine();
if(msg.equals("/ll")) {
System.out.println("-------- LOCAL LIST --------");
for (int i = 0; i < localArq.size(); i++) {
System.out.println(localArq.get(i));
}
System.out.println("-------- ******************* --------");
msg = scan.readLine();
}else if(msg.equals("/exit") || (msg.equals("/Exit")) || (msg.equals("/EXIT"))) {
out.println(msg);
size=localArq.size();
out.println(size);
for(int i=0;i<size;i++) {
out.println(localArq.get(i));
}
}
else if(msg.equals("/get") || (msg.equals("/GET")) || (msg.equals("/Get"))) {
System.out.println("Chose file's number to /get: ");
c++;
}
if (done == true) {
break;
}
out.println(msg);
}
} catch (UnknownHostException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String rmsg;
String req;
while (true) {
rmsg = in.readLine();
if (rmsg == null) {
System.out.println("Connection Terminated");
break;
}else if(rmsg.substring(rmsg.length() - 5).equals("idreq")) {
req = in.readLine();
for(int i=0;i<localArq.size();i++) { //IDENTIFIES WHO OWNS THE REQUESTED FILE
if(localArq.get(i).equals(req)) {
System.out.println("Owns requested file");
Socket requester = new Socket("192.168.3.114", 2007);
ObjectOutputStream outputr = new ObjectOutputStream(requester.getOutputStream());
ObjectInputStream inputr = new ObjectInputStream(requester.getInputStream());
Object mens= inputr.readObject();
System.out.println(mens);
outputr.writeObject("OWNER FOUND");
}
}
if(c==1) { //IDENTIFIES WHO WANTS THE FILE
rmsg = in.readLine();
c= Integer.parseInt(rmsg);
System.out.println("file: "+req);
ServerSocket peer = new ServerSocket(2007);
System.out.println("OPEN FOR CONNECTIONS\n");
Socket client = peer.accept();
System.out.println("Client connected: " + client.getInetAddress().getHostAddress());
ObjectOutputStream outputo = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream inputo = new ObjectInputStream(client.getInputStream());
outputo.flush();
outputo.writeObject("Connected to requester");
Object mens= inputo.readObject();
System.out.println(mens);
}
}
else {
System.out.println(rmsg);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
done = true;
}
}
I was able to make a transfer between two clients easily with the information provided and a little research on stackOverflow to understand more about out/inputStreams!
This post also helped me a lot: Sending a file with Java Sockets, losing data
next step is the shared transfer

FileZilla won't react on commands from my java FTP server

I write my own Java FTP server. Until recently I used PUttY to debug my control telnet connection and everything seemed fine - I had successful two-way communication. Now I try to debug my server with FileZilla, but it does not seem to read my text, nor to send some to server, so it just hangs and wait for something.
Control connection class
public class ControlConnection extends Thread {
private enum OperationMode {
ACTIVE, PASSIVE
}
private final Map<String, Supplier<String>> COMMANDS;
private String[] userTokens;
private User user;
private String userLogin;
private boolean authenticated;
private boolean dataConnected;
private boolean userExists;
private final Socket socket;
private DataInputStream inputStream;
private DataOutputStream outputStream;
private DataConnection ftpSession;
private OperationMode operationMode;
private String errorMessage;
public ControlConnection(Socket socket) {
super(ControlConnection.class.toString());
this.socket = socket;
// constants initialization
authenticated = false;
dataConnected = false;
// commands initialization
COMMANDS = new HashMap<>();
// commands init
}
#Override
public void run() {
try {
inputStream = new DataInputStream(socket.getInputStream());
outputStream = new DataOutputStream(socket.getOutputStream());
sendGreetings();
IOProcessing.writeBytes(outputStream, pasvCommand());;
boolean running = true;
while (running) {
sendGreetings();
String input = IOProcessing.readBytes(inputStream);
if (!(input.equals("")))
System.out.println(input);
if (!checkInput(input))
continue;
userTokens = input.split(" ");
String command = userTokens[0].toUpperCase();
String answer = COMMANDS.get(command).get();
outputStream.writeBytes(answer);
}
}
catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}
private boolean commonCheck() {
// some checks
return true;
}
private String getErrorMessage() {
return errorMessage;
}
public void sendGreetings() {
String greetings = String.format("220 Control connection established: %s", getConnectionInfo());
IOProcessing.writeBytes(outputStream, greetings);
}
public String getConnectionInfo() {
String info = String.format("%s: %d %s",
socket.getInetAddress().toString(), socket.getPort(), user != null ? user.getUsername(): "");
return info;
}
// input/output proccessing functions
public boolean checkInput(String input) {
// checks
return true;
}
// commands functions
private String pasvCommand() {
if (operationMode == OperationMode.PASSIVE) {
errorMessage = "Already in passive mode.%n";
return errorMessage;
}
String answer;
new ListenToSocket().start();
answer = String.format("227 Entering Passive Mode (%s, %d)",
"127.0.0.1", DataConnection.PORT);
operationMode = OperationMode.PASSIVE;
return answer;
}
private class ListenToSocket extends Thread {
public ListenToSocket() {
}
#Override
public void run() {
try {
ServerSocket ftpSocket =
new ServerSocket(DataConnection.PORT);
ftpSession =
DataConnection.getDataConnection(ftpSocket.accept());
if (ftpSession != null) {
ftpSession.start();
dataConnected = true;
String greetings = "Data connection established: " + ftpSession.getConnectionInfo();
IOProcessing.writeBytes(outputStream, greetings);
} else {
dataConnected = false;
}
} catch (IOException e) {
System.out.print(e);
}
}
}
also, server does not get user credentials, entered in FileZilla - input from server is always empty
IOProcessing class
public class IOProcessing {
private static final Charset UTF8_CHARSET;
static {
UTF8_CHARSET = Charset.forName("UTF-8");
}
public static String readBytes(DataInputStream inputStream) {
String result = "";
try {
int len = inputStream.available();
if (len == 0) {
return result;
}
byte[] byteInput = new byte[len];
inputStream.readFully(byteInput, 0, len);
result = new String(byteInput, "UTF-8").trim();
} catch (IOException e) {
System.err.println(e);
}
return result;
}
output FileZlla log
Status: Resolving address of localhost
Status: Connecting to [::1]:21...
Status: Connection established, waiting for welcome message.
You didn't show us the writeBytes. So I can only guess that you are not sending \r\n after the messages sent to the client. Particularly after the welcome message. So FileZilla keeps waiting forever for it, as any FTP client would do.

Insert record to database from a server/client GUI java

Hi i am struggling to get my database to receive a username and ip address from a client instance connecting to a server.
It is a bidding system that initially just lets multiple individual instances of the client bid on 2 items, now I need to add the name (user prompted to enter upon loading client instance) and their ip address to my database.
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null; //null pointer exception fix
Statement statement = null;
String inserSql = null;
Connection sqlLink = null;
final int PORT = 1239;
Socket client = null;
ClientHandler handler = null;
Scanner getTime;
try {
/**
* This piece of code has errors or you maybe did the error
* when copy/paste your code.
* Fixed the DriverManager connection code
*/
sqlLink = DriverManager.getConnection(
"correct info already here);
} catch (SQLException e) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ioEx) {
System.out.println("Unable to set up port!");
System.exit(1);
}
System.out.println("\nUp and running\n");
String currentTime = null;
getTime = new Scanner(System.in);
System.out.println("\nSet time for Ball");
currentTime = getTime.nextLine();
Items BallItem = new Items("Ball", currentTime, "Ball");
System.out.println("\nSet time for Plate");
currentTime = getTime.nextLine();
Items PlateItem = new Items("Plate", currentTime, "Plate");
Bidder bidder = new Bidder(null);
BallItem.start();
PlateItem.start();
Users user = new Users(BallItem, PlateItem);
ArrayList<ClientHandler> userList =
new ArrayList<ClientHandler>();
//add new array for the clients details as stated
ArrayList<String> bidders = new ArrayList<String>();
do {
client = serverSocket.accept();//
System.out.println("Enter username ");//
//takes in bidders name (1.1 and 2.1)
bidders.add(getTime.nextLine());
bidders.add(client.getInetAddress().toString());
//takes in next bidder's ip address to string like in tips (2.2)
Bidder userBidding = new Bidder(bidders);
System.out.println("\nUser" + (user.getUsers() + 1));
user.addUsers(userList, client, handler);
System.out.println(userBidding.returnUsers());
bidder.insert(statement, statement);
}
while (true);
}
}
class Items extends Thread {
private String name, description, timeUp, userBidding = "";
private boolean newBid = true;
private double topBid = 0;
private Calendar start = Calendar.getInstance();
private int date = start.get(Calendar.DATE); //gets the dates
private int month = start.get(Calendar.MONTH);
private int year = start.get(Calendar.YEAR);
private Calendar deadline = Calendar.getInstance();
//time file supplied to help etc
private Calendar now = Calendar.getInstance();
public Items(String newName, String newTimeString,
String newDescription) throws IOException {
String timeString, hourString, minString;
name = newName;
description = newDescription;
timeUp = newTimeString;
timeString = newTimeString;
hourString = timeString.substring(0, 2);
int hour = Integer.parseInt(hourString);
minString = timeString.substring(3, 5);
int minute = Integer.parseInt(minString);
deadline.set(year, month, date, hour, minute, 0); //setting time
}
public void run() {
while (now.before(deadline)) {
System.out.println(name + " " + getDateTime(now));
try {
Thread.sleep(5000); //increased to check server notifications easier
} catch (InterruptedException intEx) {
}
now = Calendar.getInstance();
}
System.out.println("\nDeadline! Times up!");
newBid = false;
}
class Bidder {
private static ArrayList<String> users;
private static Users user = new Users(null, null);
public Bidder(ArrayList<String> newUserList) {
users = newUserList;
}
public ArrayList<String> returnUsers()//return users as in question
{
return users;
}
public static String returnIP()//return ip as in question
{
return users.get(user.getUsers() + 1);
}
static void insert(Statement insert, Statement statement) {
Users user = new Users(null, null);
try {
String insertSql = "INSERT INTO Usernames(id, Name, ipAddress) VALUES (1"
+ users.get(user.getUsers()) + "," + returnIP() + ")";
System.out.println(users.get(user.getUsers()));
statement.executeUpdate(insertSql);
} catch (SQLException sqlEx) {
System.out.println("* Cannot execute insert! *");
sqlEx.printStackTrace();
System.exit(1);
}
}
//remove user as stated in question
public synchronized void RemoveUser(Socket client, int clientUser) {
int index = 0;
for (final String newString : users) {
if (users.indexOf(user.getUsers()) == clientUser) {
try {
client.close();
Thread.currentThread().isInterrupted();
users.remove(index);
} catch (final IOException e) {
System.out.println("Try to leave again!");
System.exit(1);
}
}
index++;
}
}
}
class Users {
private ArrayList<ClientHandler> userList;
private Items Ball;
private Items Plate;
public Users(Items newItem1, Items newItem2) {
Ball = newItem1;
Plate = newItem2;
userList = null;
}
public synchronized int getUsers() {
int totalUsers = 0;
if (userList != null)
for (ClientHandler handler : userList)
totalUsers++;
return totalUsers;
}
}// <-- miss this close brace

Java Telnet Library

I am really not clear on explaining this requirement but what I need basically is a JSP page that connects to a Unix server and gets the word count of a file and displays on the JSP page. I have looked on various questions here but nothing helped. A sample code would be of much help. Thanks
Kavin, I guess you must have found some other solution or moved on by now. However, I just came across a requirement that led me to this page.
I looked through the somewhat smuckish responses on this page and many others but could not find a simple to use Telnet client at all.
I spent a little bit of time and wrote a simple client on top of Commons Net's solution. Please forgive the System.out and System.err in the code, I got it to barely work.
public static void main(String[] args) throws Exception {
SimpleTelnetClient client = new SimpleTelnetClient("localhost", 2323);
client.connect();
String result = client.waitFor("login:");
System.out.println("Got " + result);
client.send("username");
result = client.waitFor("Password:");
System.out.println("Got " + result);
client.send("password");
client.waitFor("#");
client.send("ls -al");
result = client.waitFor("#");
System.out.println("Got " + result);
client.send("exit");
}
Not sure if it will help you anymore, but perhaps it could be a starting point for others.
import java.io.InputStream;
import java.io.PrintStream;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.net.telnet.EchoOptionHandler;
import org.apache.commons.net.telnet.InvalidTelnetOptionException;
import org.apache.commons.net.telnet.SuppressGAOptionHandler;
import org.apache.commons.net.telnet.TelnetClient;
import org.apache.commons.net.telnet.TerminalTypeOptionHandler;
public class SimpleTelnetClient {
static class Responder extends Thread {
private StringBuilder builder = new StringBuilder();
private final SimpleTelnetClient checker;
private CountDownLatch latch;
private String waitFor = null;
private boolean isKeepRunning = true;
Responder(SimpleTelnetClient checker) {
this.checker = checker;
}
boolean foundWaitFor(String waitFor) {
return builder.toString().contains(waitFor);
}
public synchronized String getAndClearBuffer() {
String result = builder.toString();
builder = new StringBuilder();
return result;
}
#Override
public void run() {
while (isKeepRunning) {
String s;
try {
s = checker.messageQueue.take();
} catch (InterruptedException e) {
break;
}
synchronized (Responder.class) {
builder.append(s);
}
if (waitFor != null && latch != null && foundWaitFor(waitFor)) {
latch.countDown();
}
}
}
public String waitFor(String waitFor) {
synchronized (Responder.class) {
if (foundWaitFor(waitFor)) {
return getAndClearBuffer();
}
}
this.waitFor = waitFor;
latch = new CountDownLatch(1);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return null;
}
String result = null;
synchronized (Responder.class) {
result = builder.toString();
builder = new StringBuilder();
}
return result;
}
}
static class TelnetReader extends Thread {
private final SimpleTelnetClient checker;
private final TelnetClient tc;
TelnetReader(SimpleTelnetClient checker, TelnetClient tc) {
this.checker = checker;
this.tc = tc;
}
#Override
public void run() {
InputStream instr = tc.getInputStream();
try {
byte[] buff = new byte[1024];
int ret_read = 0;
do {
ret_read = instr.read(buff);
if (ret_read > 0) {
checker.sendForResponse(new String(buff, 0, ret_read));
}
} while (ret_read >= 0);
} catch (Exception e) {
System.err.println("Exception while reading socket:" + e.getMessage());
}
try {
tc.disconnect();
checker.stop();
System.out.println("Disconnected.");
} catch (Exception e) {
System.err.println("Exception while closing telnet:" + e.getMessage());
}
}
}
private String host;
private BlockingQueue<String> messageQueue = new LinkedBlockingQueue<String>();
private int port;
private TelnetReader reader;
private Responder responder;
private TelnetClient tc;
public SimpleTelnetClient(String host, int port) {
this.host = host;
this.port = port;
}
protected void stop() {
responder.isKeepRunning = false;
responder.interrupt();
}
public void send(String command) {
PrintStream ps = new PrintStream(tc.getOutputStream());
ps.println(command);
ps.flush();
}
public void sendForResponse(String s) {
messageQueue.add(s);
}
public void connect() throws Exception {
tc = new TelnetClient();
TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);
try {
tc.addOptionHandler(ttopt);
tc.addOptionHandler(echoopt);
tc.addOptionHandler(gaopt);
} catch (InvalidTelnetOptionException e) {
System.err.println("Error registering option handlers: " + e.getMessage());
}
tc.connect(host, port);
reader = new TelnetReader(this, tc);
reader.start();
responder = new Responder(this);
responder.start();
}
public String waitFor(String s) {
return responder.waitFor(s);
}
}
Why wouldn't you just use an open source telnet client. There is bound to be several to choose from. Google lists many.

Categories

Resources