ConnectionThread.java :  » Testing » jacareto » jacareto » cleverphl » connection » Java Open Source

Java Open Source » Testing » jacareto 
jacareto » jacareto » cleverphl » connection » ConnectionThread.java
/*
 * Jacareto Copyright (c) 2002-2005
 * Applied Computer Science Research Group, Darmstadt University of
 * Technology, Institute of Mathematics & Computer Science,
 * Ludwigsburg University of Education, and Computer Based
 * Learning Research Group, Aachen University. All rights reserved.
 *
 * Jacareto is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * Jacareto is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with Jacareto; if not, write to the Free
 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

package jacareto.cleverphl.connection;


import jacareto.cleverphl.CleverPHL;
import jacareto.cleverphl.session.Session;
import jacareto.record.RandomAccessRecord;
import jacareto.record.RecordException;
import jacareto.record.RecordTools;
import jacareto.record.Recordable;
import jacareto.record.XMLStreamRecord;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

import java.net.Socket;

import java.util.Iterator;

/**
 * This class implements a thread that connects with a given socket. The sockets output stream is
 * read and depending on the value, the thread undertakes action. This "connection" reads the
 * first line of it's input stream expecting one of two "requests":  This can be either a
 * "SEND_RESULT" or "LOAD_RECORD" request. On a "SEND_RESULT" request, the thread will respond by
 * sending the current session record in  XML format to the client and then will quit. On a
 * "LOAD_RECORD" request, the thread will continue to read from it's input stream expecting a
 * valid jacareto record in XML format, which it will load to the actual session.
 *
 * @author uak <a href="mailto:cspannagel@web.de">Christian Spannagel</a>
 * @version 1.02
 */
public class ConnectionThread extends Thread {
    /** The CleverPHL object this thread belongs to. */
    private CleverPHL cleverPHL;

    /** The socket this thread uses to communicate with the client. */
    private Socket socket = null;

    /**
     * Default constructor.
     *
     * @param socket the socket to communicate with
     * @param cleverPHL the cleverPHL object
     */
    public ConnectionThread (Socket socket, CleverPHL cleverPHL) {
        super("ConnectionThread");
        this.socket = socket;
        this.cleverPHL = cleverPHL;
    }

    /**
     * The run method of the thread. Action is taken depending on data from the input stream.
     */
    public void run () {
        try {
            // Establishing the connection channels
            PrintWriter out = new PrintWriter(socket.getOutputStream (), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream ()));
            OutputStream stream = socket.getOutputStream ();

            String inputLine;
            inputLine = in.readLine ();

            // Now check kind of incoming request:
            // SEND_RESULT request are processed here 
            if (inputLine.equals ("GET_RECORD_FROM_SERVER")) {
                // Let's get the current session record
                RandomAccessRecord record = cleverPHL.getSessionList ().getActual ().getRecord ();
                XMLStreamRecord streamRecord = new XMLStreamRecord(cleverPHL.getEnvironment (),
                        socket.getOutputStream (), "XMLRecord", XMLStreamRecord.INIT_CUSTOM,
                        cleverPHL.getSessionList ().getActual ().getSessionClassLoader ());

                // create the XML elements out of the data
                try {
                    streamRecord.open ();

                    if (! record.isOpen ()) {
                        record.open ();
                    }

                    RecordTools.write (record, streamRecord);
                    record.close ();
                    streamRecord.close ();
                } catch (RecordException e1) {
                    e1.printStackTrace ();
                }

                streamRecord.getOutput ();

                // write the data to the client over the stream
                Iterator it;

                try {
                    it = streamRecord.iterator ();

                    while (it.hasNext ()) {
                        Object helper = it.next ();

                        if (helper != null) {
                            if (streamRecord.getSelectionConverter ().handlesElement ((Recordable) helper)) {
                                streamRecord.getSelectionConverter ().convertElement ((Recordable) helper);
                            }
                        }
                    }
                } catch (RecordException e2) {
                    e2.printStackTrace ();
                }
            }
            // SEND_RESULT request are processed here 
            else if (inputLine.equalsIgnoreCase ("SEND_RECORD_TO_SERVER")) {
                // process the input
                // try to receive a document object from the input stream
                Document doc = new Document();
                SAXBuilder builder = new SAXBuilder();

                try {
                    doc = builder.build (in);
                } catch (JDOMException e1) {
                    e1.printStackTrace ();
                }

                Element root = doc.getRootElement ();

                //Check whether input is a valid xml record
                if (root.getName ().equals ("JacaretoRecord")) {
                    cleverPHL.getLogger ().info ("Validated input. Trying to load data.");

                    try {
                        Session actualSession = cleverPHL.getSessionList ().getActual ();

                        XMLStreamRecord streamRecord = new XMLStreamRecord(cleverPHL.getEnvironment (),
                                stream, "XMLRecord", XMLStreamRecord.INIT_CUSTOM,
                                cleverPHL.getSessionList ().getActual ().getSessionClassLoader ());
                        streamRecord.openFromDocument (doc);

                        //get the actual session's record and clear it
                        RandomAccessRecord record = actualSession.getRecord ();

                        if (! record.isOpen ()) {
                            record.open ();
                        }

                        if (! record.isEmpty ()) {
                            record.clear ();
                        }

                        // and finally load it to the current session
                        RecordTools.write (streamRecord, record);

                        actualSession.restructureRecord ();

                        cleverPHL.getLogger ().info ("Loaded record from stream.");
                    } catch (RecordException r) {
                        cleverPHL.getLogger ().error ("Unable to load record.");
                    }
                } else {
                    cleverPHL.getLogger ().error ("Input is not a valid XML Record. Unable to load data.");
                }
            } else {
                cleverPHL.getLogger ().error ("Unknown request: " + inputLine);
                out.println ("Unknown request: " + inputLine);
            }

            // now close the connection
            out.close ();
            in.close ();
            socket.close ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.