1

I'm relatively new to Java and I'm writing an application to interrogate an Apache HTTP server's access_log file; with this, I want to submit the IP Addresses individually (probably via the Apache HTTPClient library) to another Java instance on another server (as the Web server does not have FTP enabled) to pull some log files. At the moment I've managed to bumble my way through modifying a 'tail -f' equivalent class to suit the programs needs and then manipulate that data to get the IP Addresses that I need to do something with - I even managed to make the 'tail' class threaded so it could address multiple periods of time!

With that said, I want to use a for loop to iterate through each entry in my computerRebootList String Array and with each address create a thread to perform some more work but all I can think of is this;

for (String tmpIpAddress : computerRebootList ) {
            ComputerIpHandler handler = new ComputerIpHandler();
        }

and then create another class named ComputerIpHandler like so;

public class KioskIpHandler implements Runnable {
    static final Logger logger = LogManager.getLogger( ComputerIpHandler.class );

    @Override public void run() {
        //do some code
    }

    public static void main(String computerIp) {
        Thread mainThread = new Thread(new ComputerIpHandler());
        mainThread.start();

        try {
            logger.info("log some stuff");
            mainThread.join();
            logger.info("yay it's done");
        }
        catch (InterruptedException errInterrupted) {
            logger.error(errInterrupted.getMessage());
            logger.error(errInterrupted.getStackTrace());
        }
    }
}

I read somewhere about ensuring that I need to manage resource limitations so I would have to create a maximum number of threads - arguably I could send something like 10 IPs to this class and then have the rest of the addresses 'queue' until the one has returned... I'm just not confident or fluent enough to be able to conceptualise these ideas.

EDIT: I omitted that I am restricted to Java 1.6 as this is the maximum compatible version of the JRE that we can use on this server - not sure if that hinders this effort somewhat...

Can anyone point me in the right direction?

Fredulom
  • 908
  • 1
  • 10
  • 23
  • Have you checked the answer in this question? http://stackoverflow.com/questions/877096/how-can-i-pass-a-parameter-to-a-java-thread?rq=1 – Mohamed Taher Alrefaie Feb 22 '16 at 15:01
  • 1
    This tutorial is a good start to learn how to use thread pools instead of separate threads for better management of resources. http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/ – Mohamed Taher Alrefaie Feb 22 '16 at 15:02
  • 2
    Take a look at [`ExecutorService`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) and its friends. – bradimus Feb 22 '16 at 15:15
  • You could also just install java 1.8 (which I'm assuming you've done already) on the server, and create a Server class to use java's FTP connections. In the java.net package, there is even a class called 'ServerSocket' that creates a socket on the specified port. Assuming you understand sockets and ports, you should agree this will be easier in the long run. –  Feb 22 '16 at 15:20
  • @Jared Massa, I completely omitted to mention but I am unfortunately limited to Java 1.6 as this is the maximum compatible version that the server's software can handle (the solution has been bought from another company and it cannot run on a newer JRE). – Fredulom Feb 22 '16 at 15:25
  • 1
    @Fredulom that should work fine, the java Socket class and ServerSocket class have been in since Java 1.0. If you don't have experience using custom FTP connections in Java, I can link some tutorials and give a brief summation in an answer (if you'd like). –  Feb 22 '16 at 15:27
  • @Jared that would be much appreciated :) – Fredulom Feb 22 '16 at 15:57

2 Answers2

2

Check ScheduledThreadPoolExecutor and ScheduledExecutorService classes in package java.util.concurrent in java API. Those and some other classes in that package would manage all resources for you. They are available in java since version 1.5

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36
  • Thanks @Michael, this looks like exactly what I'm looking for :) – Fredulom Feb 22 '16 at 15:35
  • @Fredulom - Did you want to get a built in ability to schedule tasks with delay or run periodically? If yes, then you may want to use ScheduledThreadPoolExecutor. But if you are just looking for Plain Thread Pool, I would recommend ExecutorService. – The Roy Feb 22 '16 at 16:38
  • @DROY, what I want to do is to iterate through an arraylist of IP address strings and, for each address, call a class to execute a set of commands using the IP Address as a parameter. Judging from what I've read about Executors, I believe that a FixedThreadPool Executor is what I'm after as this allows me to queue jobs if necessary. – Fredulom Feb 23 '16 at 08:15
0

I recommend using Java's built in FTP connection platform to make a thread for continually receiving data on a specified port, until it receives a termination key.

Basically, one class will create a ServerSocket (open socket on server) and upon connection with another socket (the client socket) it would create a new thread for receiving information.

public class Server {
    public ServerSocket ss;
    public Socket clientSocket;
    public Thread receiveingThread;
    public BufferedReader inFromClient = null;
    public boolean running = false;

    public Server(int port) {
        try {
            ss = new ServerSocket(port);
            startReceiving();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public synchronized void startReceiving() {
        receiveingThread = new Thread("Recieve") {
            public void run() {
                String dataFromClient = new String("");
                while (running) {
                    try {
                        inFromClient = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                        dataFromClient = inFromClient.readLine();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (dataFromClient.equals("TERMINATOR_KEY") {
                        stopRecieving();
                    }
                    else if(!dataFromClient.equals("")) {
                        //add item to array
                    }
                }
            }
        };
        receiveingThread.start();
    }

    public synchronized void stopReceiving() {
        try {
            running = false;
            receivingThread.join();
            ss.close();
            clientSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

    public static void main(String[] args) {
        new Server(yourPortHere);
    }
}

then the client class would look something like:

public class Client {
    public Socket socket;
    public Thread send;
    public Client(string serverPublicIP, int port) {
        try {
            socket = new Socket(serverPublicIP, port);
            send("some IP address");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void send(String toSend) {
        send = new Thread("Send") {
            public void run() {
                PrintWriter outToServer;
                try {
                    outToServer = new PrintWriter(new   OutputStreamWriter(socket.getOutputStream()));
                    outToServer.print(toSend);
                    outToServer.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    outToServer.close();
                }
            }   
        };
        send.start();
    }
    public static void main(String[] args) {
        new Client("127.0.0.1", yourPortHere);
    }
}

This is the link for the start of socket tutorials on the oracle site.

This is the Oracle Documentation for java.net.ServerSocket

This is the Oracle Documentation for java.net.Socket