BasicQuagent.java

import java.net.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.util.*;
import java.util.regex.*;

public class BasicQuagent {

    protected LinkedList event_list=new LinkedList();
    private QuagentSocket socket;
    private static Pattern pattern;

    public BasicQuagent (SocketChannel s) {

	socket = new QuagentSocket(s);
	pattern = Pattern.compile("\\(([^\\)]+)\\)");

    }

    public Request send(Request req) {

	// don't forget the trailing \n
	System.out.println("Sending: "+req);
	socket.sendString(req.toString()+"\n");
	return req;
    }

    public void getGreeting() {
	socket.getLine();
    }

    public Response getResponse(Request request) {

	String received = null;
	Response response = null;
	String request_type = null;
	boolean matched = false;

	if(request == null)
	    matched = true;

	do {

	    // wait for a response to come
	    do {
		received = socket.receiveString();
	    }while (received.length() < 1);

	    // possibly multiple responses in the socket
	    // break into individual messages
	    String[] message = received.split("\\n");

	    for(int i=0; i<message.length; ++i) {
		System.out.println("Received msg: "+i+" " +message[i]);

		// retrieve and then remove the echoing part

		Matcher matcher = pattern.matcher(message[i]);
		String msg = matcher.replaceFirst("");
		String[] tokens = msg.split("\\s+");

		// keep the echo'ed part
		if(!msg.equals(message[i]) ) {
		    request_type = matcher.group(1);
		}


		if(tokens[0].equals("TELL")) { // it's an event

		    event_list.add(new QuagentEvent(tokens));

		} else {

		    // if not "TELL", request_type must not be null

		    // check if the response it what we expected
		    if(request_type.equals(request.toString()))
			matched = true;

		    // create specific response according to the request
		    if (request_type.indexOf("ASK RADIUS") != -1)
			response = new RadiusResponse();
		    else if(request_type.indexOf("DO GETWELLBEING") != -1)
			response = new WellbeingResponse();
		    else
			response = new Response();

		    if(tokens[0].equals("OK")) {
			response.isOK(true);
			response.setValue(tokens);
		    }else {
			response.isOK(false);
		    }
		}
	    }

	}while (!matched);

	return response;
    }

    public void run() {
	System.out.println("BasicQuagent's running.");
    }

    public void handleEvent() {
	System.out.println("Event's coming.");
    }

}


Generated by GNU enscript 1.6.1.